(bug-reference-map): Bind down-mouse-1 rather than mouse-1.
[emacs.git] / src / editfns.c
blob192277e429576512445c5bfe7cf2005c6bfb44a8
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985, 1986, 1987, 1989, 1993, 1994, 1995, 1996,
3 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22 #include <config.h>
23 #include <sys/types.h>
24 #include <stdio.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #endif
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
34 #ifdef HAVE_SYS_UTSNAME_H
35 #include <sys/utsname.h>
36 #endif
38 #include "lisp.h"
40 /* systime.h includes <sys/time.h> which, on some systems, is required
41 for <sys/resource.h>; thus systime.h must be included before
42 <sys/resource.h> */
43 #include "systime.h"
45 #if defined HAVE_SYS_RESOURCE_H
46 #include <sys/resource.h>
47 #endif
49 #include <ctype.h>
51 #include "intervals.h"
52 #include "buffer.h"
53 #include "character.h"
54 #include "coding.h"
55 #include "frame.h"
56 #include "window.h"
57 #include "blockinput.h"
59 #ifdef STDC_HEADERS
60 #include <float.h>
61 #define MAX_10_EXP DBL_MAX_10_EXP
62 #else
63 #define MAX_10_EXP 310
64 #endif
66 #ifndef NULL
67 #define NULL 0
68 #endif
70 #ifndef USE_CRT_DLL
71 extern char **environ;
72 #endif
74 #define TM_YEAR_BASE 1900
76 /* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
77 asctime to have well-defined behavior. */
78 #ifndef TM_YEAR_IN_ASCTIME_RANGE
79 # define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
80 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
81 #endif
83 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
84 const struct tm *, int));
86 #ifdef WINDOWSNT
87 extern Lisp_Object w32_get_internal_run_time ();
88 #endif
90 static int tm_diff P_ ((struct tm *, struct tm *));
91 static void find_field P_ ((Lisp_Object, Lisp_Object, Lisp_Object, int *, Lisp_Object, int *));
92 static void update_buffer_properties P_ ((int, int));
93 static Lisp_Object region_limit P_ ((int));
94 int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
95 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
96 size_t, const struct tm *, int));
97 static void general_insert_function P_ ((void (*) (const unsigned char *, int),
98 void (*) (Lisp_Object, int, int, int,
99 int, int),
100 int, int, Lisp_Object *));
101 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
102 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
103 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
105 #ifdef HAVE_INDEX
106 extern char *index P_ ((const char *, int));
107 #endif
109 Lisp_Object Vbuffer_access_fontify_functions;
110 Lisp_Object Qbuffer_access_fontify_functions;
111 Lisp_Object Vbuffer_access_fontified_property;
113 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
115 /* Non-nil means don't stop at field boundary in text motion commands. */
117 Lisp_Object Vinhibit_field_text_motion;
119 /* Some static data, and a function to initialize it for each run */
121 Lisp_Object Vsystem_name;
122 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
123 Lisp_Object Vuser_full_name; /* full name of current user */
124 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
125 Lisp_Object Voperating_system_release; /* Operating System Release */
127 /* Symbol for the text property used to mark fields. */
129 Lisp_Object Qfield;
131 /* A special value for Qfield properties. */
133 Lisp_Object Qboundary;
136 void
137 init_editfns ()
139 char *user_name;
140 register unsigned char *p;
141 struct passwd *pw; /* password entry for the current user */
142 Lisp_Object tem;
144 /* Set up system_name even when dumping. */
145 init_system_name ();
147 #ifndef CANNOT_DUMP
148 /* Don't bother with this on initial start when just dumping out */
149 if (!initialized)
150 return;
151 #endif /* not CANNOT_DUMP */
153 pw = (struct passwd *) getpwuid (getuid ());
154 #ifdef MSDOS
155 /* We let the real user name default to "root" because that's quite
156 accurate on MSDOG and because it lets Emacs find the init file.
157 (The DVX libraries override the Djgpp libraries here.) */
158 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
159 #else
160 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
161 #endif
163 /* Get the effective user name, by consulting environment variables,
164 or the effective uid if those are unset. */
165 user_name = (char *) getenv ("LOGNAME");
166 if (!user_name)
167 #ifdef WINDOWSNT
168 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
169 #else /* WINDOWSNT */
170 user_name = (char *) getenv ("USER");
171 #endif /* WINDOWSNT */
172 if (!user_name)
174 pw = (struct passwd *) getpwuid (geteuid ());
175 user_name = (char *) (pw ? pw->pw_name : "unknown");
177 Vuser_login_name = build_string (user_name);
179 /* If the user name claimed in the environment vars differs from
180 the real uid, use the claimed name to find the full name. */
181 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
182 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
183 : Vuser_login_name);
185 p = (unsigned char *) getenv ("NAME");
186 if (p)
187 Vuser_full_name = build_string (p);
188 else if (NILP (Vuser_full_name))
189 Vuser_full_name = build_string ("unknown");
191 #ifdef HAVE_SYS_UTSNAME_H
193 struct utsname uts;
194 uname (&uts);
195 Voperating_system_release = build_string (uts.release);
197 #else
198 Voperating_system_release = Qnil;
199 #endif
202 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
203 doc: /* Convert arg CHAR to a string containing that character.
204 usage: (char-to-string CHAR) */)
205 (character)
206 Lisp_Object character;
208 int len;
209 unsigned char str[MAX_MULTIBYTE_LENGTH];
211 CHECK_CHARACTER (character);
213 len = CHAR_STRING (XFASTINT (character), str);
214 return make_string_from_bytes (str, 1, len);
217 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
218 doc: /* Convert arg STRING to a character, the first character of that string.
219 A multibyte character is handled correctly. */)
220 (string)
221 register Lisp_Object string;
223 register Lisp_Object val;
224 CHECK_STRING (string);
225 if (SCHARS (string))
227 if (STRING_MULTIBYTE (string))
228 XSETFASTINT (val, STRING_CHAR (SDATA (string), SBYTES (string)));
229 else
230 XSETFASTINT (val, SREF (string, 0));
232 else
233 XSETFASTINT (val, 0);
234 return val;
237 static Lisp_Object
238 buildmark (charpos, bytepos)
239 int charpos, bytepos;
241 register Lisp_Object mark;
242 mark = Fmake_marker ();
243 set_marker_both (mark, Qnil, charpos, bytepos);
244 return mark;
247 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
248 doc: /* Return value of point, as an integer.
249 Beginning of buffer is position (point-min). */)
252 Lisp_Object temp;
253 XSETFASTINT (temp, PT);
254 return temp;
257 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
258 doc: /* Return value of point, as a marker object. */)
261 return buildmark (PT, PT_BYTE);
265 clip_to_bounds (lower, num, upper)
266 int lower, num, upper;
268 if (num < lower)
269 return lower;
270 else if (num > upper)
271 return upper;
272 else
273 return num;
276 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
277 doc: /* Set point to POSITION, a number or marker.
278 Beginning of buffer is position (point-min), end is (point-max).
280 The return value is POSITION. */)
281 (position)
282 register Lisp_Object position;
284 int pos;
286 if (MARKERP (position)
287 && current_buffer == XMARKER (position)->buffer)
289 pos = marker_position (position);
290 if (pos < BEGV)
291 SET_PT_BOTH (BEGV, BEGV_BYTE);
292 else if (pos > ZV)
293 SET_PT_BOTH (ZV, ZV_BYTE);
294 else
295 SET_PT_BOTH (pos, marker_byte_position (position));
297 return position;
300 CHECK_NUMBER_COERCE_MARKER (position);
302 pos = clip_to_bounds (BEGV, XINT (position), ZV);
303 SET_PT (pos);
304 return position;
308 /* Return the start or end position of the region.
309 BEGINNINGP non-zero means return the start.
310 If there is no region active, signal an error. */
312 static Lisp_Object
313 region_limit (beginningp)
314 int beginningp;
316 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
317 Lisp_Object m;
319 if (!NILP (Vtransient_mark_mode)
320 && NILP (Vmark_even_if_inactive)
321 && NILP (current_buffer->mark_active))
322 xsignal0 (Qmark_inactive);
324 m = Fmarker_position (current_buffer->mark);
325 if (NILP (m))
326 error ("The mark is not set now, so there is no region");
328 if ((PT < XFASTINT (m)) == (beginningp != 0))
329 m = make_number (PT);
330 return m;
333 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
334 doc: /* Return position of beginning of region, as an integer. */)
337 return region_limit (1);
340 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
341 doc: /* Return position of end of region, as an integer. */)
344 return region_limit (0);
347 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
348 doc: /* Return this buffer's mark, as a marker object.
349 Watch out! Moving this marker changes the mark position.
350 If you set the marker not to point anywhere, the buffer will have no mark. */)
353 return current_buffer->mark;
357 /* Find all the overlays in the current buffer that touch position POS.
358 Return the number found, and store them in a vector in VEC
359 of length LEN. */
361 static int
362 overlays_around (pos, vec, len)
363 int pos;
364 Lisp_Object *vec;
365 int len;
367 Lisp_Object overlay, start, end;
368 struct Lisp_Overlay *tail;
369 int startpos, endpos;
370 int idx = 0;
372 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
374 XSETMISC (overlay, tail);
376 end = OVERLAY_END (overlay);
377 endpos = OVERLAY_POSITION (end);
378 if (endpos < pos)
379 break;
380 start = OVERLAY_START (overlay);
381 startpos = OVERLAY_POSITION (start);
382 if (startpos <= pos)
384 if (idx < len)
385 vec[idx] = overlay;
386 /* Keep counting overlays even if we can't return them all. */
387 idx++;
391 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
393 XSETMISC (overlay, tail);
395 start = OVERLAY_START (overlay);
396 startpos = OVERLAY_POSITION (start);
397 if (pos < startpos)
398 break;
399 end = OVERLAY_END (overlay);
400 endpos = OVERLAY_POSITION (end);
401 if (pos <= endpos)
403 if (idx < len)
404 vec[idx] = overlay;
405 idx++;
409 return idx;
412 /* Return the value of property PROP, in OBJECT at POSITION.
413 It's the value of PROP that a char inserted at POSITION would get.
414 OBJECT is optional and defaults to the current buffer.
415 If OBJECT is a buffer, then overlay properties are considered as well as
416 text properties.
417 If OBJECT is a window, then that window's buffer is used, but
418 window-specific overlays are considered only if they are associated
419 with OBJECT. */
420 Lisp_Object
421 get_pos_property (position, prop, object)
422 Lisp_Object position, object;
423 register Lisp_Object prop;
425 CHECK_NUMBER_COERCE_MARKER (position);
427 if (NILP (object))
428 XSETBUFFER (object, current_buffer);
429 else if (WINDOWP (object))
430 object = XWINDOW (object)->buffer;
432 if (!BUFFERP (object))
433 /* pos-property only makes sense in buffers right now, since strings
434 have no overlays and no notion of insertion for which stickiness
435 could be obeyed. */
436 return Fget_text_property (position, prop, object);
437 else
439 int posn = XINT (position);
440 int noverlays;
441 Lisp_Object *overlay_vec, tem;
442 struct buffer *obuf = current_buffer;
444 set_buffer_temp (XBUFFER (object));
446 /* First try with room for 40 overlays. */
447 noverlays = 40;
448 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
449 noverlays = overlays_around (posn, overlay_vec, noverlays);
451 /* If there are more than 40,
452 make enough space for all, and try again. */
453 if (noverlays > 40)
455 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
456 noverlays = overlays_around (posn, overlay_vec, noverlays);
458 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
460 set_buffer_temp (obuf);
462 /* Now check the overlays in order of decreasing priority. */
463 while (--noverlays >= 0)
465 Lisp_Object ol = overlay_vec[noverlays];
466 tem = Foverlay_get (ol, prop);
467 if (!NILP (tem))
469 /* Check the overlay is indeed active at point. */
470 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
471 if ((OVERLAY_POSITION (start) == posn
472 && XMARKER (start)->insertion_type == 1)
473 || (OVERLAY_POSITION (finish) == posn
474 && XMARKER (finish)->insertion_type == 0))
475 ; /* The overlay will not cover a char inserted at point. */
476 else
478 return tem;
483 { /* Now check the text properties. */
484 int stickiness = text_property_stickiness (prop, position, object);
485 if (stickiness > 0)
486 return Fget_text_property (position, prop, object);
487 else if (stickiness < 0
488 && XINT (position) > BUF_BEGV (XBUFFER (object)))
489 return Fget_text_property (make_number (XINT (position) - 1),
490 prop, object);
491 else
492 return Qnil;
497 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
498 the value of point is used instead. If BEG or END is null,
499 means don't store the beginning or end of the field.
501 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
502 results; they do not effect boundary behavior.
504 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
505 position of a field, then the beginning of the previous field is
506 returned instead of the beginning of POS's field (since the end of a
507 field is actually also the beginning of the next input field, this
508 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
509 true case, if two fields are separated by a field with the special
510 value `boundary', and POS lies within it, then the two separated
511 fields are considered to be adjacent, and POS between them, when
512 finding the beginning and ending of the "merged" field.
514 Either BEG or END may be 0, in which case the corresponding value
515 is not stored. */
517 static void
518 find_field (pos, merge_at_boundary, beg_limit, beg, end_limit, end)
519 Lisp_Object pos;
520 Lisp_Object merge_at_boundary;
521 Lisp_Object beg_limit, end_limit;
522 int *beg, *end;
524 /* Fields right before and after the point. */
525 Lisp_Object before_field, after_field;
526 /* 1 if POS counts as the start of a field. */
527 int at_field_start = 0;
528 /* 1 if POS counts as the end of a field. */
529 int at_field_end = 0;
531 if (NILP (pos))
532 XSETFASTINT (pos, PT);
533 else
534 CHECK_NUMBER_COERCE_MARKER (pos);
536 after_field
537 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
538 before_field
539 = (XFASTINT (pos) > BEGV
540 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
541 Qfield, Qnil, NULL)
542 /* Using nil here would be a more obvious choice, but it would
543 fail when the buffer starts with a non-sticky field. */
544 : after_field);
546 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
547 and POS is at beginning of a field, which can also be interpreted
548 as the end of the previous field. Note that the case where if
549 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
550 more natural one; then we avoid treating the beginning of a field
551 specially. */
552 if (NILP (merge_at_boundary))
554 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
555 if (!EQ (field, after_field))
556 at_field_end = 1;
557 if (!EQ (field, before_field))
558 at_field_start = 1;
559 if (NILP (field) && at_field_start && at_field_end)
560 /* If an inserted char would have a nil field while the surrounding
561 text is non-nil, we're probably not looking at a
562 zero-length field, but instead at a non-nil field that's
563 not intended for editing (such as comint's prompts). */
564 at_field_end = at_field_start = 0;
567 /* Note about special `boundary' fields:
569 Consider the case where the point (`.') is between the fields `x' and `y':
571 xxxx.yyyy
573 In this situation, if merge_at_boundary is true, we consider the
574 `x' and `y' fields as forming one big merged field, and so the end
575 of the field is the end of `y'.
577 However, if `x' and `y' are separated by a special `boundary' field
578 (a field with a `field' char-property of 'boundary), then we ignore
579 this special field when merging adjacent fields. Here's the same
580 situation, but with a `boundary' field between the `x' and `y' fields:
582 xxx.BBBByyyy
584 Here, if point is at the end of `x', the beginning of `y', or
585 anywhere in-between (within the `boundary' field), we merge all
586 three fields and consider the beginning as being the beginning of
587 the `x' field, and the end as being the end of the `y' field. */
589 if (beg)
591 if (at_field_start)
592 /* POS is at the edge of a field, and we should consider it as
593 the beginning of the following field. */
594 *beg = XFASTINT (pos);
595 else
596 /* Find the previous field boundary. */
598 Lisp_Object p = pos;
599 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
600 /* Skip a `boundary' field. */
601 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
602 beg_limit);
604 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
605 beg_limit);
606 *beg = NILP (p) ? BEGV : XFASTINT (p);
610 if (end)
612 if (at_field_end)
613 /* POS is at the edge of a field, and we should consider it as
614 the end of the previous field. */
615 *end = XFASTINT (pos);
616 else
617 /* Find the next field boundary. */
619 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
620 /* Skip a `boundary' field. */
621 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
622 end_limit);
624 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
625 end_limit);
626 *end = NILP (pos) ? ZV : XFASTINT (pos);
632 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
633 doc: /* Delete the field surrounding POS.
634 A field is a region of text with the same `field' property.
635 If POS is nil, the value of point is used for POS. */)
636 (pos)
637 Lisp_Object pos;
639 int beg, end;
640 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
641 if (beg != end)
642 del_range (beg, end);
643 return Qnil;
646 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
647 doc: /* Return the contents of the field surrounding POS as a string.
648 A field is a region of text with the same `field' property.
649 If POS is nil, the value of point is used for POS. */)
650 (pos)
651 Lisp_Object pos;
653 int beg, end;
654 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
655 return make_buffer_string (beg, end, 1);
658 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
659 doc: /* Return the contents of the field around POS, without text properties.
660 A field is a region of text with the same `field' property.
661 If POS is nil, the value of point is used for POS. */)
662 (pos)
663 Lisp_Object pos;
665 int beg, end;
666 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
667 return make_buffer_string (beg, end, 0);
670 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
671 doc: /* Return the beginning of the field surrounding POS.
672 A field is a region of text with the same `field' property.
673 If POS is nil, the value of point is used for POS.
674 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
675 field, then the beginning of the *previous* field is returned.
676 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
677 is before LIMIT, then LIMIT will be returned instead. */)
678 (pos, escape_from_edge, limit)
679 Lisp_Object pos, escape_from_edge, limit;
681 int beg;
682 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
683 return make_number (beg);
686 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
687 doc: /* Return the end of the field surrounding POS.
688 A field is a region of text with the same `field' property.
689 If POS is nil, the value of point is used for POS.
690 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
691 then the end of the *following* field is returned.
692 If LIMIT is non-nil, it is a buffer position; if the end of the field
693 is after LIMIT, then LIMIT will be returned instead. */)
694 (pos, escape_from_edge, limit)
695 Lisp_Object pos, escape_from_edge, limit;
697 int end;
698 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
699 return make_number (end);
702 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
703 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
705 A field is a region of text with the same `field' property.
706 If NEW-POS is nil, then the current point is used instead, and set to the
707 constrained position if that is different.
709 If OLD-POS is at the boundary of two fields, then the allowable
710 positions for NEW-POS depends on the value of the optional argument
711 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
712 constrained to the field that has the same `field' char-property
713 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
714 is non-nil, NEW-POS is constrained to the union of the two adjacent
715 fields. Additionally, if two fields are separated by another field with
716 the special value `boundary', then any point within this special field is
717 also considered to be `on the boundary'.
719 If the optional argument ONLY-IN-LINE is non-nil and constraining
720 NEW-POS would move it to a different line, NEW-POS is returned
721 unconstrained. This useful for commands that move by line, like
722 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
723 only in the case where they can still move to the right line.
725 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
726 a non-nil property of that name, then any field boundaries are ignored.
728 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
729 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
730 Lisp_Object new_pos, old_pos;
731 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
733 /* If non-zero, then the original point, before re-positioning. */
734 int orig_point = 0;
735 int fwd;
736 Lisp_Object prev_old, prev_new;
738 if (NILP (new_pos))
739 /* Use the current point, and afterwards, set it. */
741 orig_point = PT;
742 XSETFASTINT (new_pos, PT);
745 CHECK_NUMBER_COERCE_MARKER (new_pos);
746 CHECK_NUMBER_COERCE_MARKER (old_pos);
748 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
750 prev_old = make_number (XFASTINT (old_pos) - 1);
751 prev_new = make_number (XFASTINT (new_pos) - 1);
753 if (NILP (Vinhibit_field_text_motion)
754 && !EQ (new_pos, old_pos)
755 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
756 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
757 /* To recognize field boundaries, we must also look at the
758 previous positions; we could use `get_pos_property'
759 instead, but in itself that would fail inside non-sticky
760 fields (like comint prompts). */
761 || (XFASTINT (new_pos) > BEGV
762 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
763 || (XFASTINT (old_pos) > BEGV
764 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
765 && (NILP (inhibit_capture_property)
766 /* Field boundaries are again a problem; but now we must
767 decide the case exactly, so we need to call
768 `get_pos_property' as well. */
769 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
770 && (XFASTINT (old_pos) <= BEGV
771 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
772 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
773 /* It is possible that NEW_POS is not within the same field as
774 OLD_POS; try to move NEW_POS so that it is. */
776 int shortage;
777 Lisp_Object field_bound;
779 if (fwd)
780 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
781 else
782 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
784 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
785 other side of NEW_POS, which would mean that NEW_POS is
786 already acceptable, and it's not necessary to constrain it
787 to FIELD_BOUND. */
788 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
789 /* NEW_POS should be constrained, but only if either
790 ONLY_IN_LINE is nil (in which case any constraint is OK),
791 or NEW_POS and FIELD_BOUND are on the same line (in which
792 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
793 && (NILP (only_in_line)
794 /* This is the ONLY_IN_LINE case, check that NEW_POS and
795 FIELD_BOUND are on the same line by seeing whether
796 there's an intervening newline or not. */
797 || (scan_buffer ('\n',
798 XFASTINT (new_pos), XFASTINT (field_bound),
799 fwd ? -1 : 1, &shortage, 1),
800 shortage != 0)))
801 /* Constrain NEW_POS to FIELD_BOUND. */
802 new_pos = field_bound;
804 if (orig_point && XFASTINT (new_pos) != orig_point)
805 /* The NEW_POS argument was originally nil, so automatically set PT. */
806 SET_PT (XFASTINT (new_pos));
809 return new_pos;
813 DEFUN ("line-beginning-position",
814 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
815 doc: /* Return the character position of the first character on the current line.
816 With argument N not nil or 1, move forward N - 1 lines first.
817 If scan reaches end of buffer, return that position.
819 This function constrains the returned position to the current field
820 unless that would be on a different line than the original,
821 unconstrained result. If N is nil or 1, and a front-sticky field
822 starts at point, the scan stops as soon as it starts. To ignore field
823 boundaries bind `inhibit-field-text-motion' to t.
825 This function does not move point. */)
827 Lisp_Object n;
829 int orig, orig_byte, end;
830 int count = SPECPDL_INDEX ();
831 specbind (Qinhibit_point_motion_hooks, Qt);
833 if (NILP (n))
834 XSETFASTINT (n, 1);
835 else
836 CHECK_NUMBER (n);
838 orig = PT;
839 orig_byte = PT_BYTE;
840 Fforward_line (make_number (XINT (n) - 1));
841 end = PT;
843 SET_PT_BOTH (orig, orig_byte);
845 unbind_to (count, Qnil);
847 /* Return END constrained to the current input field. */
848 return Fconstrain_to_field (make_number (end), make_number (orig),
849 XINT (n) != 1 ? Qt : Qnil,
850 Qt, Qnil);
853 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
854 doc: /* Return the character position of the last character on the current line.
855 With argument N not nil or 1, move forward N - 1 lines first.
856 If scan reaches end of buffer, return that position.
858 This function constrains the returned position to the current field
859 unless that would be on a different line than the original,
860 unconstrained result. If N is nil or 1, and a rear-sticky field ends
861 at point, the scan stops as soon as it starts. To ignore field
862 boundaries bind `inhibit-field-text-motion' to t.
864 This function does not move point. */)
866 Lisp_Object n;
868 int end_pos;
869 int orig = PT;
871 if (NILP (n))
872 XSETFASTINT (n, 1);
873 else
874 CHECK_NUMBER (n);
876 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
878 /* Return END_POS constrained to the current input field. */
879 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
880 Qnil, Qt, Qnil);
884 Lisp_Object
885 save_excursion_save ()
887 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
888 == current_buffer);
890 return Fcons (Fpoint_marker (),
891 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
892 Fcons (visible ? Qt : Qnil,
893 Fcons (current_buffer->mark_active,
894 selected_window))));
897 Lisp_Object
898 save_excursion_restore (info)
899 Lisp_Object info;
901 Lisp_Object tem, tem1, omark, nmark;
902 struct gcpro gcpro1, gcpro2, gcpro3;
903 int visible_p;
905 tem = Fmarker_buffer (XCAR (info));
906 /* If buffer being returned to is now deleted, avoid error */
907 /* Otherwise could get error here while unwinding to top level
908 and crash */
909 /* In that case, Fmarker_buffer returns nil now. */
910 if (NILP (tem))
911 return Qnil;
913 omark = nmark = Qnil;
914 GCPRO3 (info, omark, nmark);
916 Fset_buffer (tem);
918 /* Point marker. */
919 tem = XCAR (info);
920 Fgoto_char (tem);
921 unchain_marker (XMARKER (tem));
923 /* Mark marker. */
924 info = XCDR (info);
925 tem = XCAR (info);
926 omark = Fmarker_position (current_buffer->mark);
927 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
928 nmark = Fmarker_position (tem);
929 unchain_marker (XMARKER (tem));
931 /* visible */
932 info = XCDR (info);
933 visible_p = !NILP (XCAR (info));
935 #if 0 /* We used to make the current buffer visible in the selected window
936 if that was true previously. That avoids some anomalies.
937 But it creates others, and it wasn't documented, and it is simpler
938 and cleaner never to alter the window/buffer connections. */
939 tem1 = Fcar (tem);
940 if (!NILP (tem1)
941 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
942 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
943 #endif /* 0 */
945 /* Mark active */
946 info = XCDR (info);
947 tem = XCAR (info);
948 tem1 = current_buffer->mark_active;
949 current_buffer->mark_active = tem;
951 if (!NILP (Vrun_hooks))
953 /* If mark is active now, and either was not active
954 or was at a different place, run the activate hook. */
955 if (! NILP (current_buffer->mark_active))
957 if (! EQ (omark, nmark))
958 call1 (Vrun_hooks, intern ("activate-mark-hook"));
960 /* If mark has ceased to be active, run deactivate hook. */
961 else if (! NILP (tem1))
962 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
965 /* If buffer was visible in a window, and a different window was
966 selected, and the old selected window is still showing this
967 buffer, restore point in that window. */
968 tem = XCDR (info);
969 if (visible_p
970 && !EQ (tem, selected_window)
971 && (tem1 = XWINDOW (tem)->buffer,
972 (/* Window is live... */
973 BUFFERP (tem1)
974 /* ...and it shows the current buffer. */
975 && XBUFFER (tem1) == current_buffer)))
976 Fset_window_point (tem, make_number (PT));
978 UNGCPRO;
979 return Qnil;
982 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
983 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
984 Executes BODY just like `progn'.
985 The values of point, mark and the current buffer are restored
986 even in case of abnormal exit (throw or error).
987 The state of activation of the mark is also restored.
989 This construct does not save `deactivate-mark', and therefore
990 functions that change the buffer will still cause deactivation
991 of the mark at the end of the command. To prevent that, bind
992 `deactivate-mark' with `let'.
994 usage: (save-excursion &rest BODY) */)
995 (args)
996 Lisp_Object args;
998 register Lisp_Object val;
999 int count = SPECPDL_INDEX ();
1001 record_unwind_protect (save_excursion_restore, save_excursion_save ());
1003 val = Fprogn (args);
1004 return unbind_to (count, val);
1007 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
1008 doc: /* Save the current buffer; execute BODY; restore the current buffer.
1009 Executes BODY just like `progn'.
1010 usage: (save-current-buffer &rest BODY) */)
1011 (args)
1012 Lisp_Object args;
1014 Lisp_Object val;
1015 int count = SPECPDL_INDEX ();
1017 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
1019 val = Fprogn (args);
1020 return unbind_to (count, val);
1023 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
1024 doc: /* Return the number of characters in the current buffer.
1025 If BUFFER, return the number of characters in that buffer instead. */)
1026 (buffer)
1027 Lisp_Object buffer;
1029 if (NILP (buffer))
1030 return make_number (Z - BEG);
1031 else
1033 CHECK_BUFFER (buffer);
1034 return make_number (BUF_Z (XBUFFER (buffer))
1035 - BUF_BEG (XBUFFER (buffer)));
1039 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
1040 doc: /* Return the minimum permissible value of point in the current buffer.
1041 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1044 Lisp_Object temp;
1045 XSETFASTINT (temp, BEGV);
1046 return temp;
1049 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1050 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1051 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1054 return buildmark (BEGV, BEGV_BYTE);
1057 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1058 doc: /* Return the maximum permissible value of point in the current buffer.
1059 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1060 is in effect, in which case it is less. */)
1063 Lisp_Object temp;
1064 XSETFASTINT (temp, ZV);
1065 return temp;
1068 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1069 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1070 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1071 is in effect, in which case it is less. */)
1074 return buildmark (ZV, ZV_BYTE);
1077 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1078 doc: /* Return the position of the gap, in the current buffer.
1079 See also `gap-size'. */)
1082 Lisp_Object temp;
1083 XSETFASTINT (temp, GPT);
1084 return temp;
1087 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1088 doc: /* Return the size of the current buffer's gap.
1089 See also `gap-position'. */)
1092 Lisp_Object temp;
1093 XSETFASTINT (temp, GAP_SIZE);
1094 return temp;
1097 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1098 doc: /* Return the byte position for character position POSITION.
1099 If POSITION is out of range, the value is nil. */)
1100 (position)
1101 Lisp_Object position;
1103 CHECK_NUMBER_COERCE_MARKER (position);
1104 if (XINT (position) < BEG || XINT (position) > Z)
1105 return Qnil;
1106 return make_number (CHAR_TO_BYTE (XINT (position)));
1109 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1110 doc: /* Return the character position for byte position BYTEPOS.
1111 If BYTEPOS is out of range, the value is nil. */)
1112 (bytepos)
1113 Lisp_Object bytepos;
1115 CHECK_NUMBER (bytepos);
1116 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1117 return Qnil;
1118 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1121 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1122 doc: /* Return the character following point, as a number.
1123 At the end of the buffer or accessible region, return 0. */)
1126 Lisp_Object temp;
1127 if (PT >= ZV)
1128 XSETFASTINT (temp, 0);
1129 else
1130 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1131 return temp;
1134 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1135 doc: /* Return the character preceding point, as a number.
1136 At the beginning of the buffer or accessible region, return 0. */)
1139 Lisp_Object temp;
1140 if (PT <= BEGV)
1141 XSETFASTINT (temp, 0);
1142 else if (!NILP (current_buffer->enable_multibyte_characters))
1144 int pos = PT_BYTE;
1145 DEC_POS (pos);
1146 XSETFASTINT (temp, FETCH_CHAR (pos));
1148 else
1149 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1150 return temp;
1153 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1154 doc: /* Return t if point is at the beginning of the buffer.
1155 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1158 if (PT == BEGV)
1159 return Qt;
1160 return Qnil;
1163 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1164 doc: /* Return t if point is at the end of the buffer.
1165 If the buffer is narrowed, this means the end of the narrowed part. */)
1168 if (PT == ZV)
1169 return Qt;
1170 return Qnil;
1173 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1174 doc: /* Return t if point is at the beginning of a line. */)
1177 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1178 return Qt;
1179 return Qnil;
1182 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1183 doc: /* Return t if point is at the end of a line.
1184 `End of a line' includes point being at the end of the buffer. */)
1187 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1188 return Qt;
1189 return Qnil;
1192 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1193 doc: /* Return character in current buffer at position POS.
1194 POS is an integer or a marker and defaults to point.
1195 If POS is out of range, the value is nil. */)
1196 (pos)
1197 Lisp_Object pos;
1199 register int pos_byte;
1201 if (NILP (pos))
1203 pos_byte = PT_BYTE;
1204 XSETFASTINT (pos, PT);
1207 if (MARKERP (pos))
1209 pos_byte = marker_byte_position (pos);
1210 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1211 return Qnil;
1213 else
1215 CHECK_NUMBER_COERCE_MARKER (pos);
1216 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1217 return Qnil;
1219 pos_byte = CHAR_TO_BYTE (XINT (pos));
1222 return make_number (FETCH_CHAR (pos_byte));
1225 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1226 doc: /* Return character in current buffer preceding position POS.
1227 POS is an integer or a marker and defaults to point.
1228 If POS is out of range, the value is nil. */)
1229 (pos)
1230 Lisp_Object pos;
1232 register Lisp_Object val;
1233 register int pos_byte;
1235 if (NILP (pos))
1237 pos_byte = PT_BYTE;
1238 XSETFASTINT (pos, PT);
1241 if (MARKERP (pos))
1243 pos_byte = marker_byte_position (pos);
1245 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1246 return Qnil;
1248 else
1250 CHECK_NUMBER_COERCE_MARKER (pos);
1252 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1253 return Qnil;
1255 pos_byte = CHAR_TO_BYTE (XINT (pos));
1258 if (!NILP (current_buffer->enable_multibyte_characters))
1260 DEC_POS (pos_byte);
1261 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1263 else
1265 pos_byte--;
1266 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1268 return val;
1271 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1272 doc: /* Return the name under which the user logged in, as a string.
1273 This is based on the effective uid, not the real uid.
1274 Also, if the environment variables LOGNAME or USER are set,
1275 that determines the value of this function.
1277 If optional argument UID is an integer, return the login name of the user
1278 with that uid, or nil if there is no such user. */)
1279 (uid)
1280 Lisp_Object uid;
1282 struct passwd *pw;
1284 /* Set up the user name info if we didn't do it before.
1285 (That can happen if Emacs is dumpable
1286 but you decide to run `temacs -l loadup' and not dump. */
1287 if (INTEGERP (Vuser_login_name))
1288 init_editfns ();
1290 if (NILP (uid))
1291 return Vuser_login_name;
1293 CHECK_NUMBER (uid);
1294 BLOCK_INPUT;
1295 pw = (struct passwd *) getpwuid (XINT (uid));
1296 UNBLOCK_INPUT;
1297 return (pw ? build_string (pw->pw_name) : Qnil);
1300 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1301 0, 0, 0,
1302 doc: /* Return the name of the user's real uid, as a string.
1303 This ignores the environment variables LOGNAME and USER, so it differs from
1304 `user-login-name' when running under `su'. */)
1307 /* Set up the user name info if we didn't do it before.
1308 (That can happen if Emacs is dumpable
1309 but you decide to run `temacs -l loadup' and not dump. */
1310 if (INTEGERP (Vuser_login_name))
1311 init_editfns ();
1312 return Vuser_real_login_name;
1315 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1316 doc: /* Return the effective uid of Emacs.
1317 Value is an integer or float, depending on the value. */)
1320 /* Assignment to EMACS_INT stops GCC whining about limited range of
1321 data type. */
1322 EMACS_INT euid = geteuid ();
1323 return make_fixnum_or_float (euid);
1326 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1327 doc: /* Return the real uid of Emacs.
1328 Value is an integer or float, depending on the value. */)
1331 /* Assignment to EMACS_INT stops GCC whining about limited range of
1332 data type. */
1333 EMACS_INT uid = getuid ();
1334 return make_fixnum_or_float (uid);
1337 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1338 doc: /* Return the full name of the user logged in, as a string.
1339 If the full name corresponding to Emacs's userid is not known,
1340 return "unknown".
1342 If optional argument UID is an integer or float, return the full name
1343 of the user with that uid, or nil if there is no such user.
1344 If UID is a string, return the full name of the user with that login
1345 name, or nil if there is no such user. */)
1346 (uid)
1347 Lisp_Object uid;
1349 struct passwd *pw;
1350 register unsigned char *p, *q;
1351 Lisp_Object full;
1353 if (NILP (uid))
1354 return Vuser_full_name;
1355 else if (NUMBERP (uid))
1357 BLOCK_INPUT;
1358 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1359 UNBLOCK_INPUT;
1361 else if (STRINGP (uid))
1363 BLOCK_INPUT;
1364 pw = (struct passwd *) getpwnam (SDATA (uid));
1365 UNBLOCK_INPUT;
1367 else
1368 error ("Invalid UID specification");
1370 if (!pw)
1371 return Qnil;
1373 p = (unsigned char *) USER_FULL_NAME;
1374 /* Chop off everything after the first comma. */
1375 q = (unsigned char *) index (p, ',');
1376 full = make_string (p, q ? q - p : strlen (p));
1378 #ifdef AMPERSAND_FULL_NAME
1379 p = SDATA (full);
1380 q = (unsigned char *) index (p, '&');
1381 /* Substitute the login name for the &, upcasing the first character. */
1382 if (q)
1384 register unsigned char *r;
1385 Lisp_Object login;
1387 login = Fuser_login_name (make_number (pw->pw_uid));
1388 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
1389 bcopy (p, r, q - p);
1390 r[q - p] = 0;
1391 strcat (r, SDATA (login));
1392 r[q - p] = UPCASE (r[q - p]);
1393 strcat (r, q + 1);
1394 full = build_string (r);
1396 #endif /* AMPERSAND_FULL_NAME */
1398 return full;
1401 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1402 doc: /* Return the host name of the machine you are running on, as a string. */)
1405 return Vsystem_name;
1408 /* For the benefit of callers who don't want to include lisp.h */
1410 char *
1411 get_system_name ()
1413 if (STRINGP (Vsystem_name))
1414 return (char *) SDATA (Vsystem_name);
1415 else
1416 return "";
1419 char *
1420 get_operating_system_release()
1422 if (STRINGP (Voperating_system_release))
1423 return (char *) SDATA (Voperating_system_release);
1424 else
1425 return "";
1428 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1429 doc: /* Return the process ID of Emacs, as an integer. */)
1432 return make_number (getpid ());
1435 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1436 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1437 The time is returned as a list of three integers. The first has the
1438 most significant 16 bits of the seconds, while the second has the
1439 least significant 16 bits. The third integer gives the microsecond
1440 count.
1442 The microsecond count is zero on systems that do not provide
1443 resolution finer than a second. */)
1446 EMACS_TIME t;
1448 EMACS_GET_TIME (t);
1449 return list3 (make_number ((EMACS_SECS (t) >> 16) & 0xffff),
1450 make_number ((EMACS_SECS (t) >> 0) & 0xffff),
1451 make_number (EMACS_USECS (t)));
1454 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1455 0, 0, 0,
1456 doc: /* Return the current run time used by Emacs.
1457 The time is returned as a list of three integers. The first has the
1458 most significant 16 bits of the seconds, while the second has the
1459 least significant 16 bits. The third integer gives the microsecond
1460 count.
1462 On systems that can't determine the run time, `get-internal-run-time'
1463 does the same thing as `current-time'. The microsecond count is zero
1464 on systems that do not provide resolution finer than a second. */)
1467 #ifdef HAVE_GETRUSAGE
1468 struct rusage usage;
1469 int secs, usecs;
1471 if (getrusage (RUSAGE_SELF, &usage) < 0)
1472 /* This shouldn't happen. What action is appropriate? */
1473 xsignal0 (Qerror);
1475 /* Sum up user time and system time. */
1476 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1477 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1478 if (usecs >= 1000000)
1480 usecs -= 1000000;
1481 secs++;
1484 return list3 (make_number ((secs >> 16) & 0xffff),
1485 make_number ((secs >> 0) & 0xffff),
1486 make_number (usecs));
1487 #else /* ! HAVE_GETRUSAGE */
1488 #if WINDOWSNT
1489 return w32_get_internal_run_time ();
1490 #else /* ! WINDOWSNT */
1491 return Fcurrent_time ();
1492 #endif /* WINDOWSNT */
1493 #endif /* HAVE_GETRUSAGE */
1498 lisp_time_argument (specified_time, result, usec)
1499 Lisp_Object specified_time;
1500 time_t *result;
1501 int *usec;
1503 if (NILP (specified_time))
1505 if (usec)
1507 EMACS_TIME t;
1509 EMACS_GET_TIME (t);
1510 *usec = EMACS_USECS (t);
1511 *result = EMACS_SECS (t);
1512 return 1;
1514 else
1515 return time (result) != -1;
1517 else
1519 Lisp_Object high, low;
1520 high = Fcar (specified_time);
1521 CHECK_NUMBER (high);
1522 low = Fcdr (specified_time);
1523 if (CONSP (low))
1525 if (usec)
1527 Lisp_Object usec_l = Fcdr (low);
1528 if (CONSP (usec_l))
1529 usec_l = Fcar (usec_l);
1530 if (NILP (usec_l))
1531 *usec = 0;
1532 else
1534 CHECK_NUMBER (usec_l);
1535 *usec = XINT (usec_l);
1538 low = Fcar (low);
1540 else if (usec)
1541 *usec = 0;
1542 CHECK_NUMBER (low);
1543 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1544 return *result >> 16 == XINT (high);
1548 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1549 doc: /* Return the current time, as a float number of seconds since the epoch.
1550 If SPECIFIED-TIME is given, it is the time to convert to float
1551 instead of the current time. The argument should have the form
1552 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1553 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1554 have the form (HIGH . LOW), but this is considered obsolete.
1556 WARNING: Since the result is floating point, it may not be exact.
1557 Do not use this function if precise time stamps are required. */)
1558 (specified_time)
1559 Lisp_Object specified_time;
1561 time_t sec;
1562 int usec;
1564 if (! lisp_time_argument (specified_time, &sec, &usec))
1565 error ("Invalid time specification");
1567 return make_float ((sec * 1e6 + usec) / 1e6);
1570 /* Write information into buffer S of size MAXSIZE, according to the
1571 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1572 Default to Universal Time if UT is nonzero, local time otherwise.
1573 Return the number of bytes written, not including the terminating
1574 '\0'. If S is NULL, nothing will be written anywhere; so to
1575 determine how many bytes would be written, use NULL for S and
1576 ((size_t) -1) for MAXSIZE.
1578 This function behaves like emacs_strftimeu, except it allows null
1579 bytes in FORMAT. */
1580 static size_t
1581 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1582 char *s;
1583 size_t maxsize;
1584 const char *format;
1585 size_t format_len;
1586 const struct tm *tp;
1587 int ut;
1589 size_t total = 0;
1591 /* Loop through all the null-terminated strings in the format
1592 argument. Normally there's just one null-terminated string, but
1593 there can be arbitrarily many, concatenated together, if the
1594 format contains '\0' bytes. emacs_strftimeu stops at the first
1595 '\0' byte so we must invoke it separately for each such string. */
1596 for (;;)
1598 size_t len;
1599 size_t result;
1601 if (s)
1602 s[0] = '\1';
1604 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1606 if (s)
1608 if (result == 0 && s[0] != '\0')
1609 return 0;
1610 s += result + 1;
1613 maxsize -= result + 1;
1614 total += result;
1615 len = strlen (format);
1616 if (len == format_len)
1617 return total;
1618 total++;
1619 format += len + 1;
1620 format_len -= len + 1;
1624 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1625 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1626 TIME is specified as (HIGH LOW . IGNORED), as returned by
1627 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1628 is also still accepted.
1629 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1630 as Universal Time; nil means describe TIME in the local time zone.
1631 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1632 by text that describes the specified date and time in TIME:
1634 %Y is the year, %y within the century, %C the century.
1635 %G is the year corresponding to the ISO week, %g within the century.
1636 %m is the numeric month.
1637 %b and %h are the locale's abbreviated month name, %B the full name.
1638 %d is the day of the month, zero-padded, %e is blank-padded.
1639 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1640 %a is the locale's abbreviated name of the day of week, %A the full name.
1641 %U is the week number starting on Sunday, %W starting on Monday,
1642 %V according to ISO 8601.
1643 %j is the day of the year.
1645 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1646 only blank-padded, %l is like %I blank-padded.
1647 %p is the locale's equivalent of either AM or PM.
1648 %M is the minute.
1649 %S is the second.
1650 %Z is the time zone name, %z is the numeric form.
1651 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1653 %c is the locale's date and time format.
1654 %x is the locale's "preferred" date format.
1655 %D is like "%m/%d/%y".
1657 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1658 %X is the locale's "preferred" time format.
1660 Finally, %n is a newline, %t is a tab, %% is a literal %.
1662 Certain flags and modifiers are available with some format controls.
1663 The flags are `_', `-', `^' and `#'. For certain characters X,
1664 %_X is like %X, but padded with blanks; %-X is like %X,
1665 but without padding. %^X is like %X, but with all textual
1666 characters up-cased; %#X is like %X, but with letter-case of
1667 all textual characters reversed.
1668 %NX (where N stands for an integer) is like %X,
1669 but takes up at least N (a number) positions.
1670 The modifiers are `E' and `O'. For certain characters X,
1671 %EX is a locale's alternative version of %X;
1672 %OX is like %X, but uses the locale's number symbols.
1674 For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1675 (format_string, time, universal)
1676 Lisp_Object format_string, time, universal;
1678 time_t value;
1679 int size;
1680 struct tm *tm;
1681 int ut = ! NILP (universal);
1683 CHECK_STRING (format_string);
1685 if (! lisp_time_argument (time, &value, NULL))
1686 error ("Invalid time specification");
1688 format_string = code_convert_string_norecord (format_string,
1689 Vlocale_coding_system, 1);
1691 /* This is probably enough. */
1692 size = SBYTES (format_string) * 6 + 50;
1694 BLOCK_INPUT;
1695 tm = ut ? gmtime (&value) : localtime (&value);
1696 UNBLOCK_INPUT;
1697 if (! tm)
1698 error ("Specified time is not representable");
1700 synchronize_system_time_locale ();
1702 while (1)
1704 char *buf = (char *) alloca (size + 1);
1705 int result;
1707 buf[0] = '\1';
1708 BLOCK_INPUT;
1709 result = emacs_memftimeu (buf, size, SDATA (format_string),
1710 SBYTES (format_string),
1711 tm, ut);
1712 UNBLOCK_INPUT;
1713 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1714 return code_convert_string_norecord (make_unibyte_string (buf, result),
1715 Vlocale_coding_system, 0);
1717 /* If buffer was too small, make it bigger and try again. */
1718 BLOCK_INPUT;
1719 result = emacs_memftimeu (NULL, (size_t) -1,
1720 SDATA (format_string),
1721 SBYTES (format_string),
1722 tm, ut);
1723 UNBLOCK_INPUT;
1724 size = result + 1;
1728 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1729 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
1730 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
1731 as from `current-time' and `file-attributes', or nil to use the
1732 current time. The obsolete form (HIGH . LOW) is also still accepted.
1733 The list has the following nine members: SEC is an integer between 0
1734 and 60; SEC is 60 for a leap second, which only some operating systems
1735 support. MINUTE is an integer between 0 and 59. HOUR is an integer
1736 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1737 integer between 1 and 12. YEAR is an integer indicating the
1738 four-digit year. DOW is the day of week, an integer between 0 and 6,
1739 where 0 is Sunday. DST is t if daylight saving time is in effect,
1740 otherwise nil. ZONE is an integer indicating the number of seconds
1741 east of Greenwich. (Note that Common Lisp has different meanings for
1742 DOW and ZONE.) */)
1743 (specified_time)
1744 Lisp_Object specified_time;
1746 time_t time_spec;
1747 struct tm save_tm;
1748 struct tm *decoded_time;
1749 Lisp_Object list_args[9];
1751 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1752 error ("Invalid time specification");
1754 BLOCK_INPUT;
1755 decoded_time = localtime (&time_spec);
1756 UNBLOCK_INPUT;
1757 if (! decoded_time)
1758 error ("Specified time is not representable");
1759 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1760 XSETFASTINT (list_args[1], decoded_time->tm_min);
1761 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1762 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1763 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1764 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1765 cast below avoids overflow in int arithmetics. */
1766 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
1767 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1768 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1770 /* Make a copy, in case gmtime modifies the struct. */
1771 save_tm = *decoded_time;
1772 BLOCK_INPUT;
1773 decoded_time = gmtime (&time_spec);
1774 UNBLOCK_INPUT;
1775 if (decoded_time == 0)
1776 list_args[8] = Qnil;
1777 else
1778 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1779 return Flist (9, list_args);
1782 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1783 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
1784 This is the reverse operation of `decode-time', which see.
1785 ZONE defaults to the current time zone rule. This can
1786 be a string or t (as from `set-time-zone-rule'), or it can be a list
1787 \(as from `current-time-zone') or an integer (as from `decode-time')
1788 applied without consideration for daylight saving time.
1790 You can pass more than 7 arguments; then the first six arguments
1791 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1792 The intervening arguments are ignored.
1793 This feature lets (apply 'encode-time (decode-time ...)) work.
1795 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
1796 for example, a DAY of 0 means the day preceding the given month.
1797 Year numbers less than 100 are treated just like other year numbers.
1798 If you want them to stand for years in this century, you must do that yourself.
1800 Years before 1970 are not guaranteed to work. On some systems,
1801 year values as low as 1901 do work.
1803 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
1804 (nargs, args)
1805 int nargs;
1806 register Lisp_Object *args;
1808 time_t time;
1809 struct tm tm;
1810 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1812 CHECK_NUMBER (args[0]); /* second */
1813 CHECK_NUMBER (args[1]); /* minute */
1814 CHECK_NUMBER (args[2]); /* hour */
1815 CHECK_NUMBER (args[3]); /* day */
1816 CHECK_NUMBER (args[4]); /* month */
1817 CHECK_NUMBER (args[5]); /* year */
1819 tm.tm_sec = XINT (args[0]);
1820 tm.tm_min = XINT (args[1]);
1821 tm.tm_hour = XINT (args[2]);
1822 tm.tm_mday = XINT (args[3]);
1823 tm.tm_mon = XINT (args[4]) - 1;
1824 tm.tm_year = XINT (args[5]) - TM_YEAR_BASE;
1825 tm.tm_isdst = -1;
1827 if (CONSP (zone))
1828 zone = Fcar (zone);
1829 if (NILP (zone))
1831 BLOCK_INPUT;
1832 time = mktime (&tm);
1833 UNBLOCK_INPUT;
1835 else
1837 char tzbuf[100];
1838 char *tzstring;
1839 char **oldenv = environ, **newenv;
1841 if (EQ (zone, Qt))
1842 tzstring = "UTC0";
1843 else if (STRINGP (zone))
1844 tzstring = (char *) SDATA (zone);
1845 else if (INTEGERP (zone))
1847 int abszone = eabs (XINT (zone));
1848 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1849 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1850 tzstring = tzbuf;
1852 else
1853 error ("Invalid time zone specification");
1855 /* Set TZ before calling mktime; merely adjusting mktime's returned
1856 value doesn't suffice, since that would mishandle leap seconds. */
1857 set_time_zone_rule (tzstring);
1859 BLOCK_INPUT;
1860 time = mktime (&tm);
1861 UNBLOCK_INPUT;
1863 /* Restore TZ to previous value. */
1864 newenv = environ;
1865 environ = oldenv;
1866 xfree (newenv);
1867 #ifdef LOCALTIME_CACHE
1868 tzset ();
1869 #endif
1872 if (time == (time_t) -1)
1873 error ("Specified time is not representable");
1875 return make_time (time);
1878 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1879 doc: /* Return the current time, as a human-readable string.
1880 Programs can use this function to decode a time,
1881 since the number of columns in each field is fixed
1882 if the year is in the range 1000-9999.
1883 The format is `Sun Sep 16 01:03:52 1973'.
1884 However, see also the functions `decode-time' and `format-time-string'
1885 which provide a much more powerful and general facility.
1887 If SPECIFIED-TIME is given, it is a time to format instead of the
1888 current time. The argument should have the form (HIGH LOW . IGNORED).
1889 Thus, you can use times obtained from `current-time' and from
1890 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1891 but this is considered obsolete. */)
1892 (specified_time)
1893 Lisp_Object specified_time;
1895 time_t value;
1896 struct tm *tm;
1897 register char *tem;
1899 if (! lisp_time_argument (specified_time, &value, NULL))
1900 error ("Invalid time specification");
1902 /* Convert to a string, checking for out-of-range time stamps.
1903 Don't use 'ctime', as that might dump core if VALUE is out of
1904 range. */
1905 BLOCK_INPUT;
1906 tm = localtime (&value);
1907 UNBLOCK_INPUT;
1908 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
1909 error ("Specified time is not representable");
1911 /* Remove the trailing newline. */
1912 tem[strlen (tem) - 1] = '\0';
1914 return build_string (tem);
1917 /* Yield A - B, measured in seconds.
1918 This function is copied from the GNU C Library. */
1919 static int
1920 tm_diff (a, b)
1921 struct tm *a, *b;
1923 /* Compute intervening leap days correctly even if year is negative.
1924 Take care to avoid int overflow in leap day calculations,
1925 but it's OK to assume that A and B are close to each other. */
1926 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1927 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1928 int a100 = a4 / 25 - (a4 % 25 < 0);
1929 int b100 = b4 / 25 - (b4 % 25 < 0);
1930 int a400 = a100 >> 2;
1931 int b400 = b100 >> 2;
1932 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1933 int years = a->tm_year - b->tm_year;
1934 int days = (365 * years + intervening_leap_days
1935 + (a->tm_yday - b->tm_yday));
1936 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1937 + (a->tm_min - b->tm_min))
1938 + (a->tm_sec - b->tm_sec));
1941 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1942 doc: /* Return the offset and name for the local time zone.
1943 This returns a list of the form (OFFSET NAME).
1944 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1945 A negative value means west of Greenwich.
1946 NAME is a string giving the name of the time zone.
1947 If SPECIFIED-TIME is given, the time zone offset is determined from it
1948 instead of using the current time. The argument should have the form
1949 (HIGH LOW . IGNORED). Thus, you can use times obtained from
1950 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
1951 have the form (HIGH . LOW), but this is considered obsolete.
1953 Some operating systems cannot provide all this information to Emacs;
1954 in this case, `current-time-zone' returns a list containing nil for
1955 the data it can't find. */)
1956 (specified_time)
1957 Lisp_Object specified_time;
1959 time_t value;
1960 struct tm *t;
1961 struct tm gmt;
1963 if (!lisp_time_argument (specified_time, &value, NULL))
1964 t = NULL;
1965 else
1967 BLOCK_INPUT;
1968 t = gmtime (&value);
1969 if (t)
1971 gmt = *t;
1972 t = localtime (&value);
1974 UNBLOCK_INPUT;
1977 if (t)
1979 int offset = tm_diff (t, &gmt);
1980 char *s = 0;
1981 char buf[6];
1983 #ifdef HAVE_TM_ZONE
1984 if (t->tm_zone)
1985 s = (char *)t->tm_zone;
1986 #else /* not HAVE_TM_ZONE */
1987 #ifdef HAVE_TZNAME
1988 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1989 s = tzname[t->tm_isdst];
1990 #endif
1991 #endif /* not HAVE_TM_ZONE */
1993 if (!s)
1995 /* No local time zone name is available; use "+-NNNN" instead. */
1996 int am = (offset < 0 ? -offset : offset) / 60;
1997 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1998 s = buf;
2001 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2003 else
2004 return Fmake_list (make_number (2), Qnil);
2007 /* This holds the value of `environ' produced by the previous
2008 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2009 has never been called. */
2010 static char **environbuf;
2012 /* This holds the startup value of the TZ environment variable so it
2013 can be restored if the user calls set-time-zone-rule with a nil
2014 argument. */
2015 static char *initial_tz;
2017 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2018 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2019 If TZ is nil, use implementation-defined default time zone information.
2020 If TZ is t, use Universal Time. */)
2021 (tz)
2022 Lisp_Object tz;
2024 char *tzstring;
2026 /* When called for the first time, save the original TZ. */
2027 if (!environbuf)
2028 initial_tz = (char *) getenv ("TZ");
2030 if (NILP (tz))
2031 tzstring = initial_tz;
2032 else if (EQ (tz, Qt))
2033 tzstring = "UTC0";
2034 else
2036 CHECK_STRING (tz);
2037 tzstring = (char *) SDATA (tz);
2040 set_time_zone_rule (tzstring);
2041 free (environbuf);
2042 environbuf = environ;
2044 return Qnil;
2047 #ifdef LOCALTIME_CACHE
2049 /* These two values are known to load tz files in buggy implementations,
2050 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
2051 Their values shouldn't matter in non-buggy implementations.
2052 We don't use string literals for these strings,
2053 since if a string in the environment is in readonly
2054 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2055 See Sun bugs 1113095 and 1114114, ``Timezone routines
2056 improperly modify environment''. */
2058 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2059 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2061 #endif
2063 /* Set the local time zone rule to TZSTRING.
2064 This allocates memory into `environ', which it is the caller's
2065 responsibility to free. */
2067 void
2068 set_time_zone_rule (tzstring)
2069 char *tzstring;
2071 int envptrs;
2072 char **from, **to, **newenv;
2074 /* Make the ENVIRON vector longer with room for TZSTRING. */
2075 for (from = environ; *from; from++)
2076 continue;
2077 envptrs = from - environ + 2;
2078 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2079 + (tzstring ? strlen (tzstring) + 4 : 0));
2081 /* Add TZSTRING to the end of environ, as a value for TZ. */
2082 if (tzstring)
2084 char *t = (char *) (to + envptrs);
2085 strcpy (t, "TZ=");
2086 strcat (t, tzstring);
2087 *to++ = t;
2090 /* Copy the old environ vector elements into NEWENV,
2091 but don't copy the TZ variable.
2092 So we have only one definition of TZ, which came from TZSTRING. */
2093 for (from = environ; *from; from++)
2094 if (strncmp (*from, "TZ=", 3) != 0)
2095 *to++ = *from;
2096 *to = 0;
2098 environ = newenv;
2100 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2101 the TZ variable is stored. If we do not have a TZSTRING,
2102 TO points to the vector slot which has the terminating null. */
2104 #ifdef LOCALTIME_CACHE
2106 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2107 "US/Pacific" that loads a tz file, then changes to a value like
2108 "XXX0" that does not load a tz file, and then changes back to
2109 its original value, the last change is (incorrectly) ignored.
2110 Also, if TZ changes twice in succession to values that do
2111 not load a tz file, tzset can dump core (see Sun bug#1225179).
2112 The following code works around these bugs. */
2114 if (tzstring)
2116 /* Temporarily set TZ to a value that loads a tz file
2117 and that differs from tzstring. */
2118 char *tz = *newenv;
2119 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2120 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
2121 tzset ();
2122 *newenv = tz;
2124 else
2126 /* The implied tzstring is unknown, so temporarily set TZ to
2127 two different values that each load a tz file. */
2128 *to = set_time_zone_rule_tz1;
2129 to[1] = 0;
2130 tzset ();
2131 *to = set_time_zone_rule_tz2;
2132 tzset ();
2133 *to = 0;
2136 /* Now TZ has the desired value, and tzset can be invoked safely. */
2139 tzset ();
2140 #endif
2143 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2144 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2145 type of object is Lisp_String). INHERIT is passed to
2146 INSERT_FROM_STRING_FUNC as the last argument. */
2148 static void
2149 general_insert_function (insert_func, insert_from_string_func,
2150 inherit, nargs, args)
2151 void (*insert_func) P_ ((const unsigned char *, int));
2152 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
2153 int inherit, nargs;
2154 register Lisp_Object *args;
2156 register int argnum;
2157 register Lisp_Object val;
2159 for (argnum = 0; argnum < nargs; argnum++)
2161 val = args[argnum];
2162 if (CHARACTERP (val))
2164 unsigned char str[MAX_MULTIBYTE_LENGTH];
2165 int len;
2167 if (!NILP (current_buffer->enable_multibyte_characters))
2168 len = CHAR_STRING (XFASTINT (val), str);
2169 else
2171 str[0] = (ASCII_CHAR_P (XINT (val))
2172 ? XINT (val)
2173 : multibyte_char_to_unibyte (XINT (val), Qnil));
2174 len = 1;
2176 (*insert_func) (str, len);
2178 else if (STRINGP (val))
2180 (*insert_from_string_func) (val, 0, 0,
2181 SCHARS (val),
2182 SBYTES (val),
2183 inherit);
2185 else
2186 wrong_type_argument (Qchar_or_string_p, val);
2190 void
2191 insert1 (arg)
2192 Lisp_Object arg;
2194 Finsert (1, &arg);
2198 /* Callers passing one argument to Finsert need not gcpro the
2199 argument "array", since the only element of the array will
2200 not be used after calling insert or insert_from_string, so
2201 we don't care if it gets trashed. */
2203 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2204 doc: /* Insert the arguments, either strings or characters, at point.
2205 Point and before-insertion markers move forward to end up
2206 after the inserted text.
2207 Any other markers at the point of insertion remain before the text.
2209 If the current buffer is multibyte, unibyte strings are converted
2210 to multibyte for insertion (see `string-make-multibyte').
2211 If the current buffer is unibyte, multibyte strings are converted
2212 to unibyte for insertion (see `string-make-unibyte').
2214 When operating on binary data, it may be necessary to preserve the
2215 original bytes of a unibyte string when inserting it into a multibyte
2216 buffer; to accomplish this, apply `string-as-multibyte' to the string
2217 and insert the result.
2219 usage: (insert &rest ARGS) */)
2220 (nargs, args)
2221 int nargs;
2222 register Lisp_Object *args;
2224 general_insert_function (insert, insert_from_string, 0, nargs, args);
2225 return Qnil;
2228 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2229 0, MANY, 0,
2230 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2231 Point and before-insertion markers move forward to end up
2232 after the inserted text.
2233 Any other markers at the point of insertion remain before the text.
2235 If the current buffer is multibyte, unibyte strings are converted
2236 to multibyte for insertion (see `unibyte-char-to-multibyte').
2237 If the current buffer is unibyte, multibyte strings are converted
2238 to unibyte for insertion.
2240 usage: (insert-and-inherit &rest ARGS) */)
2241 (nargs, args)
2242 int nargs;
2243 register Lisp_Object *args;
2245 general_insert_function (insert_and_inherit, insert_from_string, 1,
2246 nargs, args);
2247 return Qnil;
2250 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2251 doc: /* Insert strings or characters at point, relocating markers after the text.
2252 Point and markers move forward to end up after the inserted text.
2254 If the current buffer is multibyte, unibyte strings are converted
2255 to multibyte for insertion (see `unibyte-char-to-multibyte').
2256 If the current buffer is unibyte, multibyte strings are converted
2257 to unibyte for insertion.
2259 usage: (insert-before-markers &rest ARGS) */)
2260 (nargs, args)
2261 int nargs;
2262 register Lisp_Object *args;
2264 general_insert_function (insert_before_markers,
2265 insert_from_string_before_markers, 0,
2266 nargs, args);
2267 return Qnil;
2270 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2271 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2272 doc: /* Insert text at point, relocating markers and inheriting properties.
2273 Point and markers move forward to end up after the inserted text.
2275 If the current buffer is multibyte, unibyte strings are converted
2276 to multibyte for insertion (see `unibyte-char-to-multibyte').
2277 If the current buffer is unibyte, multibyte strings are converted
2278 to unibyte for insertion.
2280 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2281 (nargs, args)
2282 int nargs;
2283 register Lisp_Object *args;
2285 general_insert_function (insert_before_markers_and_inherit,
2286 insert_from_string_before_markers, 1,
2287 nargs, args);
2288 return Qnil;
2291 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2292 doc: /* Insert COUNT copies of CHARACTER.
2293 Point, and before-insertion markers, are relocated as in the function `insert'.
2294 The optional third arg INHERIT, if non-nil, says to inherit text properties
2295 from adjoining text, if those properties are sticky. */)
2296 (character, count, inherit)
2297 Lisp_Object character, count, inherit;
2299 register unsigned char *string;
2300 register int strlen;
2301 register int i, n;
2302 int len;
2303 unsigned char str[MAX_MULTIBYTE_LENGTH];
2305 CHECK_NUMBER (character);
2306 CHECK_NUMBER (count);
2308 if (!NILP (current_buffer->enable_multibyte_characters))
2309 len = CHAR_STRING (XFASTINT (character), str);
2310 else
2311 str[0] = XFASTINT (character), len = 1;
2312 n = XINT (count) * len;
2313 if (n <= 0)
2314 return Qnil;
2315 strlen = min (n, 256 * len);
2316 string = (unsigned char *) alloca (strlen);
2317 for (i = 0; i < strlen; i++)
2318 string[i] = str[i % len];
2319 while (n >= strlen)
2321 QUIT;
2322 if (!NILP (inherit))
2323 insert_and_inherit (string, strlen);
2324 else
2325 insert (string, strlen);
2326 n -= strlen;
2328 if (n > 0)
2330 if (!NILP (inherit))
2331 insert_and_inherit (string, n);
2332 else
2333 insert (string, n);
2335 return Qnil;
2338 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2339 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2340 Both arguments are required.
2341 BYTE is a number of the range 0..255.
2343 If BYTE is 128..255 and the current buffer is multibyte, the
2344 corresponding eight-bit character is inserted.
2346 Point, and before-insertion markers, are relocated as in the function `insert'.
2347 The optional third arg INHERIT, if non-nil, says to inherit text properties
2348 from adjoining text, if those properties are sticky. */)
2349 (byte, count, inherit)
2350 Lisp_Object byte, count, inherit;
2352 CHECK_NUMBER (byte);
2353 if (XINT (byte) < 0 || XINT (byte) > 255)
2354 args_out_of_range_3 (byte, make_number (0), make_number (255));
2355 if (XINT (byte) >= 128
2356 && ! NILP (current_buffer->enable_multibyte_characters))
2357 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2358 return Finsert_char (byte, count, inherit);
2362 /* Making strings from buffer contents. */
2364 /* Return a Lisp_String containing the text of the current buffer from
2365 START to END. If text properties are in use and the current buffer
2366 has properties in the range specified, the resulting string will also
2367 have them, if PROPS is nonzero.
2369 We don't want to use plain old make_string here, because it calls
2370 make_uninit_string, which can cause the buffer arena to be
2371 compacted. make_string has no way of knowing that the data has
2372 been moved, and thus copies the wrong data into the string. This
2373 doesn't effect most of the other users of make_string, so it should
2374 be left as is. But we should use this function when conjuring
2375 buffer substrings. */
2377 Lisp_Object
2378 make_buffer_string (start, end, props)
2379 int start, end;
2380 int props;
2382 int start_byte = CHAR_TO_BYTE (start);
2383 int end_byte = CHAR_TO_BYTE (end);
2385 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2388 /* Return a Lisp_String containing the text of the current buffer from
2389 START / START_BYTE to END / END_BYTE.
2391 If text properties are in use and the current buffer
2392 has properties in the range specified, the resulting string will also
2393 have them, if PROPS is nonzero.
2395 We don't want to use plain old make_string here, because it calls
2396 make_uninit_string, which can cause the buffer arena to be
2397 compacted. make_string has no way of knowing that the data has
2398 been moved, and thus copies the wrong data into the string. This
2399 doesn't effect most of the other users of make_string, so it should
2400 be left as is. But we should use this function when conjuring
2401 buffer substrings. */
2403 Lisp_Object
2404 make_buffer_string_both (start, start_byte, end, end_byte, props)
2405 int start, start_byte, end, end_byte;
2406 int props;
2408 Lisp_Object result, tem, tem1;
2410 if (start < GPT && GPT < end)
2411 move_gap (start);
2413 if (! NILP (current_buffer->enable_multibyte_characters))
2414 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2415 else
2416 result = make_uninit_string (end - start);
2417 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
2418 end_byte - start_byte);
2420 /* If desired, update and copy the text properties. */
2421 if (props)
2423 update_buffer_properties (start, end);
2425 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2426 tem1 = Ftext_properties_at (make_number (start), Qnil);
2428 if (XINT (tem) != end || !NILP (tem1))
2429 copy_intervals_to_string (result, current_buffer, start,
2430 end - start);
2433 return result;
2436 /* Call Vbuffer_access_fontify_functions for the range START ... END
2437 in the current buffer, if necessary. */
2439 static void
2440 update_buffer_properties (start, end)
2441 int start, end;
2443 /* If this buffer has some access functions,
2444 call them, specifying the range of the buffer being accessed. */
2445 if (!NILP (Vbuffer_access_fontify_functions))
2447 Lisp_Object args[3];
2448 Lisp_Object tem;
2450 args[0] = Qbuffer_access_fontify_functions;
2451 XSETINT (args[1], start);
2452 XSETINT (args[2], end);
2454 /* But don't call them if we can tell that the work
2455 has already been done. */
2456 if (!NILP (Vbuffer_access_fontified_property))
2458 tem = Ftext_property_any (args[1], args[2],
2459 Vbuffer_access_fontified_property,
2460 Qnil, Qnil);
2461 if (! NILP (tem))
2462 Frun_hook_with_args (3, args);
2464 else
2465 Frun_hook_with_args (3, args);
2469 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2470 doc: /* Return the contents of part of the current buffer as a string.
2471 The two arguments START and END are character positions;
2472 they can be in either order.
2473 The string returned is multibyte if the buffer is multibyte.
2475 This function copies the text properties of that part of the buffer
2476 into the result string; if you don't want the text properties,
2477 use `buffer-substring-no-properties' instead. */)
2478 (start, end)
2479 Lisp_Object start, end;
2481 register int b, e;
2483 validate_region (&start, &end);
2484 b = XINT (start);
2485 e = XINT (end);
2487 return make_buffer_string (b, e, 1);
2490 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2491 Sbuffer_substring_no_properties, 2, 2, 0,
2492 doc: /* Return the characters of part of the buffer, without the text properties.
2493 The two arguments START and END are character positions;
2494 they can be in either order. */)
2495 (start, end)
2496 Lisp_Object start, end;
2498 register int b, e;
2500 validate_region (&start, &end);
2501 b = XINT (start);
2502 e = XINT (end);
2504 return make_buffer_string (b, e, 0);
2507 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2508 doc: /* Return the contents of the current buffer as a string.
2509 If narrowing is in effect, this function returns only the visible part
2510 of the buffer. */)
2513 return make_buffer_string (BEGV, ZV, 1);
2516 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2517 1, 3, 0,
2518 doc: /* Insert before point a substring of the contents of BUFFER.
2519 BUFFER may be a buffer or a buffer name.
2520 Arguments START and END are character positions specifying the substring.
2521 They default to the values of (point-min) and (point-max) in BUFFER. */)
2522 (buffer, start, end)
2523 Lisp_Object buffer, start, end;
2525 register int b, e, temp;
2526 register struct buffer *bp, *obuf;
2527 Lisp_Object buf;
2529 buf = Fget_buffer (buffer);
2530 if (NILP (buf))
2531 nsberror (buffer);
2532 bp = XBUFFER (buf);
2533 if (NILP (bp->name))
2534 error ("Selecting deleted buffer");
2536 if (NILP (start))
2537 b = BUF_BEGV (bp);
2538 else
2540 CHECK_NUMBER_COERCE_MARKER (start);
2541 b = XINT (start);
2543 if (NILP (end))
2544 e = BUF_ZV (bp);
2545 else
2547 CHECK_NUMBER_COERCE_MARKER (end);
2548 e = XINT (end);
2551 if (b > e)
2552 temp = b, b = e, e = temp;
2554 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2555 args_out_of_range (start, end);
2557 obuf = current_buffer;
2558 set_buffer_internal_1 (bp);
2559 update_buffer_properties (b, e);
2560 set_buffer_internal_1 (obuf);
2562 insert_from_buffer (bp, b, e - b, 0);
2563 return Qnil;
2566 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2567 6, 6, 0,
2568 doc: /* Compare two substrings of two buffers; return result as number.
2569 the value is -N if first string is less after N-1 chars,
2570 +N if first string is greater after N-1 chars, or 0 if strings match.
2571 Each substring is represented as three arguments: BUFFER, START and END.
2572 That makes six args in all, three for each substring.
2574 The value of `case-fold-search' in the current buffer
2575 determines whether case is significant or ignored. */)
2576 (buffer1, start1, end1, buffer2, start2, end2)
2577 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2579 register int begp1, endp1, begp2, endp2, temp;
2580 register struct buffer *bp1, *bp2;
2581 register Lisp_Object trt
2582 = (!NILP (current_buffer->case_fold_search)
2583 ? current_buffer->case_canon_table : Qnil);
2584 int chars = 0;
2585 int i1, i2, i1_byte, i2_byte;
2587 /* Find the first buffer and its substring. */
2589 if (NILP (buffer1))
2590 bp1 = current_buffer;
2591 else
2593 Lisp_Object buf1;
2594 buf1 = Fget_buffer (buffer1);
2595 if (NILP (buf1))
2596 nsberror (buffer1);
2597 bp1 = XBUFFER (buf1);
2598 if (NILP (bp1->name))
2599 error ("Selecting deleted buffer");
2602 if (NILP (start1))
2603 begp1 = BUF_BEGV (bp1);
2604 else
2606 CHECK_NUMBER_COERCE_MARKER (start1);
2607 begp1 = XINT (start1);
2609 if (NILP (end1))
2610 endp1 = BUF_ZV (bp1);
2611 else
2613 CHECK_NUMBER_COERCE_MARKER (end1);
2614 endp1 = XINT (end1);
2617 if (begp1 > endp1)
2618 temp = begp1, begp1 = endp1, endp1 = temp;
2620 if (!(BUF_BEGV (bp1) <= begp1
2621 && begp1 <= endp1
2622 && endp1 <= BUF_ZV (bp1)))
2623 args_out_of_range (start1, end1);
2625 /* Likewise for second substring. */
2627 if (NILP (buffer2))
2628 bp2 = current_buffer;
2629 else
2631 Lisp_Object buf2;
2632 buf2 = Fget_buffer (buffer2);
2633 if (NILP (buf2))
2634 nsberror (buffer2);
2635 bp2 = XBUFFER (buf2);
2636 if (NILP (bp2->name))
2637 error ("Selecting deleted buffer");
2640 if (NILP (start2))
2641 begp2 = BUF_BEGV (bp2);
2642 else
2644 CHECK_NUMBER_COERCE_MARKER (start2);
2645 begp2 = XINT (start2);
2647 if (NILP (end2))
2648 endp2 = BUF_ZV (bp2);
2649 else
2651 CHECK_NUMBER_COERCE_MARKER (end2);
2652 endp2 = XINT (end2);
2655 if (begp2 > endp2)
2656 temp = begp2, begp2 = endp2, endp2 = temp;
2658 if (!(BUF_BEGV (bp2) <= begp2
2659 && begp2 <= endp2
2660 && endp2 <= BUF_ZV (bp2)))
2661 args_out_of_range (start2, end2);
2663 i1 = begp1;
2664 i2 = begp2;
2665 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2666 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2668 while (i1 < endp1 && i2 < endp2)
2670 /* When we find a mismatch, we must compare the
2671 characters, not just the bytes. */
2672 int c1, c2;
2674 QUIT;
2676 if (! NILP (bp1->enable_multibyte_characters))
2678 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2679 BUF_INC_POS (bp1, i1_byte);
2680 i1++;
2682 else
2684 c1 = BUF_FETCH_BYTE (bp1, i1);
2685 c1 = unibyte_char_to_multibyte (c1);
2686 i1++;
2689 if (! NILP (bp2->enable_multibyte_characters))
2691 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2692 BUF_INC_POS (bp2, i2_byte);
2693 i2++;
2695 else
2697 c2 = BUF_FETCH_BYTE (bp2, i2);
2698 c2 = unibyte_char_to_multibyte (c2);
2699 i2++;
2702 if (!NILP (trt))
2704 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2705 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
2707 if (c1 < c2)
2708 return make_number (- 1 - chars);
2709 if (c1 > c2)
2710 return make_number (chars + 1);
2712 chars++;
2715 /* The strings match as far as they go.
2716 If one is shorter, that one is less. */
2717 if (chars < endp1 - begp1)
2718 return make_number (chars + 1);
2719 else if (chars < endp2 - begp2)
2720 return make_number (- chars - 1);
2722 /* Same length too => they are equal. */
2723 return make_number (0);
2726 static Lisp_Object
2727 subst_char_in_region_unwind (arg)
2728 Lisp_Object arg;
2730 return current_buffer->undo_list = arg;
2733 static Lisp_Object
2734 subst_char_in_region_unwind_1 (arg)
2735 Lisp_Object arg;
2737 return current_buffer->filename = arg;
2740 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2741 Ssubst_char_in_region, 4, 5, 0,
2742 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2743 If optional arg NOUNDO is non-nil, don't record this change for undo
2744 and don't mark the buffer as really changed.
2745 Both characters must have the same length of multi-byte form. */)
2746 (start, end, fromchar, tochar, noundo)
2747 Lisp_Object start, end, fromchar, tochar, noundo;
2749 register int pos, pos_byte, stop, i, len, end_byte;
2750 /* Keep track of the first change in the buffer:
2751 if 0 we haven't found it yet.
2752 if < 0 we've found it and we've run the before-change-function.
2753 if > 0 we've actually performed it and the value is its position. */
2754 int changed = 0;
2755 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2756 unsigned char *p;
2757 int count = SPECPDL_INDEX ();
2758 #define COMBINING_NO 0
2759 #define COMBINING_BEFORE 1
2760 #define COMBINING_AFTER 2
2761 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2762 int maybe_byte_combining = COMBINING_NO;
2763 int last_changed = 0;
2764 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2766 restart:
2768 validate_region (&start, &end);
2769 CHECK_NUMBER (fromchar);
2770 CHECK_NUMBER (tochar);
2772 if (multibyte_p)
2774 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2775 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2776 error ("Characters in `subst-char-in-region' have different byte-lengths");
2777 if (!ASCII_BYTE_P (*tostr))
2779 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2780 complete multibyte character, it may be combined with the
2781 after bytes. If it is in the range 0xA0..0xFF, it may be
2782 combined with the before and after bytes. */
2783 if (!CHAR_HEAD_P (*tostr))
2784 maybe_byte_combining = COMBINING_BOTH;
2785 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2786 maybe_byte_combining = COMBINING_AFTER;
2789 else
2791 len = 1;
2792 fromstr[0] = XFASTINT (fromchar);
2793 tostr[0] = XFASTINT (tochar);
2796 pos = XINT (start);
2797 pos_byte = CHAR_TO_BYTE (pos);
2798 stop = CHAR_TO_BYTE (XINT (end));
2799 end_byte = stop;
2801 /* If we don't want undo, turn off putting stuff on the list.
2802 That's faster than getting rid of things,
2803 and it prevents even the entry for a first change.
2804 Also inhibit locking the file. */
2805 if (!changed && !NILP (noundo))
2807 record_unwind_protect (subst_char_in_region_unwind,
2808 current_buffer->undo_list);
2809 current_buffer->undo_list = Qt;
2810 /* Don't do file-locking. */
2811 record_unwind_protect (subst_char_in_region_unwind_1,
2812 current_buffer->filename);
2813 current_buffer->filename = Qnil;
2816 if (pos_byte < GPT_BYTE)
2817 stop = min (stop, GPT_BYTE);
2818 while (1)
2820 int pos_byte_next = pos_byte;
2822 if (pos_byte >= stop)
2824 if (pos_byte >= end_byte) break;
2825 stop = end_byte;
2827 p = BYTE_POS_ADDR (pos_byte);
2828 if (multibyte_p)
2829 INC_POS (pos_byte_next);
2830 else
2831 ++pos_byte_next;
2832 if (pos_byte_next - pos_byte == len
2833 && p[0] == fromstr[0]
2834 && (len == 1
2835 || (p[1] == fromstr[1]
2836 && (len == 2 || (p[2] == fromstr[2]
2837 && (len == 3 || p[3] == fromstr[3]))))))
2839 if (changed < 0)
2840 /* We've already seen this and run the before-change-function;
2841 this time we only need to record the actual position. */
2842 changed = pos;
2843 else if (!changed)
2845 changed = -1;
2846 modify_region (current_buffer, pos, XINT (end), 0);
2848 if (! NILP (noundo))
2850 if (MODIFF - 1 == SAVE_MODIFF)
2851 SAVE_MODIFF++;
2852 if (MODIFF - 1 == current_buffer->auto_save_modified)
2853 current_buffer->auto_save_modified++;
2856 /* The before-change-function may have moved the gap
2857 or even modified the buffer so we should start over. */
2858 goto restart;
2861 /* Take care of the case where the new character
2862 combines with neighboring bytes. */
2863 if (maybe_byte_combining
2864 && (maybe_byte_combining == COMBINING_AFTER
2865 ? (pos_byte_next < Z_BYTE
2866 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2867 : ((pos_byte_next < Z_BYTE
2868 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2869 || (pos_byte > BEG_BYTE
2870 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2872 Lisp_Object tem, string;
2874 struct gcpro gcpro1;
2876 tem = current_buffer->undo_list;
2877 GCPRO1 (tem);
2879 /* Make a multibyte string containing this single character. */
2880 string = make_multibyte_string (tostr, 1, len);
2881 /* replace_range is less efficient, because it moves the gap,
2882 but it handles combining correctly. */
2883 replace_range (pos, pos + 1, string,
2884 0, 0, 1);
2885 pos_byte_next = CHAR_TO_BYTE (pos);
2886 if (pos_byte_next > pos_byte)
2887 /* Before combining happened. We should not increment
2888 POS. So, to cancel the later increment of POS,
2889 decrease it now. */
2890 pos--;
2891 else
2892 INC_POS (pos_byte_next);
2894 if (! NILP (noundo))
2895 current_buffer->undo_list = tem;
2897 UNGCPRO;
2899 else
2901 if (NILP (noundo))
2902 record_change (pos, 1);
2903 for (i = 0; i < len; i++) *p++ = tostr[i];
2905 last_changed = pos + 1;
2907 pos_byte = pos_byte_next;
2908 pos++;
2911 if (changed > 0)
2913 signal_after_change (changed,
2914 last_changed - changed, last_changed - changed);
2915 update_compositions (changed, last_changed, CHECK_ALL);
2918 unbind_to (count, Qnil);
2919 return Qnil;
2923 static Lisp_Object check_translation P_ ((int, int, int, Lisp_Object));
2925 /* Helper function for Ftranslate_region_internal.
2927 Check if a character sequence at POS (POS_BYTE) matches an element
2928 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2929 element is found, return it. Otherwise return Qnil. */
2931 static Lisp_Object
2932 check_translation (pos, pos_byte, end, val)
2933 int pos, pos_byte, end;
2934 Lisp_Object val;
2936 int buf_size = 16, buf_used = 0;
2937 int *buf = alloca (sizeof (int) * buf_size);
2939 for (; CONSP (val); val = XCDR (val))
2941 Lisp_Object elt;
2942 int len, i;
2944 elt = XCAR (val);
2945 if (! CONSP (elt))
2946 continue;
2947 elt = XCAR (elt);
2948 if (! VECTORP (elt))
2949 continue;
2950 len = ASIZE (elt);
2951 if (len <= end - pos)
2953 for (i = 0; i < len; i++)
2955 if (buf_used <= i)
2957 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2958 int len;
2960 if (buf_used == buf_size)
2962 int *newbuf;
2964 buf_size += 16;
2965 newbuf = alloca (sizeof (int) * buf_size);
2966 memcpy (newbuf, buf, sizeof (int) * buf_used);
2967 buf = newbuf;
2969 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, 0, len);
2970 pos_byte += len;
2972 if (XINT (AREF (elt, i)) != buf[i])
2973 break;
2975 if (i == len)
2976 return XCAR (val);
2979 return Qnil;
2983 DEFUN ("translate-region-internal", Ftranslate_region_internal,
2984 Stranslate_region_internal, 3, 3, 0,
2985 doc: /* Internal use only.
2986 From START to END, translate characters according to TABLE.
2987 TABLE is a string or a char-table; the Nth character in it is the
2988 mapping for the character with code N.
2989 It returns the number of characters changed. */)
2990 (start, end, table)
2991 Lisp_Object start;
2992 Lisp_Object end;
2993 register Lisp_Object table;
2995 register unsigned char *tt; /* Trans table. */
2996 register int nc; /* New character. */
2997 int cnt; /* Number of changes made. */
2998 int size; /* Size of translate table. */
2999 int pos, pos_byte, end_pos;
3000 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
3001 int string_multibyte;
3002 Lisp_Object val;
3004 validate_region (&start, &end);
3005 if (CHAR_TABLE_P (table))
3007 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3008 error ("Not a translation table");
3009 size = MAX_CHAR;
3010 tt = NULL;
3012 else
3014 CHECK_STRING (table);
3016 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3017 table = string_make_unibyte (table);
3018 string_multibyte = SCHARS (table) < SBYTES (table);
3019 size = SBYTES (table);
3020 tt = SDATA (table);
3023 pos = XINT (start);
3024 pos_byte = CHAR_TO_BYTE (pos);
3025 end_pos = XINT (end);
3026 modify_region (current_buffer, pos, end_pos, 0);
3028 cnt = 0;
3029 for (; pos < end_pos; )
3031 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3032 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3033 int len, str_len;
3034 int oc;
3035 Lisp_Object val;
3037 if (multibyte)
3038 oc = STRING_CHAR_AND_LENGTH (p, MAX_MULTIBYTE_LENGTH, len);
3039 else
3040 oc = *p, len = 1;
3041 if (oc < size)
3043 if (tt)
3045 /* Reload as signal_after_change in last iteration may GC. */
3046 tt = SDATA (table);
3047 if (string_multibyte)
3049 str = tt + string_char_to_byte (table, oc);
3050 nc = STRING_CHAR_AND_LENGTH (str, MAX_MULTIBYTE_LENGTH,
3051 str_len);
3053 else
3055 nc = tt[oc];
3056 if (! ASCII_BYTE_P (nc) && multibyte)
3058 str_len = BYTE8_STRING (nc, buf);
3059 str = buf;
3061 else
3063 str_len = 1;
3064 str = tt + oc;
3068 else
3070 int c;
3072 nc = oc;
3073 val = CHAR_TABLE_REF (table, oc);
3074 if (CHARACTERP (val)
3075 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3077 nc = c;
3078 str_len = CHAR_STRING (nc, buf);
3079 str = buf;
3081 else if (VECTORP (val) || (CONSP (val)))
3083 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3084 where TO is TO-CHAR or [TO-CHAR ...]. */
3085 nc = -1;
3089 if (nc != oc && nc >= 0)
3091 /* Simple one char to one char translation. */
3092 if (len != str_len)
3094 Lisp_Object string;
3096 /* This is less efficient, because it moves the gap,
3097 but it should handle multibyte characters correctly. */
3098 string = make_multibyte_string (str, 1, str_len);
3099 replace_range (pos, pos + 1, string, 1, 0, 1);
3100 len = str_len;
3102 else
3104 record_change (pos, 1);
3105 while (str_len-- > 0)
3106 *p++ = *str++;
3107 signal_after_change (pos, 1, 1);
3108 update_compositions (pos, pos + 1, CHECK_BORDER);
3110 ++cnt;
3112 else if (nc < 0)
3114 Lisp_Object string;
3116 if (CONSP (val))
3118 val = check_translation (pos, pos_byte, end_pos, val);
3119 if (NILP (val))
3121 pos_byte += len;
3122 pos++;
3123 continue;
3125 /* VAL is ([FROM-CHAR ...] . TO). */
3126 len = ASIZE (XCAR (val));
3127 val = XCDR (val);
3129 else
3130 len = 1;
3132 if (VECTORP (val))
3134 int i;
3136 string = Fmake_string (make_number (ASIZE (val)),
3137 AREF (val, 0));
3138 for (i = 1; i < ASIZE (val); i++)
3139 Faset (string, make_number (i), AREF (val, i));
3141 else
3143 string = Fmake_string (make_number (1), val);
3145 replace_range (pos, pos + len, string, 1, 0, 1);
3146 pos_byte += SBYTES (string);
3147 pos += SCHARS (string);
3148 cnt += SCHARS (string);
3149 end_pos += SCHARS (string) - len;
3150 continue;
3153 pos_byte += len;
3154 pos++;
3157 return make_number (cnt);
3160 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3161 doc: /* Delete the text between point and mark.
3163 When called from a program, expects two arguments,
3164 positions (integers or markers) specifying the stretch to be deleted. */)
3165 (start, end)
3166 Lisp_Object start, end;
3168 validate_region (&start, &end);
3169 del_range (XINT (start), XINT (end));
3170 return Qnil;
3173 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3174 Sdelete_and_extract_region, 2, 2, 0,
3175 doc: /* Delete the text between START and END and return it. */)
3176 (start, end)
3177 Lisp_Object start, end;
3179 validate_region (&start, &end);
3180 if (XINT (start) == XINT (end))
3181 return empty_unibyte_string;
3182 return del_range_1 (XINT (start), XINT (end), 1, 1);
3185 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3186 doc: /* Remove restrictions (narrowing) from current buffer.
3187 This allows the buffer's full text to be seen and edited. */)
3190 if (BEG != BEGV || Z != ZV)
3191 current_buffer->clip_changed = 1;
3192 BEGV = BEG;
3193 BEGV_BYTE = BEG_BYTE;
3194 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3195 /* Changing the buffer bounds invalidates any recorded current column. */
3196 invalidate_current_column ();
3197 return Qnil;
3200 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3201 doc: /* Restrict editing in this buffer to the current region.
3202 The rest of the text becomes temporarily invisible and untouchable
3203 but is not deleted; if you save the buffer in a file, the invisible
3204 text is included in the file. \\[widen] makes all visible again.
3205 See also `save-restriction'.
3207 When calling from a program, pass two arguments; positions (integers
3208 or markers) bounding the text that should remain visible. */)
3209 (start, end)
3210 register Lisp_Object start, end;
3212 CHECK_NUMBER_COERCE_MARKER (start);
3213 CHECK_NUMBER_COERCE_MARKER (end);
3215 if (XINT (start) > XINT (end))
3217 Lisp_Object tem;
3218 tem = start; start = end; end = tem;
3221 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3222 args_out_of_range (start, end);
3224 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3225 current_buffer->clip_changed = 1;
3227 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3228 SET_BUF_ZV (current_buffer, XFASTINT (end));
3229 if (PT < XFASTINT (start))
3230 SET_PT (XFASTINT (start));
3231 if (PT > XFASTINT (end))
3232 SET_PT (XFASTINT (end));
3233 /* Changing the buffer bounds invalidates any recorded current column. */
3234 invalidate_current_column ();
3235 return Qnil;
3238 Lisp_Object
3239 save_restriction_save ()
3241 if (BEGV == BEG && ZV == Z)
3242 /* The common case that the buffer isn't narrowed.
3243 We return just the buffer object, which save_restriction_restore
3244 recognizes as meaning `no restriction'. */
3245 return Fcurrent_buffer ();
3246 else
3247 /* We have to save a restriction, so return a pair of markers, one
3248 for the beginning and one for the end. */
3250 Lisp_Object beg, end;
3252 beg = buildmark (BEGV, BEGV_BYTE);
3253 end = buildmark (ZV, ZV_BYTE);
3255 /* END must move forward if text is inserted at its exact location. */
3256 XMARKER(end)->insertion_type = 1;
3258 return Fcons (beg, end);
3262 Lisp_Object
3263 save_restriction_restore (data)
3264 Lisp_Object data;
3266 if (CONSP (data))
3267 /* A pair of marks bounding a saved restriction. */
3269 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3270 struct Lisp_Marker *end = XMARKER (XCDR (data));
3271 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
3273 if (buf /* Verify marker still points to a buffer. */
3274 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3275 /* The restriction has changed from the saved one, so restore
3276 the saved restriction. */
3278 int pt = BUF_PT (buf);
3280 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3281 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3283 if (pt < beg->charpos || pt > end->charpos)
3284 /* The point is outside the new visible range, move it inside. */
3285 SET_BUF_PT_BOTH (buf,
3286 clip_to_bounds (beg->charpos, pt, end->charpos),
3287 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3288 end->bytepos));
3290 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3293 else
3294 /* A buffer, which means that there was no old restriction. */
3296 struct buffer *buf = XBUFFER (data);
3298 if (buf /* Verify marker still points to a buffer. */
3299 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3300 /* The buffer has been narrowed, get rid of the narrowing. */
3302 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3303 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3305 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3309 return Qnil;
3312 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3313 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3314 The buffer's restrictions make parts of the beginning and end invisible.
3315 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3316 This special form, `save-restriction', saves the current buffer's restrictions
3317 when it is entered, and restores them when it is exited.
3318 So any `narrow-to-region' within BODY lasts only until the end of the form.
3319 The old restrictions settings are restored
3320 even in case of abnormal exit (throw or error).
3322 The value returned is the value of the last form in BODY.
3324 Note: if you are using both `save-excursion' and `save-restriction',
3325 use `save-excursion' outermost:
3326 (save-excursion (save-restriction ...))
3328 usage: (save-restriction &rest BODY) */)
3329 (body)
3330 Lisp_Object body;
3332 register Lisp_Object val;
3333 int count = SPECPDL_INDEX ();
3335 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3336 val = Fprogn (body);
3337 return unbind_to (count, val);
3340 /* Buffer for the most recent text displayed by Fmessage_box. */
3341 static char *message_text;
3343 /* Allocated length of that buffer. */
3344 static int message_length;
3346 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3347 doc: /* Display a message at the bottom of the screen.
3348 The message also goes into the `*Messages*' buffer.
3349 \(In keyboard macros, that's all it does.)
3350 Return the message.
3352 The first argument is a format control string, and the rest are data
3353 to be formatted under control of the string. See `format' for details.
3355 Note: Use (message "%s" VALUE) to print the value of expressions and
3356 variables to avoid accidentally interpreting `%' as format specifiers.
3358 If the first argument is nil or the empty string, the function clears
3359 any existing message; this lets the minibuffer contents show. See
3360 also `current-message'.
3362 usage: (message FORMAT-STRING &rest ARGS) */)
3363 (nargs, args)
3364 int nargs;
3365 Lisp_Object *args;
3367 if (NILP (args[0])
3368 || (STRINGP (args[0])
3369 && SBYTES (args[0]) == 0))
3371 message (0);
3372 return args[0];
3374 else
3376 register Lisp_Object val;
3377 val = Fformat (nargs, args);
3378 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
3379 return val;
3383 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3384 doc: /* Display a message, in a dialog box if possible.
3385 If a dialog box is not available, use the echo area.
3386 The first argument is a format control string, and the rest are data
3387 to be formatted under control of the string. See `format' for details.
3389 If the first argument is nil or the empty string, clear any existing
3390 message; let the minibuffer contents show.
3392 usage: (message-box FORMAT-STRING &rest ARGS) */)
3393 (nargs, args)
3394 int nargs;
3395 Lisp_Object *args;
3397 if (NILP (args[0]))
3399 message (0);
3400 return Qnil;
3402 else
3404 register Lisp_Object val;
3405 val = Fformat (nargs, args);
3406 #ifdef HAVE_MENUS
3407 /* The MS-DOS frames support popup menus even though they are
3408 not FRAME_WINDOW_P. */
3409 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3410 || FRAME_MSDOS_P (XFRAME (selected_frame)))
3412 Lisp_Object pane, menu, obj;
3413 struct gcpro gcpro1;
3414 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3415 GCPRO1 (pane);
3416 menu = Fcons (val, pane);
3417 obj = Fx_popup_dialog (Qt, menu, Qt);
3418 UNGCPRO;
3419 return val;
3421 #endif /* HAVE_MENUS */
3422 /* Copy the data so that it won't move when we GC. */
3423 if (! message_text)
3425 message_text = (char *)xmalloc (80);
3426 message_length = 80;
3428 if (SBYTES (val) > message_length)
3430 message_length = SBYTES (val);
3431 message_text = (char *)xrealloc (message_text, message_length);
3433 bcopy (SDATA (val), message_text, SBYTES (val));
3434 message2 (message_text, SBYTES (val),
3435 STRING_MULTIBYTE (val));
3436 return val;
3439 #ifdef HAVE_MENUS
3440 extern Lisp_Object last_nonmenu_event;
3441 #endif
3443 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3444 doc: /* Display a message in a dialog box or in the echo area.
3445 If this command was invoked with the mouse, use a dialog box if
3446 `use-dialog-box' is non-nil.
3447 Otherwise, use the echo area.
3448 The first argument is a format control string, and the rest are data
3449 to be formatted under control of the string. See `format' for details.
3451 If the first argument is nil or the empty string, clear any existing
3452 message; let the minibuffer contents show.
3454 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3455 (nargs, args)
3456 int nargs;
3457 Lisp_Object *args;
3459 #ifdef HAVE_MENUS
3460 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3461 && use_dialog_box)
3462 return Fmessage_box (nargs, args);
3463 #endif
3464 return Fmessage (nargs, args);
3467 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3468 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3471 return current_message ();
3475 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3476 doc: /* Return a copy of STRING with text properties added.
3477 First argument is the string to copy.
3478 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3479 properties to add to the result.
3480 usage: (propertize STRING &rest PROPERTIES) */)
3481 (nargs, args)
3482 int nargs;
3483 Lisp_Object *args;
3485 Lisp_Object properties, string;
3486 struct gcpro gcpro1, gcpro2;
3487 int i;
3489 /* Number of args must be odd. */
3490 if ((nargs & 1) == 0 || nargs < 1)
3491 error ("Wrong number of arguments");
3493 properties = string = Qnil;
3494 GCPRO2 (properties, string);
3496 /* First argument must be a string. */
3497 CHECK_STRING (args[0]);
3498 string = Fcopy_sequence (args[0]);
3500 for (i = 1; i < nargs; i += 2)
3501 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3503 Fadd_text_properties (make_number (0),
3504 make_number (SCHARS (string)),
3505 properties, string);
3506 RETURN_UNGCPRO (string);
3510 /* Number of bytes that STRING will occupy when put into the result.
3511 MULTIBYTE is nonzero if the result should be multibyte. */
3513 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3514 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3515 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3516 : SBYTES (STRING))
3518 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3519 doc: /* Format a string out of a format-string and arguments.
3520 The first argument is a format control string.
3521 The other arguments are substituted into it to make the result, a string.
3523 The format control string may contain %-sequences meaning to substitute
3524 the next available argument:
3526 %s means print a string argument. Actually, prints any object, with `princ'.
3527 %d means print as number in decimal (%o octal, %x hex).
3528 %X is like %x, but uses upper case.
3529 %e means print a number in exponential notation.
3530 %f means print a number in decimal-point notation.
3531 %g means print a number in exponential notation
3532 or decimal-point notation, whichever uses fewer characters.
3533 %c means print a number as a single character.
3534 %S means print any object as an s-expression (using `prin1').
3536 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3537 Use %% to put a single % into the output.
3539 A %-sequence may contain optional flag, width, and precision
3540 specifiers, as follows:
3542 %<flags><width><precision>character
3544 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3546 The + flag character inserts a + before any positive number, while a
3547 space inserts a space before any positive number; these flags only
3548 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3549 The # flag means to use an alternate display form for %o, %x, %X, %e,
3550 %f, and %g sequences. The - and 0 flags affect the width specifier,
3551 as described below.
3553 The width specifier supplies a lower limit for the length of the
3554 printed representation. The padding, if any, normally goes on the
3555 left, but it goes on the right if the - flag is present. The padding
3556 character is normally a space, but it is 0 if the 0 flag is present.
3557 The - flag takes precedence over the 0 flag.
3559 For %e, %f, and %g sequences, the number after the "." in the
3560 precision specifier says how many decimal places to show; if zero, the
3561 decimal point itself is omitted. For %s and %S, the precision
3562 specifier truncates the string to the given width.
3564 usage: (format STRING &rest OBJECTS) */)
3565 (nargs, args)
3566 int nargs;
3567 register Lisp_Object *args;
3569 register int n; /* The number of the next arg to substitute */
3570 register int total; /* An estimate of the final length */
3571 char *buf, *p;
3572 register unsigned char *format, *end, *format_start;
3573 int nchars;
3574 /* Nonzero if the output should be a multibyte string,
3575 which is true if any of the inputs is one. */
3576 int multibyte = 0;
3577 /* When we make a multibyte string, we must pay attention to the
3578 byte combining problem, i.e., a byte may be combined with a
3579 multibyte charcter of the previous string. This flag tells if we
3580 must consider such a situation or not. */
3581 int maybe_combine_byte;
3582 unsigned char *this_format;
3583 /* Precision for each spec, or -1, a flag value meaning no precision
3584 was given in that spec. Element 0, corresonding to the format
3585 string itself, will not be used. Element NARGS, corresponding to
3586 no argument, *will* be assigned to in the case that a `%' and `.'
3587 occur after the final format specifier. */
3588 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
3589 int longest_format;
3590 Lisp_Object val;
3591 int arg_intervals = 0;
3592 USE_SAFE_ALLOCA;
3594 /* discarded[I] is 1 if byte I of the format
3595 string was not copied into the output.
3596 It is 2 if byte I was not the first byte of its character. */
3597 char *discarded = 0;
3599 /* Each element records, for one argument,
3600 the start and end bytepos in the output string,
3601 and whether the argument is a string with intervals.
3602 info[0] is unused. Unused elements have -1 for start. */
3603 struct info
3605 int start, end, intervals;
3606 } *info = 0;
3608 /* It should not be necessary to GCPRO ARGS, because
3609 the caller in the interpreter should take care of that. */
3611 /* Try to determine whether the result should be multibyte.
3612 This is not always right; sometimes the result needs to be multibyte
3613 because of an object that we will pass through prin1,
3614 and in that case, we won't know it here. */
3615 for (n = 0; n < nargs; n++)
3617 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3618 multibyte = 1;
3619 /* Piggyback on this loop to initialize precision[N]. */
3620 precision[n] = -1;
3622 precision[nargs] = -1;
3624 CHECK_STRING (args[0]);
3625 /* We may have to change "%S" to "%s". */
3626 args[0] = Fcopy_sequence (args[0]);
3628 /* GC should never happen here, so abort if it does. */
3629 abort_on_gc++;
3631 /* If we start out planning a unibyte result,
3632 then discover it has to be multibyte, we jump back to retry.
3633 That can only happen from the first large while loop below. */
3634 retry:
3636 format = SDATA (args[0]);
3637 format_start = format;
3638 end = format + SBYTES (args[0]);
3639 longest_format = 0;
3641 /* Make room in result for all the non-%-codes in the control string. */
3642 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
3644 /* Allocate the info and discarded tables. */
3646 int nbytes = (nargs+1) * sizeof *info;
3647 int i;
3648 if (!info)
3649 info = (struct info *) alloca (nbytes);
3650 bzero (info, nbytes);
3651 for (i = 0; i <= nargs; i++)
3652 info[i].start = -1;
3653 if (!discarded)
3654 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
3655 bzero (discarded, SBYTES (args[0]));
3658 /* Add to TOTAL enough space to hold the converted arguments. */
3660 n = 0;
3661 while (format != end)
3662 if (*format++ == '%')
3664 int thissize = 0;
3665 int actual_width = 0;
3666 unsigned char *this_format_start = format - 1;
3667 int field_width = 0;
3669 /* General format specifications look like
3671 '%' [flags] [field-width] [precision] format
3673 where
3675 flags ::= [-+ #0]+
3676 field-width ::= [0-9]+
3677 precision ::= '.' [0-9]*
3679 If a field-width is specified, it specifies to which width
3680 the output should be padded with blanks, if the output
3681 string is shorter than field-width.
3683 If precision is specified, it specifies the number of
3684 digits to print after the '.' for floats, or the max.
3685 number of chars to print from a string. */
3687 while (format != end
3688 && (*format == '-' || *format == '0' || *format == '#'
3689 || * format == ' ' || *format == '+'))
3690 ++format;
3692 if (*format >= '0' && *format <= '9')
3694 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3695 field_width = 10 * field_width + *format - '0';
3698 /* N is not incremented for another few lines below, so refer to
3699 element N+1 (which might be precision[NARGS]). */
3700 if (*format == '.')
3702 ++format;
3703 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3704 precision[n+1] = 10 * precision[n+1] + *format - '0';
3707 /* Extra +1 for 'l' that we may need to insert into the
3708 format. */
3709 if (format - this_format_start + 2 > longest_format)
3710 longest_format = format - this_format_start + 2;
3712 if (format == end)
3713 error ("Format string ends in middle of format specifier");
3714 if (*format == '%')
3715 format++;
3716 else if (++n >= nargs)
3717 error ("Not enough arguments for format string");
3718 else if (*format == 'S')
3720 /* For `S', prin1 the argument and then treat like a string. */
3721 register Lisp_Object tem;
3722 tem = Fprin1_to_string (args[n], Qnil);
3723 if (STRING_MULTIBYTE (tem) && ! multibyte)
3725 multibyte = 1;
3726 goto retry;
3728 args[n] = tem;
3729 /* If we restart the loop, we should not come here again
3730 because args[n] is now a string and calling
3731 Fprin1_to_string on it produces superflous double
3732 quotes. So, change "%S" to "%s" now. */
3733 *format = 's';
3734 goto string;
3736 else if (SYMBOLP (args[n]))
3738 args[n] = SYMBOL_NAME (args[n]);
3739 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3741 multibyte = 1;
3742 goto retry;
3744 goto string;
3746 else if (STRINGP (args[n]))
3748 string:
3749 if (*format != 's' && *format != 'S')
3750 error ("Format specifier doesn't match argument type");
3751 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3752 to be as large as is calculated here. Easy check for
3753 the case PRECISION = 0. */
3754 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
3755 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
3757 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3758 else if (INTEGERP (args[n]) && *format != 's')
3760 /* The following loop assumes the Lisp type indicates
3761 the proper way to pass the argument.
3762 So make sure we have a flonum if the argument should
3763 be a double. */
3764 if (*format == 'e' || *format == 'f' || *format == 'g')
3765 args[n] = Ffloat (args[n]);
3766 else
3767 if (*format != 'd' && *format != 'o' && *format != 'x'
3768 && *format != 'i' && *format != 'X' && *format != 'c')
3769 error ("Invalid format operation %%%c", *format);
3771 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
3772 if (*format == 'c')
3774 if (! ASCII_CHAR_P (XINT (args[n]))
3775 /* Note: No one can remeber why we have to treat
3776 the character 0 as a multibyte character here.
3777 But, until it causes a real problem, let's
3778 don't change it. */
3779 || XINT (args[n]) == 0)
3781 if (! multibyte)
3783 multibyte = 1;
3784 goto retry;
3786 args[n] = Fchar_to_string (args[n]);
3787 thissize = SBYTES (args[n]);
3789 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3791 args[n]
3792 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3793 thissize = SBYTES (args[n]);
3797 else if (FLOATP (args[n]) && *format != 's')
3799 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3801 if (*format != 'd' && *format != 'o' && *format != 'x'
3802 && *format != 'i' && *format != 'X' && *format != 'c')
3803 error ("Invalid format operation %%%c", *format);
3804 /* This fails unnecessarily if args[n] is bigger than
3805 most-positive-fixnum but smaller than MAXINT.
3806 These cases are important because we sometimes use floats
3807 to represent such integer values (typically such values
3808 come from UIDs or PIDs). */
3809 /* args[n] = Ftruncate (args[n], Qnil); */
3812 /* Note that we're using sprintf to print floats,
3813 so we have to take into account what that function
3814 prints. */
3815 /* Filter out flag value of -1. */
3816 thissize = (MAX_10_EXP + 100
3817 + (precision[n] > 0 ? precision[n] : 0));
3819 else
3821 /* Anything but a string, convert to a string using princ. */
3822 register Lisp_Object tem;
3823 tem = Fprin1_to_string (args[n], Qt);
3824 if (STRING_MULTIBYTE (tem) && ! multibyte)
3826 multibyte = 1;
3827 goto retry;
3829 args[n] = tem;
3830 goto string;
3833 thissize += max (0, field_width - actual_width);
3834 total += thissize + 4;
3837 abort_on_gc--;
3839 /* Now we can no longer jump to retry.
3840 TOTAL and LONGEST_FORMAT are known for certain. */
3842 this_format = (unsigned char *) alloca (longest_format + 1);
3844 /* Allocate the space for the result.
3845 Note that TOTAL is an overestimate. */
3846 SAFE_ALLOCA (buf, char *, total);
3848 p = buf;
3849 nchars = 0;
3850 n = 0;
3852 /* Scan the format and store result in BUF. */
3853 format = SDATA (args[0]);
3854 format_start = format;
3855 end = format + SBYTES (args[0]);
3856 maybe_combine_byte = 0;
3857 while (format != end)
3859 if (*format == '%')
3861 int minlen;
3862 int negative = 0;
3863 unsigned char *this_format_start = format;
3865 discarded[format - format_start] = 1;
3866 format++;
3868 while (index("-+0# ", *format))
3870 if (*format == '-')
3872 negative = 1;
3874 discarded[format - format_start] = 1;
3875 ++format;
3878 minlen = atoi (format);
3880 while ((*format >= '0' && *format <= '9') || *format == '.')
3882 discarded[format - format_start] = 1;
3883 format++;
3886 if (*format++ == '%')
3888 *p++ = '%';
3889 nchars++;
3890 continue;
3893 ++n;
3895 discarded[format - format_start - 1] = 1;
3896 info[n].start = nchars;
3898 if (STRINGP (args[n]))
3900 /* handle case (precision[n] >= 0) */
3902 int width, padding;
3903 int nbytes, start, end;
3904 int nchars_string;
3906 /* lisp_string_width ignores a precision of 0, but GNU
3907 libc functions print 0 characters when the precision
3908 is 0. Imitate libc behavior here. Changing
3909 lisp_string_width is the right thing, and will be
3910 done, but meanwhile we work with it. */
3912 if (precision[n] == 0)
3913 width = nchars_string = nbytes = 0;
3914 else if (precision[n] > 0)
3915 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3916 else
3917 { /* no precision spec given for this argument */
3918 width = lisp_string_width (args[n], -1, NULL, NULL);
3919 nbytes = SBYTES (args[n]);
3920 nchars_string = SCHARS (args[n]);
3923 /* If spec requires it, pad on right with spaces. */
3924 padding = minlen - width;
3925 if (! negative)
3926 while (padding-- > 0)
3928 *p++ = ' ';
3929 ++nchars;
3932 info[n].start = start = nchars;
3933 nchars += nchars_string;
3934 end = nchars;
3936 if (p > buf
3937 && multibyte
3938 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3939 && STRING_MULTIBYTE (args[n])
3940 && !CHAR_HEAD_P (SREF (args[n], 0)))
3941 maybe_combine_byte = 1;
3943 p += copy_text (SDATA (args[n]), p,
3944 nbytes,
3945 STRING_MULTIBYTE (args[n]), multibyte);
3947 info[n].end = nchars;
3949 if (negative)
3950 while (padding-- > 0)
3952 *p++ = ' ';
3953 nchars++;
3956 /* If this argument has text properties, record where
3957 in the result string it appears. */
3958 if (STRING_INTERVALS (args[n]))
3959 info[n].intervals = arg_intervals = 1;
3961 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3963 int this_nchars;
3965 bcopy (this_format_start, this_format,
3966 format - this_format_start);
3967 this_format[format - this_format_start] = 0;
3969 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
3970 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3971 else
3973 if (sizeof (EMACS_INT) > sizeof (int)
3974 && format[-1] != 'c')
3976 /* Insert 'l' before format spec. */
3977 this_format[format - this_format_start]
3978 = this_format[format - this_format_start - 1];
3979 this_format[format - this_format_start - 1] = 'l';
3980 this_format[format - this_format_start + 1] = 0;
3983 if (INTEGERP (args[n]))
3985 if (format[-1] == 'c')
3986 sprintf (p, this_format, (int) XINT (args[n]));
3987 else if (format[-1] == 'd')
3988 sprintf (p, this_format, XINT (args[n]));
3989 /* Don't sign-extend for octal or hex printing. */
3990 else
3991 sprintf (p, this_format, XUINT (args[n]));
3993 else if (format[-1] == 'c')
3994 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
3995 else if (format[-1] == 'd')
3996 /* Maybe we should use "%1.0f" instead so it also works
3997 for values larger than MAXINT. */
3998 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
3999 else
4000 /* Don't sign-extend for octal or hex printing. */
4001 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
4004 if (p > buf
4005 && multibyte
4006 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4007 && !CHAR_HEAD_P (*((unsigned char *) p)))
4008 maybe_combine_byte = 1;
4009 this_nchars = strlen (p);
4010 if (multibyte)
4011 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
4012 else
4013 p += this_nchars;
4014 nchars += this_nchars;
4015 info[n].end = nchars;
4019 else if (STRING_MULTIBYTE (args[0]))
4021 /* Copy a whole multibyte character. */
4022 if (p > buf
4023 && multibyte
4024 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4025 && !CHAR_HEAD_P (*format))
4026 maybe_combine_byte = 1;
4027 *p++ = *format++;
4028 while (! CHAR_HEAD_P (*format))
4030 discarded[format - format_start] = 2;
4031 *p++ = *format++;
4033 nchars++;
4035 else if (multibyte)
4037 /* Convert a single-byte character to multibyte. */
4038 int len = copy_text (format, p, 1, 0, 1);
4040 p += len;
4041 format++;
4042 nchars++;
4044 else
4045 *p++ = *format++, nchars++;
4048 if (p > buf + total)
4049 abort ();
4051 if (maybe_combine_byte)
4052 nchars = multibyte_chars_in_text (buf, p - buf);
4053 val = make_specified_string (buf, nchars, p - buf, multibyte);
4055 /* If we allocated BUF with malloc, free it too. */
4056 SAFE_FREE ();
4058 /* If the format string has text properties, or any of the string
4059 arguments has text properties, set up text properties of the
4060 result string. */
4062 if (STRING_INTERVALS (args[0]) || arg_intervals)
4064 Lisp_Object len, new_len, props;
4065 struct gcpro gcpro1;
4067 /* Add text properties from the format string. */
4068 len = make_number (SCHARS (args[0]));
4069 props = text_property_list (args[0], make_number (0), len, Qnil);
4070 GCPRO1 (props);
4072 if (CONSP (props))
4074 int bytepos = 0, position = 0, translated = 0, argn = 1;
4075 Lisp_Object list;
4077 /* Adjust the bounds of each text property
4078 to the proper start and end in the output string. */
4080 /* Put the positions in PROPS in increasing order, so that
4081 we can do (effectively) one scan through the position
4082 space of the format string. */
4083 props = Fnreverse (props);
4085 /* BYTEPOS is the byte position in the format string,
4086 POSITION is the untranslated char position in it,
4087 TRANSLATED is the translated char position in BUF,
4088 and ARGN is the number of the next arg we will come to. */
4089 for (list = props; CONSP (list); list = XCDR (list))
4091 Lisp_Object item;
4092 int pos;
4094 item = XCAR (list);
4096 /* First adjust the property start position. */
4097 pos = XINT (XCAR (item));
4099 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4100 up to this position. */
4101 for (; position < pos; bytepos++)
4103 if (! discarded[bytepos])
4104 position++, translated++;
4105 else if (discarded[bytepos] == 1)
4107 position++;
4108 if (translated == info[argn].start)
4110 translated += info[argn].end - info[argn].start;
4111 argn++;
4116 XSETCAR (item, make_number (translated));
4118 /* Likewise adjust the property end position. */
4119 pos = XINT (XCAR (XCDR (item)));
4121 for (; position < pos; bytepos++)
4123 if (! discarded[bytepos])
4124 position++, translated++;
4125 else if (discarded[bytepos] == 1)
4127 position++;
4128 if (translated == info[argn].start)
4130 translated += info[argn].end - info[argn].start;
4131 argn++;
4136 XSETCAR (XCDR (item), make_number (translated));
4139 add_text_properties_from_list (val, props, make_number (0));
4142 /* Add text properties from arguments. */
4143 if (arg_intervals)
4144 for (n = 1; n < nargs; ++n)
4145 if (info[n].intervals)
4147 len = make_number (SCHARS (args[n]));
4148 new_len = make_number (info[n].end - info[n].start);
4149 props = text_property_list (args[n], make_number (0), len, Qnil);
4150 extend_property_ranges (props, len, new_len);
4151 /* If successive arguments have properites, be sure that
4152 the value of `composition' property be the copy. */
4153 if (n > 1 && info[n - 1].end)
4154 make_composition_value_copy (props);
4155 add_text_properties_from_list (val, props,
4156 make_number (info[n].start));
4159 UNGCPRO;
4162 return val;
4165 Lisp_Object
4166 format2 (string1, arg0, arg1)
4167 char *string1;
4168 Lisp_Object arg0, arg1;
4170 Lisp_Object args[3];
4171 args[0] = build_string (string1);
4172 args[1] = arg0;
4173 args[2] = arg1;
4174 return Fformat (3, args);
4177 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4178 doc: /* Return t if two characters match, optionally ignoring case.
4179 Both arguments must be characters (i.e. integers).
4180 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4181 (c1, c2)
4182 register Lisp_Object c1, c2;
4184 int i1, i2;
4185 /* Check they're chars, not just integers, otherwise we could get array
4186 bounds violations in DOWNCASE. */
4187 CHECK_CHARACTER (c1);
4188 CHECK_CHARACTER (c2);
4190 if (XINT (c1) == XINT (c2))
4191 return Qt;
4192 if (NILP (current_buffer->case_fold_search))
4193 return Qnil;
4195 /* Do these in separate statements,
4196 then compare the variables.
4197 because of the way DOWNCASE uses temp variables. */
4198 i1 = XFASTINT (c1);
4199 if (NILP (current_buffer->enable_multibyte_characters)
4200 && ! ASCII_CHAR_P (i1))
4202 MAKE_CHAR_MULTIBYTE (i1);
4204 i2 = XFASTINT (c2);
4205 if (NILP (current_buffer->enable_multibyte_characters)
4206 && ! ASCII_CHAR_P (i2))
4208 MAKE_CHAR_MULTIBYTE (i2);
4210 i1 = DOWNCASE (i1);
4211 i2 = DOWNCASE (i2);
4212 return (i1 == i2 ? Qt : Qnil);
4215 /* Transpose the markers in two regions of the current buffer, and
4216 adjust the ones between them if necessary (i.e.: if the regions
4217 differ in size).
4219 START1, END1 are the character positions of the first region.
4220 START1_BYTE, END1_BYTE are the byte positions.
4221 START2, END2 are the character positions of the second region.
4222 START2_BYTE, END2_BYTE are the byte positions.
4224 Traverses the entire marker list of the buffer to do so, adding an
4225 appropriate amount to some, subtracting from some, and leaving the
4226 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4228 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4230 static void
4231 transpose_markers (start1, end1, start2, end2,
4232 start1_byte, end1_byte, start2_byte, end2_byte)
4233 register int start1, end1, start2, end2;
4234 register int start1_byte, end1_byte, start2_byte, end2_byte;
4236 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4237 register struct Lisp_Marker *marker;
4239 /* Update point as if it were a marker. */
4240 if (PT < start1)
4242 else if (PT < end1)
4243 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4244 PT_BYTE + (end2_byte - end1_byte));
4245 else if (PT < start2)
4246 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4247 (PT_BYTE + (end2_byte - start2_byte)
4248 - (end1_byte - start1_byte)));
4249 else if (PT < end2)
4250 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4251 PT_BYTE - (start2_byte - start1_byte));
4253 /* We used to adjust the endpoints here to account for the gap, but that
4254 isn't good enough. Even if we assume the caller has tried to move the
4255 gap out of our way, it might still be at start1 exactly, for example;
4256 and that places it `inside' the interval, for our purposes. The amount
4257 of adjustment is nontrivial if there's a `denormalized' marker whose
4258 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4259 the dirty work to Fmarker_position, below. */
4261 /* The difference between the region's lengths */
4262 diff = (end2 - start2) - (end1 - start1);
4263 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4265 /* For shifting each marker in a region by the length of the other
4266 region plus the distance between the regions. */
4267 amt1 = (end2 - start2) + (start2 - end1);
4268 amt2 = (end1 - start1) + (start2 - end1);
4269 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4270 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4272 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4274 mpos = marker->bytepos;
4275 if (mpos >= start1_byte && mpos < end2_byte)
4277 if (mpos < end1_byte)
4278 mpos += amt1_byte;
4279 else if (mpos < start2_byte)
4280 mpos += diff_byte;
4281 else
4282 mpos -= amt2_byte;
4283 marker->bytepos = mpos;
4285 mpos = marker->charpos;
4286 if (mpos >= start1 && mpos < end2)
4288 if (mpos < end1)
4289 mpos += amt1;
4290 else if (mpos < start2)
4291 mpos += diff;
4292 else
4293 mpos -= amt2;
4295 marker->charpos = mpos;
4299 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4300 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4301 The regions may not be overlapping, because the size of the buffer is
4302 never changed in a transposition.
4304 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4305 any markers that happen to be located in the regions.
4307 Transposing beyond buffer boundaries is an error. */)
4308 (startr1, endr1, startr2, endr2, leave_markers)
4309 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
4311 register EMACS_INT start1, end1, start2, end2;
4312 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4313 EMACS_INT gap, len1, len_mid, len2;
4314 unsigned char *start1_addr, *start2_addr, *temp;
4316 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4317 Lisp_Object buf;
4319 XSETBUFFER (buf, current_buffer);
4320 cur_intv = BUF_INTERVALS (current_buffer);
4322 validate_region (&startr1, &endr1);
4323 validate_region (&startr2, &endr2);
4325 start1 = XFASTINT (startr1);
4326 end1 = XFASTINT (endr1);
4327 start2 = XFASTINT (startr2);
4328 end2 = XFASTINT (endr2);
4329 gap = GPT;
4331 /* Swap the regions if they're reversed. */
4332 if (start2 < end1)
4334 register int glumph = start1;
4335 start1 = start2;
4336 start2 = glumph;
4337 glumph = end1;
4338 end1 = end2;
4339 end2 = glumph;
4342 len1 = end1 - start1;
4343 len2 = end2 - start2;
4345 if (start2 < end1)
4346 error ("Transposed regions overlap");
4347 else if (start1 == end1 || start2 == end2)
4348 error ("Transposed region has length 0");
4350 /* The possibilities are:
4351 1. Adjacent (contiguous) regions, or separate but equal regions
4352 (no, really equal, in this case!), or
4353 2. Separate regions of unequal size.
4355 The worst case is usually No. 2. It means that (aside from
4356 potential need for getting the gap out of the way), there also
4357 needs to be a shifting of the text between the two regions. So
4358 if they are spread far apart, we are that much slower... sigh. */
4360 /* It must be pointed out that the really studly thing to do would
4361 be not to move the gap at all, but to leave it in place and work
4362 around it if necessary. This would be extremely efficient,
4363 especially considering that people are likely to do
4364 transpositions near where they are working interactively, which
4365 is exactly where the gap would be found. However, such code
4366 would be much harder to write and to read. So, if you are
4367 reading this comment and are feeling squirrely, by all means have
4368 a go! I just didn't feel like doing it, so I will simply move
4369 the gap the minimum distance to get it out of the way, and then
4370 deal with an unbroken array. */
4372 /* Make sure the gap won't interfere, by moving it out of the text
4373 we will operate on. */
4374 if (start1 < gap && gap < end2)
4376 if (gap - start1 < end2 - gap)
4377 move_gap (start1);
4378 else
4379 move_gap (end2);
4382 start1_byte = CHAR_TO_BYTE (start1);
4383 start2_byte = CHAR_TO_BYTE (start2);
4384 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4385 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
4387 #ifdef BYTE_COMBINING_DEBUG
4388 if (end1 == start2)
4390 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4391 len2_byte, start1, start1_byte)
4392 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4393 len1_byte, end2, start2_byte + len2_byte)
4394 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4395 len1_byte, end2, start2_byte + len2_byte))
4396 abort ();
4398 else
4400 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4401 len2_byte, start1, start1_byte)
4402 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4403 len1_byte, start2, start2_byte)
4404 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4405 len2_byte, end1, start1_byte + len1_byte)
4406 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4407 len1_byte, end2, start2_byte + len2_byte))
4408 abort ();
4410 #endif
4412 /* Hmmm... how about checking to see if the gap is large
4413 enough to use as the temporary storage? That would avoid an
4414 allocation... interesting. Later, don't fool with it now. */
4416 /* Working without memmove, for portability (sigh), so must be
4417 careful of overlapping subsections of the array... */
4419 if (end1 == start2) /* adjacent regions */
4421 modify_region (current_buffer, start1, end2, 0);
4422 record_change (start1, len1 + len2);
4424 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4425 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4426 /* Don't use Fset_text_properties: that can cause GC, which can
4427 clobber objects stored in the tmp_intervals. */
4428 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4429 if (!NULL_INTERVAL_P (tmp_interval3))
4430 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4432 /* First region smaller than second. */
4433 if (len1_byte < len2_byte)
4435 USE_SAFE_ALLOCA;
4437 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4439 /* Don't precompute these addresses. We have to compute them
4440 at the last minute, because the relocating allocator might
4441 have moved the buffer around during the xmalloc. */
4442 start1_addr = BYTE_POS_ADDR (start1_byte);
4443 start2_addr = BYTE_POS_ADDR (start2_byte);
4445 bcopy (start2_addr, temp, len2_byte);
4446 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4447 bcopy (temp, start1_addr, len2_byte);
4448 SAFE_FREE ();
4450 else
4451 /* First region not smaller than second. */
4453 USE_SAFE_ALLOCA;
4455 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4456 start1_addr = BYTE_POS_ADDR (start1_byte);
4457 start2_addr = BYTE_POS_ADDR (start2_byte);
4458 bcopy (start1_addr, temp, len1_byte);
4459 bcopy (start2_addr, start1_addr, len2_byte);
4460 bcopy (temp, start1_addr + len2_byte, len1_byte);
4461 SAFE_FREE ();
4463 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4464 len1, current_buffer, 0);
4465 graft_intervals_into_buffer (tmp_interval2, start1,
4466 len2, current_buffer, 0);
4467 update_compositions (start1, start1 + len2, CHECK_BORDER);
4468 update_compositions (start1 + len2, end2, CHECK_TAIL);
4470 /* Non-adjacent regions, because end1 != start2, bleagh... */
4471 else
4473 len_mid = start2_byte - (start1_byte + len1_byte);
4475 if (len1_byte == len2_byte)
4476 /* Regions are same size, though, how nice. */
4478 USE_SAFE_ALLOCA;
4480 modify_region (current_buffer, start1, end1, 0);
4481 modify_region (current_buffer, start2, end2, 0);
4482 record_change (start1, len1);
4483 record_change (start2, len2);
4484 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4485 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4487 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4488 if (!NULL_INTERVAL_P (tmp_interval3))
4489 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4491 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4492 if (!NULL_INTERVAL_P (tmp_interval3))
4493 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4495 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4496 start1_addr = BYTE_POS_ADDR (start1_byte);
4497 start2_addr = BYTE_POS_ADDR (start2_byte);
4498 bcopy (start1_addr, temp, len1_byte);
4499 bcopy (start2_addr, start1_addr, len2_byte);
4500 bcopy (temp, start2_addr, len1_byte);
4501 SAFE_FREE ();
4503 graft_intervals_into_buffer (tmp_interval1, start2,
4504 len1, current_buffer, 0);
4505 graft_intervals_into_buffer (tmp_interval2, start1,
4506 len2, current_buffer, 0);
4509 else if (len1_byte < len2_byte) /* Second region larger than first */
4510 /* Non-adjacent & unequal size, area between must also be shifted. */
4512 USE_SAFE_ALLOCA;
4514 modify_region (current_buffer, start1, end2, 0);
4515 record_change (start1, (end2 - start1));
4516 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4517 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4518 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4520 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4521 if (!NULL_INTERVAL_P (tmp_interval3))
4522 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4524 /* holds region 2 */
4525 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
4526 start1_addr = BYTE_POS_ADDR (start1_byte);
4527 start2_addr = BYTE_POS_ADDR (start2_byte);
4528 bcopy (start2_addr, temp, len2_byte);
4529 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4530 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4531 bcopy (temp, start1_addr, len2_byte);
4532 SAFE_FREE ();
4534 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4535 len1, current_buffer, 0);
4536 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4537 len_mid, current_buffer, 0);
4538 graft_intervals_into_buffer (tmp_interval2, start1,
4539 len2, current_buffer, 0);
4541 else
4542 /* Second region smaller than first. */
4544 USE_SAFE_ALLOCA;
4546 record_change (start1, (end2 - start1));
4547 modify_region (current_buffer, start1, end2, 0);
4549 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4550 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4551 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4553 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4554 if (!NULL_INTERVAL_P (tmp_interval3))
4555 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4557 /* holds region 1 */
4558 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
4559 start1_addr = BYTE_POS_ADDR (start1_byte);
4560 start2_addr = BYTE_POS_ADDR (start2_byte);
4561 bcopy (start1_addr, temp, len1_byte);
4562 bcopy (start2_addr, start1_addr, len2_byte);
4563 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4564 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
4565 SAFE_FREE ();
4567 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4568 len1, current_buffer, 0);
4569 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4570 len_mid, current_buffer, 0);
4571 graft_intervals_into_buffer (tmp_interval2, start1,
4572 len2, current_buffer, 0);
4575 update_compositions (start1, start1 + len2, CHECK_BORDER);
4576 update_compositions (end2 - len1, end2, CHECK_BORDER);
4579 /* When doing multiple transpositions, it might be nice
4580 to optimize this. Perhaps the markers in any one buffer
4581 should be organized in some sorted data tree. */
4582 if (NILP (leave_markers))
4584 transpose_markers (start1, end1, start2, end2,
4585 start1_byte, start1_byte + len1_byte,
4586 start2_byte, start2_byte + len2_byte);
4587 fix_start_end_in_overlays (start1, end2);
4590 signal_after_change (start1, end2 - start1, end2 - start1);
4591 return Qnil;
4595 void
4596 syms_of_editfns ()
4598 environbuf = 0;
4599 initial_tz = 0;
4601 Qbuffer_access_fontify_functions
4602 = intern ("buffer-access-fontify-functions");
4603 staticpro (&Qbuffer_access_fontify_functions);
4605 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
4606 doc: /* Non-nil means text motion commands don't notice fields. */);
4607 Vinhibit_field_text_motion = Qnil;
4609 DEFVAR_LISP ("buffer-access-fontify-functions",
4610 &Vbuffer_access_fontify_functions,
4611 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4612 Each function is called with two arguments which specify the range
4613 of the buffer being accessed. */);
4614 Vbuffer_access_fontify_functions = Qnil;
4617 Lisp_Object obuf;
4618 extern Lisp_Object Vprin1_to_string_buffer;
4619 obuf = Fcurrent_buffer ();
4620 /* Do this here, because init_buffer_once is too early--it won't work. */
4621 Fset_buffer (Vprin1_to_string_buffer);
4622 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4623 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
4624 Qnil);
4625 Fset_buffer (obuf);
4628 DEFVAR_LISP ("buffer-access-fontified-property",
4629 &Vbuffer_access_fontified_property,
4630 doc: /* Property which (if non-nil) indicates text has been fontified.
4631 `buffer-substring' need not call the `buffer-access-fontify-functions'
4632 functions if all the text being accessed has this property. */);
4633 Vbuffer_access_fontified_property = Qnil;
4635 DEFVAR_LISP ("system-name", &Vsystem_name,
4636 doc: /* The host name of the machine Emacs is running on. */);
4638 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4639 doc: /* The full name of the user logged in. */);
4641 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4642 doc: /* The user's name, taken from environment variables if possible. */);
4644 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4645 doc: /* The user's name, based upon the real uid only. */);
4647 DEFVAR_LISP ("operating-system-release", &Voperating_system_release,
4648 doc: /* The release of the operating system Emacs is running on. */);
4650 defsubr (&Spropertize);
4651 defsubr (&Schar_equal);
4652 defsubr (&Sgoto_char);
4653 defsubr (&Sstring_to_char);
4654 defsubr (&Schar_to_string);
4655 defsubr (&Sbuffer_substring);
4656 defsubr (&Sbuffer_substring_no_properties);
4657 defsubr (&Sbuffer_string);
4659 defsubr (&Spoint_marker);
4660 defsubr (&Smark_marker);
4661 defsubr (&Spoint);
4662 defsubr (&Sregion_beginning);
4663 defsubr (&Sregion_end);
4665 staticpro (&Qfield);
4666 Qfield = intern ("field");
4667 staticpro (&Qboundary);
4668 Qboundary = intern ("boundary");
4669 defsubr (&Sfield_beginning);
4670 defsubr (&Sfield_end);
4671 defsubr (&Sfield_string);
4672 defsubr (&Sfield_string_no_properties);
4673 defsubr (&Sdelete_field);
4674 defsubr (&Sconstrain_to_field);
4676 defsubr (&Sline_beginning_position);
4677 defsubr (&Sline_end_position);
4679 /* defsubr (&Smark); */
4680 /* defsubr (&Sset_mark); */
4681 defsubr (&Ssave_excursion);
4682 defsubr (&Ssave_current_buffer);
4684 defsubr (&Sbufsize);
4685 defsubr (&Spoint_max);
4686 defsubr (&Spoint_min);
4687 defsubr (&Spoint_min_marker);
4688 defsubr (&Spoint_max_marker);
4689 defsubr (&Sgap_position);
4690 defsubr (&Sgap_size);
4691 defsubr (&Sposition_bytes);
4692 defsubr (&Sbyte_to_position);
4694 defsubr (&Sbobp);
4695 defsubr (&Seobp);
4696 defsubr (&Sbolp);
4697 defsubr (&Seolp);
4698 defsubr (&Sfollowing_char);
4699 defsubr (&Sprevious_char);
4700 defsubr (&Schar_after);
4701 defsubr (&Schar_before);
4702 defsubr (&Sinsert);
4703 defsubr (&Sinsert_before_markers);
4704 defsubr (&Sinsert_and_inherit);
4705 defsubr (&Sinsert_and_inherit_before_markers);
4706 defsubr (&Sinsert_char);
4707 defsubr (&Sinsert_byte);
4709 defsubr (&Suser_login_name);
4710 defsubr (&Suser_real_login_name);
4711 defsubr (&Suser_uid);
4712 defsubr (&Suser_real_uid);
4713 defsubr (&Suser_full_name);
4714 defsubr (&Semacs_pid);
4715 defsubr (&Scurrent_time);
4716 defsubr (&Sget_internal_run_time);
4717 defsubr (&Sformat_time_string);
4718 defsubr (&Sfloat_time);
4719 defsubr (&Sdecode_time);
4720 defsubr (&Sencode_time);
4721 defsubr (&Scurrent_time_string);
4722 defsubr (&Scurrent_time_zone);
4723 defsubr (&Sset_time_zone_rule);
4724 defsubr (&Ssystem_name);
4725 defsubr (&Smessage);
4726 defsubr (&Smessage_box);
4727 defsubr (&Smessage_or_box);
4728 defsubr (&Scurrent_message);
4729 defsubr (&Sformat);
4731 defsubr (&Sinsert_buffer_substring);
4732 defsubr (&Scompare_buffer_substrings);
4733 defsubr (&Ssubst_char_in_region);
4734 defsubr (&Stranslate_region_internal);
4735 defsubr (&Sdelete_region);
4736 defsubr (&Sdelete_and_extract_region);
4737 defsubr (&Swiden);
4738 defsubr (&Snarrow_to_region);
4739 defsubr (&Ssave_restriction);
4740 defsubr (&Stranspose_regions);
4743 /* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4744 (do not change this comment) */