(profile, make-docfile, hexl): Depend on config.h.
[emacs.git] / src / editfns.c
blobc8011c8eb3e02605157ddfd57c9c5efda84c55c8
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999, 2000
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
23 #include <config.h>
24 #include <sys/types.h>
26 #ifdef VMS
27 #include "vms-pwd.h"
28 #else
29 #include <pwd.h>
30 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
36 #include "lisp.h"
37 #include "intervals.h"
38 #include "buffer.h"
39 #include "charset.h"
40 #include "coding.h"
41 #include "window.h"
43 #include "systime.h"
45 #ifdef HAVE_STRING_H
46 #include <string.h>
47 #endif
49 #ifdef HAVE_STRINGS_H
50 #include <strings.h>
51 #endif
53 #define min(a, b) ((a) < (b) ? (a) : (b))
54 #define max(a, b) ((a) > (b) ? (a) : (b))
56 #ifndef NULL
57 #define NULL 0
58 #endif
60 #ifndef USE_CRT_DLL
61 extern char **environ;
62 #endif
64 extern Lisp_Object make_time P_ ((time_t));
65 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
66 const struct tm *, int));
67 static int tm_diff P_ ((struct tm *, struct tm *));
68 static void find_field P_ ((Lisp_Object, Lisp_Object, int *, int *));
69 static void update_buffer_properties P_ ((int, int));
70 static Lisp_Object region_limit P_ ((int));
71 static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
72 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
73 size_t, const struct tm *, int));
74 static void general_insert_function P_ ((void (*) (unsigned char *, int),
75 void (*) (Lisp_Object, int, int, int,
76 int, int),
77 int, int, Lisp_Object *));
78 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
79 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
80 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
82 Lisp_Object Vbuffer_access_fontify_functions;
83 Lisp_Object Qbuffer_access_fontify_functions;
84 Lisp_Object Vbuffer_access_fontified_property;
86 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
88 /* Non-nil means don't stop at field boundary in text motion commands. */
90 Lisp_Object Vinhibit_field_text_motion;
92 /* Some static data, and a function to initialize it for each run */
94 Lisp_Object Vsystem_name;
95 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
96 Lisp_Object Vuser_full_name; /* full name of current user */
97 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
99 /* Symbol for the text property used to mark fields. */
101 Lisp_Object Qfield;
103 /* A special value for Qfield properties. */
105 Lisp_Object Qboundary;
108 void
109 init_editfns ()
111 char *user_name;
112 register unsigned char *p;
113 struct passwd *pw; /* password entry for the current user */
114 Lisp_Object tem;
116 /* Set up system_name even when dumping. */
117 init_system_name ();
119 #ifndef CANNOT_DUMP
120 /* Don't bother with this on initial start when just dumping out */
121 if (!initialized)
122 return;
123 #endif /* not CANNOT_DUMP */
125 pw = (struct passwd *) getpwuid (getuid ());
126 #ifdef MSDOS
127 /* We let the real user name default to "root" because that's quite
128 accurate on MSDOG and because it lets Emacs find the init file.
129 (The DVX libraries override the Djgpp libraries here.) */
130 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
131 #else
132 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
133 #endif
135 /* Get the effective user name, by consulting environment variables,
136 or the effective uid if those are unset. */
137 user_name = (char *) getenv ("LOGNAME");
138 if (!user_name)
139 #ifdef WINDOWSNT
140 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
141 #else /* WINDOWSNT */
142 user_name = (char *) getenv ("USER");
143 #endif /* WINDOWSNT */
144 if (!user_name)
146 pw = (struct passwd *) getpwuid (geteuid ());
147 user_name = (char *) (pw ? pw->pw_name : "unknown");
149 Vuser_login_name = build_string (user_name);
151 /* If the user name claimed in the environment vars differs from
152 the real uid, use the claimed name to find the full name. */
153 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
154 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
155 : Vuser_login_name);
157 p = (unsigned char *) getenv ("NAME");
158 if (p)
159 Vuser_full_name = build_string (p);
160 else if (NILP (Vuser_full_name))
161 Vuser_full_name = build_string ("unknown");
164 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
165 "Convert arg CHAR to a string containing that character.")
166 (character)
167 Lisp_Object character;
169 int len;
170 unsigned char str[MAX_MULTIBYTE_LENGTH];
172 CHECK_NUMBER (character, 0);
174 len = CHAR_STRING (XFASTINT (character), str);
175 return make_string_from_bytes (str, 1, len);
178 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
179 "Convert arg STRING to a character, the first character of that string.\n\
180 A multibyte character is handled correctly.")
181 (string)
182 register Lisp_Object string;
184 register Lisp_Object val;
185 register struct Lisp_String *p;
186 CHECK_STRING (string, 0);
187 p = XSTRING (string);
188 if (p->size)
190 if (STRING_MULTIBYTE (string))
191 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
192 else
193 XSETFASTINT (val, p->data[0]);
195 else
196 XSETFASTINT (val, 0);
197 return val;
200 static Lisp_Object
201 buildmark (charpos, bytepos)
202 int charpos, bytepos;
204 register Lisp_Object mark;
205 mark = Fmake_marker ();
206 set_marker_both (mark, Qnil, charpos, bytepos);
207 return mark;
210 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
211 "Return value of point, as an integer.\n\
212 Beginning of buffer is position (point-min)")
215 Lisp_Object temp;
216 XSETFASTINT (temp, PT);
217 return temp;
220 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
221 "Return value of point, as a marker object.")
224 return buildmark (PT, PT_BYTE);
228 clip_to_bounds (lower, num, upper)
229 int lower, num, upper;
231 if (num < lower)
232 return lower;
233 else if (num > upper)
234 return upper;
235 else
236 return num;
239 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
240 "Set point to POSITION, a number or marker.\n\
241 Beginning of buffer is position (point-min), end is (point-max).\n\
242 If the position is in the middle of a multibyte form,\n\
243 the actual point is set at the head of the multibyte form\n\
244 except in the case that `enable-multibyte-characters' is nil.")
245 (position)
246 register Lisp_Object position;
248 int pos;
250 if (MARKERP (position)
251 && current_buffer == XMARKER (position)->buffer)
253 pos = marker_position (position);
254 if (pos < BEGV)
255 SET_PT_BOTH (BEGV, BEGV_BYTE);
256 else if (pos > ZV)
257 SET_PT_BOTH (ZV, ZV_BYTE);
258 else
259 SET_PT_BOTH (pos, marker_byte_position (position));
261 return position;
264 CHECK_NUMBER_COERCE_MARKER (position, 0);
266 pos = clip_to_bounds (BEGV, XINT (position), ZV);
267 SET_PT (pos);
268 return position;
272 /* Return the start or end position of the region.
273 BEGINNINGP non-zero means return the start.
274 If there is no region active, signal an error. */
276 static Lisp_Object
277 region_limit (beginningp)
278 int beginningp;
280 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
281 Lisp_Object m;
283 if (!NILP (Vtransient_mark_mode)
284 && NILP (Vmark_even_if_inactive)
285 && NILP (current_buffer->mark_active))
286 Fsignal (Qmark_inactive, Qnil);
288 m = Fmarker_position (current_buffer->mark);
289 if (NILP (m))
290 error ("There is no region now");
292 if ((PT < XFASTINT (m)) == beginningp)
293 m = make_number (PT);
294 return m;
297 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
298 "Return position of beginning of region, as an integer.")
301 return region_limit (1);
304 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
305 "Return position of end of region, as an integer.")
308 return region_limit (0);
311 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
312 "Return this buffer's mark, as a marker object.\n\
313 Watch out! Moving this marker changes the mark position.\n\
314 If you set the marker not to point anywhere, the buffer will have no mark.")
317 return current_buffer->mark;
321 /* Return nonzero if POS1 and POS2 have the same value
322 for the text property PROP. */
324 static int
325 char_property_eq (prop, pos1, pos2)
326 Lisp_Object prop;
327 Lisp_Object pos1, pos2;
329 Lisp_Object pval1, pval2;
331 pval1 = Fget_char_property (pos1, prop, Qnil);
332 pval2 = Fget_char_property (pos2, prop, Qnil);
334 return EQ (pval1, pval2);
337 /* Return the direction from which the char-property PROP would be
338 inherited by any new text inserted at POS: 1 if it would be
339 inherited from the char after POS, -1 if it would be inherited from
340 the char before POS, and 0 if from neither. */
342 static int
343 char_property_stickiness (prop, pos)
344 Lisp_Object prop;
345 Lisp_Object pos;
347 Lisp_Object front_sticky;
349 if (XINT (pos) > BEGV)
350 /* Consider previous character. */
352 Lisp_Object prev_pos, rear_non_sticky;
354 prev_pos = make_number (XINT (pos) - 1);
355 rear_non_sticky = Fget_char_property (prev_pos, Qrear_nonsticky, Qnil);
357 if (EQ (rear_non_sticky, Qnil)
358 || (CONSP (rear_non_sticky)
359 && NILP (Fmemq (prop, rear_non_sticky))))
360 /* PROP is not rear-non-sticky, and since this takes precedence over
361 any front-stickiness, PROP is inherited from before. */
362 return -1;
365 /* Consider following character. */
366 front_sticky = Fget_char_property (pos, Qfront_sticky, Qnil);
368 if (EQ (front_sticky, Qt)
369 || (CONSP (front_sticky)
370 && !NILP (Fmemq (prop, front_sticky))))
371 /* PROP is inherited from after. */
372 return 1;
374 /* PROP is not inherited from either side. */
375 return 0;
379 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
380 the value of point is used instead. If BEG or END null,
381 means don't store the beginning or end of the field.
383 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
384 position of a field, then the beginning of the previous field is
385 returned instead of the beginning of POS's field (since the end of a
386 field is actually also the beginning of the next input field, this
387 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
388 true case, if two fields are separated by a field with the special
389 value `boundary', and POS lies within it, then the two separated
390 fields are considered to be adjacent, and POS between them, when
391 finding the beginning and ending of the "merged" field.
393 Either BEG or END may be 0, in which case the corresponding value
394 is not stored. */
396 static void
397 find_field (pos, merge_at_boundary, beg, end)
398 Lisp_Object pos;
399 Lisp_Object merge_at_boundary;
400 int *beg, *end;
402 /* Fields right before and after the point. */
403 Lisp_Object before_field, after_field;
404 /* 1 if POS counts as the start of a field. */
405 int at_field_start = 0;
406 /* 1 if POS counts as the end of a field. */
407 int at_field_end = 0;
409 if (NILP (pos))
410 XSETFASTINT (pos, PT);
411 else
412 CHECK_NUMBER_COERCE_MARKER (pos, 0);
414 after_field
415 = Fget_char_property (pos, Qfield, Qnil);
416 before_field
417 = (XFASTINT (pos) > BEGV
418 ? Fget_char_property (make_number (XINT (pos) - 1), Qfield, Qnil)
419 : Qnil);
421 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
422 and POS is at beginning of a field, which can also be interpreted
423 as the end of the previous field. Note that the case where if
424 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
425 more natural one; then we avoid treating the beginning of a field
426 specially. */
427 if (NILP (merge_at_boundary) && !EQ (after_field, before_field))
428 /* We are at a boundary, see which direction is inclusive. We
429 decide by seeing which field the `field' property sticks to. */
431 int stickiness = char_property_stickiness (Qfield, pos);
433 if (stickiness > 0)
434 at_field_start = 1;
435 else if (stickiness < 0)
436 at_field_end = 1;
437 else
438 /* STICKINESS == 0 means that any inserted text will get a
439 `field' char-property of nil, so check to see if that
440 matches either of the adjacent characters (this being a
441 kind of "stickiness by default"). */
443 if (NILP (before_field))
444 at_field_end = 1; /* Sticks to the left. */
445 else if (NILP (after_field))
446 at_field_start = 1; /* Sticks to the right. */
450 /* Note about special `boundary' fields:
452 Consider the case where the point (`.') is between the fields `x' and `y':
454 xxxx.yyyy
456 In this situation, if merge_at_boundary is true, we consider the
457 `x' and `y' fields as forming one big merged field, and so the end
458 of the field is the end of `y'.
460 However, if `x' and `y' are separated by a special `boundary' field
461 (a field with a `field' char-property of 'boundary), then we ignore
462 this special field when merging adjacent fields. Here's the same
463 situation, but with a `boundary' field between the `x' and `y' fields:
465 xxx.BBBByyyy
467 Here, if point is at the end of `x', the beginning of `y', or
468 anywhere in-between (within the `boundary' field), we merge all
469 three fields and consider the beginning as being the beginning of
470 the `x' field, and the end as being the end of the `y' field. */
472 if (beg)
474 if (at_field_start)
475 /* POS is at the edge of a field, and we should consider it as
476 the beginning of the following field. */
477 *beg = XFASTINT (pos);
478 else
479 /* Find the previous field boundary. */
481 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
482 /* Skip a `boundary' field. */
483 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
485 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
486 *beg = NILP (pos) ? BEGV : XFASTINT (pos);
490 if (end)
492 if (at_field_end)
493 /* POS is at the edge of a field, and we should consider it as
494 the end of the previous field. */
495 *end = XFASTINT (pos);
496 else
497 /* Find the next field boundary. */
499 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
500 /* Skip a `boundary' field. */
501 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
503 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
504 *end = NILP (pos) ? ZV : XFASTINT (pos);
510 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
511 "Delete the field surrounding POS.\n\
512 A field is a region of text with the same `field' property.\n\
513 If POS is nil, the value of point is used for POS.")
514 (pos)
515 Lisp_Object pos;
517 int beg, end;
518 find_field (pos, Qnil, &beg, &end);
519 if (beg != end)
520 del_range (beg, end);
521 return Qnil;
524 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
525 "Return the contents of the field surrounding POS as a string.\n\
526 A field is a region of text with the same `field' property.\n\
527 If POS is nil, the value of point is used for POS.")
528 (pos)
529 Lisp_Object pos;
531 int beg, end;
532 find_field (pos, Qnil, &beg, &end);
533 return make_buffer_string (beg, end, 1);
536 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
537 "Return the contents of the field around POS, without text-properties.\n\
538 A field is a region of text with the same `field' property.\n\
539 If POS is nil, the value of point is used for POS.")
540 (pos)
541 Lisp_Object pos;
543 int beg, end;
544 find_field (pos, Qnil, &beg, &end);
545 return make_buffer_string (beg, end, 0);
548 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
549 "Return the beginning of the field surrounding POS.\n\
550 A field is a region of text with the same `field' property.\n\
551 If POS is nil, the value of point is used for POS.\n\
552 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its\n\
553 field, then the beginning of the *previous* field is returned.")
554 (pos, escape_from_edge)
555 Lisp_Object pos, escape_from_edge;
557 int beg;
558 find_field (pos, escape_from_edge, &beg, 0);
559 return make_number (beg);
562 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
563 "Return the end of the field surrounding POS.\n\
564 A field is a region of text with the same `field' property.\n\
565 If POS is nil, the value of point is used for POS.\n\
566 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,\n\
567 then the end of the *following* field is returned.")
568 (pos, escape_from_edge)
569 Lisp_Object pos, escape_from_edge;
571 int end;
572 find_field (pos, escape_from_edge, 0, &end);
573 return make_number (end);
576 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
577 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
579 A field is a region of text with the same `field' property.\n\
580 If NEW-POS is nil, then the current point is used instead, and set to the\n\
581 constrained position if that is is different.\n\
583 If OLD-POS is at the boundary of two fields, then the allowable\n\
584 positions for NEW-POS depends on the value of the optional argument\n\
585 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
586 constrained to the field that has the same `field' char-property\n\
587 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
588 is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
589 fields. Additionally, if two fields are separated by another field with\n\
590 the special value `boundary', then any point within this special field is\n\
591 also considered to be `on the boundary'.\n\
593 If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
594 NEW-POS would move it to a different line, NEW-POS is returned\n\
595 unconstrained. This useful for commands that move by line, like\n\
596 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
597 only in the case where they can still move to the right line.\n\
599 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has\n\
600 a non-nil property of that name, then any field boundaries are ignored.\n\
602 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
603 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
604 Lisp_Object new_pos, old_pos;
605 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
607 /* If non-zero, then the original point, before re-positioning. */
608 int orig_point = 0;
610 if (NILP (new_pos))
611 /* Use the current point, and afterwards, set it. */
613 orig_point = PT;
614 XSETFASTINT (new_pos, PT);
617 if (NILP (Vinhibit_field_text_motion)
618 && !EQ (new_pos, old_pos)
619 && !char_property_eq (Qfield, new_pos, old_pos)
620 && (NILP (inhibit_capture_property)
621 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
622 /* NEW_POS is not within the same field as OLD_POS; try to
623 move NEW_POS so that it is. */
625 int fwd, shortage;
626 Lisp_Object field_bound;
628 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
629 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
631 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
633 if (fwd)
634 field_bound = Ffield_end (old_pos, escape_from_edge);
635 else
636 field_bound = Ffield_beginning (old_pos, escape_from_edge);
638 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
639 other side of NEW_POS, which would mean that NEW_POS is
640 already acceptable, and it's not necessary to constrain it
641 to FIELD_BOUND. */
642 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
643 /* NEW_POS should be constrained, but only if either
644 ONLY_IN_LINE is nil (in which case any constraint is OK),
645 or NEW_POS and FIELD_BOUND are on the same line (in which
646 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
647 && (NILP (only_in_line)
648 /* This is the ONLY_IN_LINE case, check that NEW_POS and
649 FIELD_BOUND are on the same line by seeing whether
650 there's an intervening newline or not. */
651 || (scan_buffer ('\n',
652 XFASTINT (new_pos), XFASTINT (field_bound),
653 fwd ? -1 : 1, &shortage, 1),
654 shortage != 0)))
655 /* Constrain NEW_POS to FIELD_BOUND. */
656 new_pos = field_bound;
658 if (orig_point && XFASTINT (new_pos) != orig_point)
659 /* The NEW_POS argument was originally nil, so automatically set PT. */
660 SET_PT (XFASTINT (new_pos));
663 return new_pos;
667 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
668 0, 1, 0,
669 "Return the character position of the first character on the current line.\n\
670 With argument N not nil or 1, move forward N - 1 lines first.\n\
671 If scan reaches end of buffer, return that position.\n\
672 The scan does not cross a field boundary unless it would move\n\
673 beyond there to a different line. Field boundaries are not noticed if\n\
674 `inhibit-field-text-motion' is non-nil. .And if N is nil or 1,\n\
675 and scan starts at a field boundary, the scan stops as soon as it starts.\n\
677 This function does not move point.")
679 Lisp_Object n;
681 int orig, orig_byte, end;
683 if (NILP (n))
684 XSETFASTINT (n, 1);
685 else
686 CHECK_NUMBER (n, 0);
688 orig = PT;
689 orig_byte = PT_BYTE;
690 Fforward_line (make_number (XINT (n) - 1));
691 end = PT;
693 SET_PT_BOTH (orig, orig_byte);
695 /* Return END constrained to the current input field. */
696 return Fconstrain_to_field (make_number (end), make_number (orig),
697 XINT (n) != 1 ? Qt : Qnil,
698 Qt, Qnil);
701 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
702 0, 1, 0,
703 "Return the character position of the last character on the current line.\n\
704 With argument N not nil or 1, move forward N - 1 lines first.\n\
705 If scan reaches end of buffer, return that position.\n\
706 This function does not move point.")
708 Lisp_Object n;
710 int end_pos;
711 int orig = PT;
713 if (NILP (n))
714 XSETFASTINT (n, 1);
715 else
716 CHECK_NUMBER (n, 0);
718 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
720 /* Return END_POS constrained to the current input field. */
721 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
722 Qnil, Qt, Qnil);
725 Lisp_Object
726 save_excursion_save ()
728 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
729 == current_buffer);
731 return Fcons (Fpoint_marker (),
732 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
733 Fcons (visible ? Qt : Qnil,
734 current_buffer->mark_active)));
737 Lisp_Object
738 save_excursion_restore (info)
739 Lisp_Object info;
741 Lisp_Object tem, tem1, omark, nmark;
742 struct gcpro gcpro1, gcpro2, gcpro3;
744 tem = Fmarker_buffer (Fcar (info));
745 /* If buffer being returned to is now deleted, avoid error */
746 /* Otherwise could get error here while unwinding to top level
747 and crash */
748 /* In that case, Fmarker_buffer returns nil now. */
749 if (NILP (tem))
750 return Qnil;
752 omark = nmark = Qnil;
753 GCPRO3 (info, omark, nmark);
755 Fset_buffer (tem);
756 tem = Fcar (info);
757 Fgoto_char (tem);
758 unchain_marker (tem);
759 tem = Fcar (Fcdr (info));
760 omark = Fmarker_position (current_buffer->mark);
761 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
762 nmark = Fmarker_position (tem);
763 unchain_marker (tem);
764 tem = Fcdr (Fcdr (info));
765 #if 0 /* We used to make the current buffer visible in the selected window
766 if that was true previously. That avoids some anomalies.
767 But it creates others, and it wasn't documented, and it is simpler
768 and cleaner never to alter the window/buffer connections. */
769 tem1 = Fcar (tem);
770 if (!NILP (tem1)
771 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
772 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
773 #endif /* 0 */
775 tem1 = current_buffer->mark_active;
776 current_buffer->mark_active = Fcdr (tem);
777 if (!NILP (Vrun_hooks))
779 /* If mark is active now, and either was not active
780 or was at a different place, run the activate hook. */
781 if (! NILP (current_buffer->mark_active))
783 if (! EQ (omark, nmark))
784 call1 (Vrun_hooks, intern ("activate-mark-hook"));
786 /* If mark has ceased to be active, run deactivate hook. */
787 else if (! NILP (tem1))
788 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
790 UNGCPRO;
791 return Qnil;
794 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
795 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
796 Executes BODY just like `progn'.\n\
797 The values of point, mark and the current buffer are restored\n\
798 even in case of abnormal exit (throw or error).\n\
799 The state of activation of the mark is also restored.\n\
801 This construct does not save `deactivate-mark', and therefore\n\
802 functions that change the buffer will still cause deactivation\n\
803 of the mark at the end of the command. To prevent that, bind\n\
804 `deactivate-mark' with `let'.")
805 (args)
806 Lisp_Object args;
808 register Lisp_Object val;
809 int count = specpdl_ptr - specpdl;
811 record_unwind_protect (save_excursion_restore, save_excursion_save ());
813 val = Fprogn (args);
814 return unbind_to (count, val);
817 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
818 "Save the current buffer; execute BODY; restore the current buffer.\n\
819 Executes BODY just like `progn'.")
820 (args)
821 Lisp_Object args;
823 Lisp_Object val;
824 int count = specpdl_ptr - specpdl;
826 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
828 val = Fprogn (args);
829 return unbind_to (count, val);
832 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
833 "Return the number of characters in the current buffer.\n\
834 If BUFFER, return the number of characters in that buffer instead.")
835 (buffer)
836 Lisp_Object buffer;
838 if (NILP (buffer))
839 return make_number (Z - BEG);
840 else
842 CHECK_BUFFER (buffer, 1);
843 return make_number (BUF_Z (XBUFFER (buffer))
844 - BUF_BEG (XBUFFER (buffer)));
848 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
849 "Return the minimum permissible value of point in the current buffer.\n\
850 This is 1, unless narrowing (a buffer restriction) is in effect.")
853 Lisp_Object temp;
854 XSETFASTINT (temp, BEGV);
855 return temp;
858 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
859 "Return a marker to the minimum permissible value of point in this buffer.\n\
860 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
863 return buildmark (BEGV, BEGV_BYTE);
866 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
867 "Return the maximum permissible value of point in the current buffer.\n\
868 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
869 is in effect, in which case it is less.")
872 Lisp_Object temp;
873 XSETFASTINT (temp, ZV);
874 return temp;
877 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
878 "Return a marker to the maximum permissible value of point in this buffer.\n\
879 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
880 is in effect, in which case it is less.")
883 return buildmark (ZV, ZV_BYTE);
886 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
887 "Return the position of the gap, in the current buffer.\n\
888 See also `gap-size'.")
891 Lisp_Object temp;
892 XSETFASTINT (temp, GPT);
893 return temp;
896 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
897 "Return the size of the current buffer's gap.\n\
898 See also `gap-position'.")
901 Lisp_Object temp;
902 XSETFASTINT (temp, GAP_SIZE);
903 return temp;
906 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
907 "Return the byte position for character position POSITION.\n\
908 If POSITION is out of range, the value is nil.")
909 (position)
910 Lisp_Object position;
912 CHECK_NUMBER_COERCE_MARKER (position, 1);
913 if (XINT (position) < BEG || XINT (position) > Z)
914 return Qnil;
915 return make_number (CHAR_TO_BYTE (XINT (position)));
918 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
919 "Return the character position for byte position BYTEPOS.\n\
920 If BYTEPOS is out of range, the value is nil.")
921 (bytepos)
922 Lisp_Object bytepos;
924 CHECK_NUMBER (bytepos, 1);
925 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
926 return Qnil;
927 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
930 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
931 "Return the character following point, as a number.\n\
932 At the end of the buffer or accessible region, return 0.")
935 Lisp_Object temp;
936 if (PT >= ZV)
937 XSETFASTINT (temp, 0);
938 else
939 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
940 return temp;
943 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
944 "Return the character preceding point, as a number.\n\
945 At the beginning of the buffer or accessible region, return 0.")
948 Lisp_Object temp;
949 if (PT <= BEGV)
950 XSETFASTINT (temp, 0);
951 else if (!NILP (current_buffer->enable_multibyte_characters))
953 int pos = PT_BYTE;
954 DEC_POS (pos);
955 XSETFASTINT (temp, FETCH_CHAR (pos));
957 else
958 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
959 return temp;
962 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
963 "Return t if point is at the beginning of the buffer.\n\
964 If the buffer is narrowed, this means the beginning of the narrowed part.")
967 if (PT == BEGV)
968 return Qt;
969 return Qnil;
972 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
973 "Return t if point is at the end of the buffer.\n\
974 If the buffer is narrowed, this means the end of the narrowed part.")
977 if (PT == ZV)
978 return Qt;
979 return Qnil;
982 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
983 "Return t if point is at the beginning of a line.")
986 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
987 return Qt;
988 return Qnil;
991 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
992 "Return t if point is at the end of a line.\n\
993 `End of a line' includes point being at the end of the buffer.")
996 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
997 return Qt;
998 return Qnil;
1001 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1002 "Return character in current buffer at position POS.\n\
1003 POS is an integer or a marker.\n\
1004 If POS is out of range, the value is nil.")
1005 (pos)
1006 Lisp_Object pos;
1008 register int pos_byte;
1010 if (NILP (pos))
1012 pos_byte = PT_BYTE;
1013 XSETFASTINT (pos, PT);
1016 if (MARKERP (pos))
1018 pos_byte = marker_byte_position (pos);
1019 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1020 return Qnil;
1022 else
1024 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1025 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1026 return Qnil;
1028 pos_byte = CHAR_TO_BYTE (XINT (pos));
1031 return make_number (FETCH_CHAR (pos_byte));
1034 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1035 "Return character in current buffer preceding position POS.\n\
1036 POS is an integer or a marker.\n\
1037 If POS is out of range, the value is nil.")
1038 (pos)
1039 Lisp_Object pos;
1041 register Lisp_Object val;
1042 register int pos_byte;
1044 if (NILP (pos))
1046 pos_byte = PT_BYTE;
1047 XSETFASTINT (pos, PT);
1050 if (MARKERP (pos))
1052 pos_byte = marker_byte_position (pos);
1054 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1055 return Qnil;
1057 else
1059 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1061 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1062 return Qnil;
1064 pos_byte = CHAR_TO_BYTE (XINT (pos));
1067 if (!NILP (current_buffer->enable_multibyte_characters))
1069 DEC_POS (pos_byte);
1070 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1072 else
1074 pos_byte--;
1075 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1077 return val;
1080 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1081 "Return the name under which the user logged in, as a string.\n\
1082 This is based on the effective uid, not the real uid.\n\
1083 Also, if the environment variable LOGNAME or USER is set,\n\
1084 that determines the value of this function.\n\n\
1085 If optional argument UID is an integer, return the login name of the user\n\
1086 with that uid, or nil if there is no such user.")
1087 (uid)
1088 Lisp_Object uid;
1090 struct passwd *pw;
1092 /* Set up the user name info if we didn't do it before.
1093 (That can happen if Emacs is dumpable
1094 but you decide to run `temacs -l loadup' and not dump. */
1095 if (INTEGERP (Vuser_login_name))
1096 init_editfns ();
1098 if (NILP (uid))
1099 return Vuser_login_name;
1101 CHECK_NUMBER (uid, 0);
1102 pw = (struct passwd *) getpwuid (XINT (uid));
1103 return (pw ? build_string (pw->pw_name) : Qnil);
1106 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1107 0, 0, 0,
1108 "Return the name of the user's real uid, as a string.\n\
1109 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1110 `user-login-name' when running under `su'.")
1113 /* Set up the user name info if we didn't do it before.
1114 (That can happen if Emacs is dumpable
1115 but you decide to run `temacs -l loadup' and not dump. */
1116 if (INTEGERP (Vuser_login_name))
1117 init_editfns ();
1118 return Vuser_real_login_name;
1121 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1122 "Return the effective uid of Emacs, as an integer.")
1125 return make_number (geteuid ());
1128 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1129 "Return the real uid of Emacs, as an integer.")
1132 return make_number (getuid ());
1135 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1136 "Return the full name of the user logged in, as a string.\n\
1137 If the full name corresponding to Emacs's userid is not known,\n\
1138 return \"unknown\".\n\
1140 If optional argument UID is an integer, return the full name of the user\n\
1141 with that uid, or nil if there is no such user.\n\
1142 If UID is a string, return the full name of the user with that login\n\
1143 name, or nil if there is no such user.")
1144 (uid)
1145 Lisp_Object uid;
1147 struct passwd *pw;
1148 register unsigned char *p, *q;
1149 Lisp_Object full;
1151 if (NILP (uid))
1152 return Vuser_full_name;
1153 else if (NUMBERP (uid))
1154 pw = (struct passwd *) getpwuid (XINT (uid));
1155 else if (STRINGP (uid))
1156 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1157 else
1158 error ("Invalid UID specification");
1160 if (!pw)
1161 return Qnil;
1163 p = (unsigned char *) USER_FULL_NAME;
1164 /* Chop off everything after the first comma. */
1165 q = (unsigned char *) index (p, ',');
1166 full = make_string (p, q ? q - p : strlen (p));
1168 #ifdef AMPERSAND_FULL_NAME
1169 p = XSTRING (full)->data;
1170 q = (unsigned char *) index (p, '&');
1171 /* Substitute the login name for the &, upcasing the first character. */
1172 if (q)
1174 register unsigned char *r;
1175 Lisp_Object login;
1177 login = Fuser_login_name (make_number (pw->pw_uid));
1178 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1179 bcopy (p, r, q - p);
1180 r[q - p] = 0;
1181 strcat (r, XSTRING (login)->data);
1182 r[q - p] = UPCASE (r[q - p]);
1183 strcat (r, q + 1);
1184 full = build_string (r);
1186 #endif /* AMPERSAND_FULL_NAME */
1188 return full;
1191 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1192 "Return the name of the machine you are running on, as a string.")
1195 return Vsystem_name;
1198 /* For the benefit of callers who don't want to include lisp.h */
1200 char *
1201 get_system_name ()
1203 if (STRINGP (Vsystem_name))
1204 return (char *) XSTRING (Vsystem_name)->data;
1205 else
1206 return "";
1209 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1210 "Return the process ID of Emacs, as an integer.")
1213 return make_number (getpid ());
1216 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1217 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1218 The time is returned as a list of three integers. The first has the\n\
1219 most significant 16 bits of the seconds, while the second has the\n\
1220 least significant 16 bits. The third integer gives the microsecond\n\
1221 count.\n\
1223 The microsecond count is zero on systems that do not provide\n\
1224 resolution finer than a second.")
1227 EMACS_TIME t;
1228 Lisp_Object result[3];
1230 EMACS_GET_TIME (t);
1231 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1232 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1233 XSETINT (result[2], EMACS_USECS (t));
1235 return Flist (3, result);
1239 static int
1240 lisp_time_argument (specified_time, result, usec)
1241 Lisp_Object specified_time;
1242 time_t *result;
1243 int *usec;
1245 if (NILP (specified_time))
1247 if (usec)
1249 EMACS_TIME t;
1251 EMACS_GET_TIME (t);
1252 *usec = EMACS_USECS (t);
1253 *result = EMACS_SECS (t);
1254 return 1;
1256 else
1257 return time (result) != -1;
1259 else
1261 Lisp_Object high, low;
1262 high = Fcar (specified_time);
1263 CHECK_NUMBER (high, 0);
1264 low = Fcdr (specified_time);
1265 if (CONSP (low))
1267 if (usec)
1269 Lisp_Object usec_l = Fcdr (low);
1270 if (CONSP (usec_l))
1271 usec_l = Fcar (usec_l);
1272 if (NILP (usec_l))
1273 *usec = 0;
1274 else
1276 CHECK_NUMBER (usec_l, 0);
1277 *usec = XINT (usec_l);
1280 low = Fcar (low);
1282 else if (usec)
1283 *usec = 0;
1284 CHECK_NUMBER (low, 0);
1285 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1286 return *result >> 16 == XINT (high);
1290 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1291 "Return the current time, as a float number of seconds since the epoch.\n\
1292 If an argument is given, it specifies a time to convert to float\n\
1293 instead of the current time. The argument should have the forms:\n\
1294 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
1295 Thus, you can use times obtained from `current-time'\n\
1296 and from `file-attributes'.")
1297 (specified_time)
1298 Lisp_Object specified_time;
1300 time_t sec;
1301 int usec;
1303 if (! lisp_time_argument (specified_time, &sec, &usec))
1304 error ("Invalid time specification");
1306 return make_float (sec + usec * 0.0000001);
1309 /* Write information into buffer S of size MAXSIZE, according to the
1310 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1311 Default to Universal Time if UT is nonzero, local time otherwise.
1312 Return the number of bytes written, not including the terminating
1313 '\0'. If S is NULL, nothing will be written anywhere; so to
1314 determine how many bytes would be written, use NULL for S and
1315 ((size_t) -1) for MAXSIZE.
1317 This function behaves like emacs_strftimeu, except it allows null
1318 bytes in FORMAT. */
1319 static size_t
1320 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1321 char *s;
1322 size_t maxsize;
1323 const char *format;
1324 size_t format_len;
1325 const struct tm *tp;
1326 int ut;
1328 size_t total = 0;
1330 /* Loop through all the null-terminated strings in the format
1331 argument. Normally there's just one null-terminated string, but
1332 there can be arbitrarily many, concatenated together, if the
1333 format contains '\0' bytes. emacs_strftimeu stops at the first
1334 '\0' byte so we must invoke it separately for each such string. */
1335 for (;;)
1337 size_t len;
1338 size_t result;
1340 if (s)
1341 s[0] = '\1';
1343 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1345 if (s)
1347 if (result == 0 && s[0] != '\0')
1348 return 0;
1349 s += result + 1;
1352 maxsize -= result + 1;
1353 total += result;
1354 len = strlen (format);
1355 if (len == format_len)
1356 return total;
1357 total++;
1358 format += len + 1;
1359 format_len -= len + 1;
1364 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1365 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1366 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1367 `current-time' or `file-attributes'.\n\
1368 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1369 as Universal Time; nil means describe TIME in the local time zone.\n\
1370 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1371 by text that describes the specified date and time in TIME:\n\
1373 %Y is the year, %y within the century, %C the century.\n\
1374 %G is the year corresponding to the ISO week, %g within the century.\n\
1375 %m is the numeric month.\n\
1376 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1377 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1378 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1379 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1380 %U is the week number starting on Sunday, %W starting on Monday,\n\
1381 %V according to ISO 8601.\n\
1382 %j is the day of the year.\n\
1384 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1385 only blank-padded, %l is like %I blank-padded.\n\
1386 %p is the locale's equivalent of either AM or PM.\n\
1387 %M is the minute.\n\
1388 %S is the second.\n\
1389 %Z is the time zone name, %z is the numeric form.\n\
1390 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1392 %c is the locale's date and time format.\n\
1393 %x is the locale's \"preferred\" date format.\n\
1394 %D is like \"%m/%d/%y\".\n\
1396 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1397 %X is the locale's \"preferred\" time format.\n\
1399 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1401 Certain flags and modifiers are available with some format controls.\n\
1402 The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
1403 but padded with blanks; %-X is like %X, but without padding.\n\
1404 %NX (where N stands for an integer) is like %X,\n\
1405 but takes up at least N (a number) positions.\n\
1406 The modifiers are `E' and `O'. For certain characters X,\n\
1407 %EX is a locale's alternative version of %X;\n\
1408 %OX is like %X, but uses the locale's number symbols.\n\
1410 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1411 (format_string, time, universal)
1414 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1415 0 /* See immediately above */)
1416 (format_string, time, universal)
1417 Lisp_Object format_string, time, universal;
1419 time_t value;
1420 int size;
1421 struct tm *tm;
1422 int ut = ! NILP (universal);
1424 CHECK_STRING (format_string, 1);
1426 if (! lisp_time_argument (time, &value, NULL))
1427 error ("Invalid time specification");
1429 format_string = code_convert_string_norecord (format_string,
1430 Vlocale_coding_system, 1);
1432 /* This is probably enough. */
1433 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1435 tm = ut ? gmtime (&value) : localtime (&value);
1436 if (! tm)
1437 error ("Specified time is not representable");
1439 synchronize_system_time_locale ();
1441 while (1)
1443 char *buf = (char *) alloca (size + 1);
1444 int result;
1446 buf[0] = '\1';
1447 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1448 STRING_BYTES (XSTRING (format_string)),
1449 tm, ut);
1450 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1451 return code_convert_string_norecord (make_string (buf, result),
1452 Vlocale_coding_system, 0);
1454 /* If buffer was too small, make it bigger and try again. */
1455 result = emacs_memftimeu (NULL, (size_t) -1,
1456 XSTRING (format_string)->data,
1457 STRING_BYTES (XSTRING (format_string)),
1458 tm, ut);
1459 size = result + 1;
1463 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1464 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1465 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1466 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1467 to use the current time. The list has the following nine members:\n\
1468 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1469 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1470 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1471 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1472 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1473 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1474 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1475 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1476 (specified_time)
1477 Lisp_Object specified_time;
1479 time_t time_spec;
1480 struct tm save_tm;
1481 struct tm *decoded_time;
1482 Lisp_Object list_args[9];
1484 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1485 error ("Invalid time specification");
1487 decoded_time = localtime (&time_spec);
1488 if (! decoded_time)
1489 error ("Specified time is not representable");
1490 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1491 XSETFASTINT (list_args[1], decoded_time->tm_min);
1492 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1493 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1494 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1495 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1496 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1497 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1499 /* Make a copy, in case gmtime modifies the struct. */
1500 save_tm = *decoded_time;
1501 decoded_time = gmtime (&time_spec);
1502 if (decoded_time == 0)
1503 list_args[8] = Qnil;
1504 else
1505 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1506 return Flist (9, list_args);
1509 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1510 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1511 This is the reverse operation of `decode-time', which see.\n\
1512 ZONE defaults to the current time zone rule. This can\n\
1513 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1514 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1515 applied without consideration for daylight savings time.\n\
1517 You can pass more than 7 arguments; then the first six arguments\n\
1518 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1519 The intervening arguments are ignored.\n\
1520 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1522 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1523 for example, a DAY of 0 means the day preceding the given month.\n\
1524 Year numbers less than 100 are treated just like other year numbers.\n\
1525 If you want them to stand for years in this century, you must do that yourself.")
1526 (nargs, args)
1527 int nargs;
1528 register Lisp_Object *args;
1530 time_t time;
1531 struct tm tm;
1532 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1534 CHECK_NUMBER (args[0], 0); /* second */
1535 CHECK_NUMBER (args[1], 1); /* minute */
1536 CHECK_NUMBER (args[2], 2); /* hour */
1537 CHECK_NUMBER (args[3], 3); /* day */
1538 CHECK_NUMBER (args[4], 4); /* month */
1539 CHECK_NUMBER (args[5], 5); /* year */
1541 tm.tm_sec = XINT (args[0]);
1542 tm.tm_min = XINT (args[1]);
1543 tm.tm_hour = XINT (args[2]);
1544 tm.tm_mday = XINT (args[3]);
1545 tm.tm_mon = XINT (args[4]) - 1;
1546 tm.tm_year = XINT (args[5]) - 1900;
1547 tm.tm_isdst = -1;
1549 if (CONSP (zone))
1550 zone = Fcar (zone);
1551 if (NILP (zone))
1552 time = mktime (&tm);
1553 else
1555 char tzbuf[100];
1556 char *tzstring;
1557 char **oldenv = environ, **newenv;
1559 if (EQ (zone, Qt))
1560 tzstring = "UTC0";
1561 else if (STRINGP (zone))
1562 tzstring = (char *) XSTRING (zone)->data;
1563 else if (INTEGERP (zone))
1565 int abszone = abs (XINT (zone));
1566 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1567 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1568 tzstring = tzbuf;
1570 else
1571 error ("Invalid time zone specification");
1573 /* Set TZ before calling mktime; merely adjusting mktime's returned
1574 value doesn't suffice, since that would mishandle leap seconds. */
1575 set_time_zone_rule (tzstring);
1577 time = mktime (&tm);
1579 /* Restore TZ to previous value. */
1580 newenv = environ;
1581 environ = oldenv;
1582 xfree (newenv);
1583 #ifdef LOCALTIME_CACHE
1584 tzset ();
1585 #endif
1588 if (time == (time_t) -1)
1589 error ("Specified time is not representable");
1591 return make_time (time);
1594 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1595 "Return the current time, as a human-readable string.\n\
1596 Programs can use this function to decode a time,\n\
1597 since the number of columns in each field is fixed.\n\
1598 The format is `Sun Sep 16 01:03:52 1973'.\n\
1599 However, see also the functions `decode-time' and `format-time-string'\n\
1600 which provide a much more powerful and general facility.\n\
1602 If an argument is given, it specifies a time to format\n\
1603 instead of the current time. The argument should have the form:\n\
1604 (HIGH . LOW)\n\
1605 or the form:\n\
1606 (HIGH LOW . IGNORED).\n\
1607 Thus, you can use times obtained from `current-time'\n\
1608 and from `file-attributes'.")
1609 (specified_time)
1610 Lisp_Object specified_time;
1612 time_t value;
1613 char buf[30];
1614 register char *tem;
1616 if (! lisp_time_argument (specified_time, &value, NULL))
1617 value = -1;
1618 tem = (char *) ctime (&value);
1620 strncpy (buf, tem, 24);
1621 buf[24] = 0;
1623 return build_string (buf);
1626 #define TM_YEAR_BASE 1900
1628 /* Yield A - B, measured in seconds.
1629 This function is copied from the GNU C Library. */
1630 static int
1631 tm_diff (a, b)
1632 struct tm *a, *b;
1634 /* Compute intervening leap days correctly even if year is negative.
1635 Take care to avoid int overflow in leap day calculations,
1636 but it's OK to assume that A and B are close to each other. */
1637 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1638 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1639 int a100 = a4 / 25 - (a4 % 25 < 0);
1640 int b100 = b4 / 25 - (b4 % 25 < 0);
1641 int a400 = a100 >> 2;
1642 int b400 = b100 >> 2;
1643 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1644 int years = a->tm_year - b->tm_year;
1645 int days = (365 * years + intervening_leap_days
1646 + (a->tm_yday - b->tm_yday));
1647 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1648 + (a->tm_min - b->tm_min))
1649 + (a->tm_sec - b->tm_sec));
1652 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1653 "Return the offset and name for the local time zone.\n\
1654 This returns a list of the form (OFFSET NAME).\n\
1655 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1656 A negative value means west of Greenwich.\n\
1657 NAME is a string giving the name of the time zone.\n\
1658 If an argument is given, it specifies when the time zone offset is determined\n\
1659 instead of using the current time. The argument should have the form:\n\
1660 (HIGH . LOW)\n\
1661 or the form:\n\
1662 (HIGH LOW . IGNORED).\n\
1663 Thus, you can use times obtained from `current-time'\n\
1664 and from `file-attributes'.\n\
1666 Some operating systems cannot provide all this information to Emacs;\n\
1667 in this case, `current-time-zone' returns a list containing nil for\n\
1668 the data it can't find.")
1669 (specified_time)
1670 Lisp_Object specified_time;
1672 time_t value;
1673 struct tm *t;
1674 struct tm gmt;
1676 if (lisp_time_argument (specified_time, &value, NULL)
1677 && (t = gmtime (&value)) != 0
1678 && (gmt = *t, t = localtime (&value)) != 0)
1680 int offset = tm_diff (t, &gmt);
1681 char *s = 0;
1682 char buf[6];
1683 #ifdef HAVE_TM_ZONE
1684 if (t->tm_zone)
1685 s = (char *)t->tm_zone;
1686 #else /* not HAVE_TM_ZONE */
1687 #ifdef HAVE_TZNAME
1688 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1689 s = tzname[t->tm_isdst];
1690 #endif
1691 #endif /* not HAVE_TM_ZONE */
1692 if (!s)
1694 /* No local time zone name is available; use "+-NNNN" instead. */
1695 int am = (offset < 0 ? -offset : offset) / 60;
1696 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1697 s = buf;
1699 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1701 else
1702 return Fmake_list (make_number (2), Qnil);
1705 /* This holds the value of `environ' produced by the previous
1706 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1707 has never been called. */
1708 static char **environbuf;
1710 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1711 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1712 If TZ is nil, use implementation-defined default time zone information.\n\
1713 If TZ is t, use Universal Time.")
1714 (tz)
1715 Lisp_Object tz;
1717 char *tzstring;
1719 if (NILP (tz))
1720 tzstring = 0;
1721 else if (EQ (tz, Qt))
1722 tzstring = "UTC0";
1723 else
1725 CHECK_STRING (tz, 0);
1726 tzstring = (char *) XSTRING (tz)->data;
1729 set_time_zone_rule (tzstring);
1730 if (environbuf)
1731 free (environbuf);
1732 environbuf = environ;
1734 return Qnil;
1737 #ifdef LOCALTIME_CACHE
1739 /* These two values are known to load tz files in buggy implementations,
1740 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1741 Their values shouldn't matter in non-buggy implementations.
1742 We don't use string literals for these strings,
1743 since if a string in the environment is in readonly
1744 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1745 See Sun bugs 1113095 and 1114114, ``Timezone routines
1746 improperly modify environment''. */
1748 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1749 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1751 #endif
1753 /* Set the local time zone rule to TZSTRING.
1754 This allocates memory into `environ', which it is the caller's
1755 responsibility to free. */
1757 void
1758 set_time_zone_rule (tzstring)
1759 char *tzstring;
1761 int envptrs;
1762 char **from, **to, **newenv;
1764 /* Make the ENVIRON vector longer with room for TZSTRING. */
1765 for (from = environ; *from; from++)
1766 continue;
1767 envptrs = from - environ + 2;
1768 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1769 + (tzstring ? strlen (tzstring) + 4 : 0));
1771 /* Add TZSTRING to the end of environ, as a value for TZ. */
1772 if (tzstring)
1774 char *t = (char *) (to + envptrs);
1775 strcpy (t, "TZ=");
1776 strcat (t, tzstring);
1777 *to++ = t;
1780 /* Copy the old environ vector elements into NEWENV,
1781 but don't copy the TZ variable.
1782 So we have only one definition of TZ, which came from TZSTRING. */
1783 for (from = environ; *from; from++)
1784 if (strncmp (*from, "TZ=", 3) != 0)
1785 *to++ = *from;
1786 *to = 0;
1788 environ = newenv;
1790 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1791 the TZ variable is stored. If we do not have a TZSTRING,
1792 TO points to the vector slot which has the terminating null. */
1794 #ifdef LOCALTIME_CACHE
1796 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1797 "US/Pacific" that loads a tz file, then changes to a value like
1798 "XXX0" that does not load a tz file, and then changes back to
1799 its original value, the last change is (incorrectly) ignored.
1800 Also, if TZ changes twice in succession to values that do
1801 not load a tz file, tzset can dump core (see Sun bug#1225179).
1802 The following code works around these bugs. */
1804 if (tzstring)
1806 /* Temporarily set TZ to a value that loads a tz file
1807 and that differs from tzstring. */
1808 char *tz = *newenv;
1809 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1810 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1811 tzset ();
1812 *newenv = tz;
1814 else
1816 /* The implied tzstring is unknown, so temporarily set TZ to
1817 two different values that each load a tz file. */
1818 *to = set_time_zone_rule_tz1;
1819 to[1] = 0;
1820 tzset ();
1821 *to = set_time_zone_rule_tz2;
1822 tzset ();
1823 *to = 0;
1826 /* Now TZ has the desired value, and tzset can be invoked safely. */
1829 tzset ();
1830 #endif
1833 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1834 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1835 type of object is Lisp_String). INHERIT is passed to
1836 INSERT_FROM_STRING_FUNC as the last argument. */
1838 static void
1839 general_insert_function (insert_func, insert_from_string_func,
1840 inherit, nargs, args)
1841 void (*insert_func) P_ ((unsigned char *, int));
1842 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1843 int inherit, nargs;
1844 register Lisp_Object *args;
1846 register int argnum;
1847 register Lisp_Object val;
1849 for (argnum = 0; argnum < nargs; argnum++)
1851 val = args[argnum];
1852 retry:
1853 if (INTEGERP (val))
1855 unsigned char str[MAX_MULTIBYTE_LENGTH];
1856 int len;
1858 if (!NILP (current_buffer->enable_multibyte_characters))
1859 len = CHAR_STRING (XFASTINT (val), str);
1860 else
1862 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1863 ? XINT (val)
1864 : multibyte_char_to_unibyte (XINT (val), Qnil));
1865 len = 1;
1867 (*insert_func) (str, len);
1869 else if (STRINGP (val))
1871 (*insert_from_string_func) (val, 0, 0,
1872 XSTRING (val)->size,
1873 STRING_BYTES (XSTRING (val)),
1874 inherit);
1876 else
1878 val = wrong_type_argument (Qchar_or_string_p, val);
1879 goto retry;
1884 void
1885 insert1 (arg)
1886 Lisp_Object arg;
1888 Finsert (1, &arg);
1892 /* Callers passing one argument to Finsert need not gcpro the
1893 argument "array", since the only element of the array will
1894 not be used after calling insert or insert_from_string, so
1895 we don't care if it gets trashed. */
1897 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1898 "Insert the arguments, either strings or characters, at point.\n\
1899 Point and before-insertion markers move forward to end up\n\
1900 after the inserted text.\n\
1901 Any other markers at the point of insertion remain before the text.\n\
1903 If the current buffer is multibyte, unibyte strings are converted\n\
1904 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1905 If the current buffer is unibyte, multibyte strings are converted\n\
1906 to unibyte for insertion.")
1907 (nargs, args)
1908 int nargs;
1909 register Lisp_Object *args;
1911 general_insert_function (insert, insert_from_string, 0, nargs, args);
1912 return Qnil;
1915 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1916 0, MANY, 0,
1917 "Insert the arguments at point, inheriting properties from adjoining text.\n\
1918 Point and before-insertion markers move forward to end up\n\
1919 after the inserted text.\n\
1920 Any other markers at the point of insertion remain before the text.\n\
1922 If the current buffer is multibyte, unibyte strings are converted\n\
1923 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1924 If the current buffer is unibyte, multibyte strings are converted\n\
1925 to unibyte for insertion.")
1926 (nargs, args)
1927 int nargs;
1928 register Lisp_Object *args;
1930 general_insert_function (insert_and_inherit, insert_from_string, 1,
1931 nargs, args);
1932 return Qnil;
1935 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1936 "Insert strings or characters at point, relocating markers after the text.\n\
1937 Point and markers move forward to end up after the inserted text.\n\
1939 If the current buffer is multibyte, unibyte strings are converted\n\
1940 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1941 If the current buffer is unibyte, multibyte strings are converted\n\
1942 to unibyte for insertion.")
1943 (nargs, args)
1944 int nargs;
1945 register Lisp_Object *args;
1947 general_insert_function (insert_before_markers,
1948 insert_from_string_before_markers, 0,
1949 nargs, args);
1950 return Qnil;
1953 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1954 Sinsert_and_inherit_before_markers, 0, MANY, 0,
1955 "Insert text at point, relocating markers and inheriting properties.\n\
1956 Point and markers move forward to end up after the inserted text.\n\
1958 If the current buffer is multibyte, unibyte strings are converted\n\
1959 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1960 If the current buffer is unibyte, multibyte strings are converted\n\
1961 to unibyte for insertion.")
1962 (nargs, args)
1963 int nargs;
1964 register Lisp_Object *args;
1966 general_insert_function (insert_before_markers_and_inherit,
1967 insert_from_string_before_markers, 1,
1968 nargs, args);
1969 return Qnil;
1972 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
1973 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
1974 Both arguments are required.\n\
1975 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
1976 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1977 from adjoining text, if those properties are sticky.")
1978 (character, count, inherit)
1979 Lisp_Object character, count, inherit;
1981 register unsigned char *string;
1982 register int strlen;
1983 register int i, n;
1984 int len;
1985 unsigned char str[MAX_MULTIBYTE_LENGTH];
1987 CHECK_NUMBER (character, 0);
1988 CHECK_NUMBER (count, 1);
1990 if (!NILP (current_buffer->enable_multibyte_characters))
1991 len = CHAR_STRING (XFASTINT (character), str);
1992 else
1993 str[0] = XFASTINT (character), len = 1;
1994 n = XINT (count) * len;
1995 if (n <= 0)
1996 return Qnil;
1997 strlen = min (n, 256 * len);
1998 string = (unsigned char *) alloca (strlen);
1999 for (i = 0; i < strlen; i++)
2000 string[i] = str[i % len];
2001 while (n >= strlen)
2003 QUIT;
2004 if (!NILP (inherit))
2005 insert_and_inherit (string, strlen);
2006 else
2007 insert (string, strlen);
2008 n -= strlen;
2010 if (n > 0)
2012 if (!NILP (inherit))
2013 insert_and_inherit (string, n);
2014 else
2015 insert (string, n);
2017 return Qnil;
2021 /* Making strings from buffer contents. */
2023 /* Return a Lisp_String containing the text of the current buffer from
2024 START to END. If text properties are in use and the current buffer
2025 has properties in the range specified, the resulting string will also
2026 have them, if PROPS is nonzero.
2028 We don't want to use plain old make_string here, because it calls
2029 make_uninit_string, which can cause the buffer arena to be
2030 compacted. make_string has no way of knowing that the data has
2031 been moved, and thus copies the wrong data into the string. This
2032 doesn't effect most of the other users of make_string, so it should
2033 be left as is. But we should use this function when conjuring
2034 buffer substrings. */
2036 Lisp_Object
2037 make_buffer_string (start, end, props)
2038 int start, end;
2039 int props;
2041 int start_byte = CHAR_TO_BYTE (start);
2042 int end_byte = CHAR_TO_BYTE (end);
2044 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2047 /* Return a Lisp_String containing the text of the current buffer from
2048 START / START_BYTE to END / END_BYTE.
2050 If text properties are in use and the current buffer
2051 has properties in the range specified, the resulting string will also
2052 have them, if PROPS is nonzero.
2054 We don't want to use plain old make_string here, because it calls
2055 make_uninit_string, which can cause the buffer arena to be
2056 compacted. make_string has no way of knowing that the data has
2057 been moved, and thus copies the wrong data into the string. This
2058 doesn't effect most of the other users of make_string, so it should
2059 be left as is. But we should use this function when conjuring
2060 buffer substrings. */
2062 Lisp_Object
2063 make_buffer_string_both (start, start_byte, end, end_byte, props)
2064 int start, start_byte, end, end_byte;
2065 int props;
2067 Lisp_Object result, tem, tem1;
2069 if (start < GPT && GPT < end)
2070 move_gap (start);
2072 if (! NILP (current_buffer->enable_multibyte_characters))
2073 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2074 else
2075 result = make_uninit_string (end - start);
2076 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
2077 end_byte - start_byte);
2079 /* If desired, update and copy the text properties. */
2080 if (props)
2082 update_buffer_properties (start, end);
2084 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2085 tem1 = Ftext_properties_at (make_number (start), Qnil);
2087 if (XINT (tem) != end || !NILP (tem1))
2088 copy_intervals_to_string (result, current_buffer, start,
2089 end - start);
2092 return result;
2095 /* Call Vbuffer_access_fontify_functions for the range START ... END
2096 in the current buffer, if necessary. */
2098 static void
2099 update_buffer_properties (start, end)
2100 int start, end;
2102 /* If this buffer has some access functions,
2103 call them, specifying the range of the buffer being accessed. */
2104 if (!NILP (Vbuffer_access_fontify_functions))
2106 Lisp_Object args[3];
2107 Lisp_Object tem;
2109 args[0] = Qbuffer_access_fontify_functions;
2110 XSETINT (args[1], start);
2111 XSETINT (args[2], end);
2113 /* But don't call them if we can tell that the work
2114 has already been done. */
2115 if (!NILP (Vbuffer_access_fontified_property))
2117 tem = Ftext_property_any (args[1], args[2],
2118 Vbuffer_access_fontified_property,
2119 Qnil, Qnil);
2120 if (! NILP (tem))
2121 Frun_hook_with_args (3, args);
2123 else
2124 Frun_hook_with_args (3, args);
2128 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2129 "Return the contents of part of the current buffer as a string.\n\
2130 The two arguments START and END are character positions;\n\
2131 they can be in either order.\n\
2132 The string returned is multibyte if the buffer is multibyte.")
2133 (start, end)
2134 Lisp_Object start, end;
2136 register int b, e;
2138 validate_region (&start, &end);
2139 b = XINT (start);
2140 e = XINT (end);
2142 return make_buffer_string (b, e, 1);
2145 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2146 Sbuffer_substring_no_properties, 2, 2, 0,
2147 "Return the characters of part of the buffer, without the text properties.\n\
2148 The two arguments START and END are character positions;\n\
2149 they can be in either order.")
2150 (start, end)
2151 Lisp_Object start, end;
2153 register int b, e;
2155 validate_region (&start, &end);
2156 b = XINT (start);
2157 e = XINT (end);
2159 return make_buffer_string (b, e, 0);
2162 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2163 "Return the contents of the current buffer as a string.\n\
2164 If narrowing is in effect, this function returns only the visible part\n\
2165 of the buffer. If in a mini-buffer, don't include the prompt in the\n\
2166 string returned.")
2169 return make_buffer_string (BEGV, ZV, 1);
2172 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2173 1, 3, 0,
2174 "Insert before point a substring of the contents of buffer BUFFER.\n\
2175 BUFFER may be a buffer or a buffer name.\n\
2176 Arguments START and END are character numbers specifying the substring.\n\
2177 They default to the beginning and the end of BUFFER.")
2178 (buf, start, end)
2179 Lisp_Object buf, start, end;
2181 register int b, e, temp;
2182 register struct buffer *bp, *obuf;
2183 Lisp_Object buffer;
2185 buffer = Fget_buffer (buf);
2186 if (NILP (buffer))
2187 nsberror (buf);
2188 bp = XBUFFER (buffer);
2189 if (NILP (bp->name))
2190 error ("Selecting deleted buffer");
2192 if (NILP (start))
2193 b = BUF_BEGV (bp);
2194 else
2196 CHECK_NUMBER_COERCE_MARKER (start, 0);
2197 b = XINT (start);
2199 if (NILP (end))
2200 e = BUF_ZV (bp);
2201 else
2203 CHECK_NUMBER_COERCE_MARKER (end, 1);
2204 e = XINT (end);
2207 if (b > e)
2208 temp = b, b = e, e = temp;
2210 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2211 args_out_of_range (start, end);
2213 obuf = current_buffer;
2214 set_buffer_internal_1 (bp);
2215 update_buffer_properties (b, e);
2216 set_buffer_internal_1 (obuf);
2218 insert_from_buffer (bp, b, e - b, 0);
2219 return Qnil;
2222 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2223 6, 6, 0,
2224 "Compare two substrings of two buffers; return result as number.\n\
2225 the value is -N if first string is less after N-1 chars,\n\
2226 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2227 Each substring is represented as three arguments: BUFFER, START and END.\n\
2228 That makes six args in all, three for each substring.\n\n\
2229 The value of `case-fold-search' in the current buffer\n\
2230 determines whether case is significant or ignored.")
2231 (buffer1, start1, end1, buffer2, start2, end2)
2232 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2234 register int begp1, endp1, begp2, endp2, temp;
2235 register struct buffer *bp1, *bp2;
2236 register Lisp_Object *trt
2237 = (!NILP (current_buffer->case_fold_search)
2238 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2239 int chars = 0;
2240 int i1, i2, i1_byte, i2_byte;
2242 /* Find the first buffer and its substring. */
2244 if (NILP (buffer1))
2245 bp1 = current_buffer;
2246 else
2248 Lisp_Object buf1;
2249 buf1 = Fget_buffer (buffer1);
2250 if (NILP (buf1))
2251 nsberror (buffer1);
2252 bp1 = XBUFFER (buf1);
2253 if (NILP (bp1->name))
2254 error ("Selecting deleted buffer");
2257 if (NILP (start1))
2258 begp1 = BUF_BEGV (bp1);
2259 else
2261 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2262 begp1 = XINT (start1);
2264 if (NILP (end1))
2265 endp1 = BUF_ZV (bp1);
2266 else
2268 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2269 endp1 = XINT (end1);
2272 if (begp1 > endp1)
2273 temp = begp1, begp1 = endp1, endp1 = temp;
2275 if (!(BUF_BEGV (bp1) <= begp1
2276 && begp1 <= endp1
2277 && endp1 <= BUF_ZV (bp1)))
2278 args_out_of_range (start1, end1);
2280 /* Likewise for second substring. */
2282 if (NILP (buffer2))
2283 bp2 = current_buffer;
2284 else
2286 Lisp_Object buf2;
2287 buf2 = Fget_buffer (buffer2);
2288 if (NILP (buf2))
2289 nsberror (buffer2);
2290 bp2 = XBUFFER (buf2);
2291 if (NILP (bp2->name))
2292 error ("Selecting deleted buffer");
2295 if (NILP (start2))
2296 begp2 = BUF_BEGV (bp2);
2297 else
2299 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2300 begp2 = XINT (start2);
2302 if (NILP (end2))
2303 endp2 = BUF_ZV (bp2);
2304 else
2306 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2307 endp2 = XINT (end2);
2310 if (begp2 > endp2)
2311 temp = begp2, begp2 = endp2, endp2 = temp;
2313 if (!(BUF_BEGV (bp2) <= begp2
2314 && begp2 <= endp2
2315 && endp2 <= BUF_ZV (bp2)))
2316 args_out_of_range (start2, end2);
2318 i1 = begp1;
2319 i2 = begp2;
2320 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2321 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2323 while (i1 < endp1 && i2 < endp2)
2325 /* When we find a mismatch, we must compare the
2326 characters, not just the bytes. */
2327 int c1, c2;
2329 if (! NILP (bp1->enable_multibyte_characters))
2331 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2332 BUF_INC_POS (bp1, i1_byte);
2333 i1++;
2335 else
2337 c1 = BUF_FETCH_BYTE (bp1, i1);
2338 c1 = unibyte_char_to_multibyte (c1);
2339 i1++;
2342 if (! NILP (bp2->enable_multibyte_characters))
2344 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2345 BUF_INC_POS (bp2, i2_byte);
2346 i2++;
2348 else
2350 c2 = BUF_FETCH_BYTE (bp2, i2);
2351 c2 = unibyte_char_to_multibyte (c2);
2352 i2++;
2355 if (trt)
2357 c1 = XINT (trt[c1]);
2358 c2 = XINT (trt[c2]);
2360 if (c1 < c2)
2361 return make_number (- 1 - chars);
2362 if (c1 > c2)
2363 return make_number (chars + 1);
2365 chars++;
2368 /* The strings match as far as they go.
2369 If one is shorter, that one is less. */
2370 if (chars < endp1 - begp1)
2371 return make_number (chars + 1);
2372 else if (chars < endp2 - begp2)
2373 return make_number (- chars - 1);
2375 /* Same length too => they are equal. */
2376 return make_number (0);
2379 static Lisp_Object
2380 subst_char_in_region_unwind (arg)
2381 Lisp_Object arg;
2383 return current_buffer->undo_list = arg;
2386 static Lisp_Object
2387 subst_char_in_region_unwind_1 (arg)
2388 Lisp_Object arg;
2390 return current_buffer->filename = arg;
2393 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2394 Ssubst_char_in_region, 4, 5, 0,
2395 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2396 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2397 and don't mark the buffer as really changed.\n\
2398 Both characters must have the same length of multi-byte form.")
2399 (start, end, fromchar, tochar, noundo)
2400 Lisp_Object start, end, fromchar, tochar, noundo;
2402 register int pos, pos_byte, stop, i, len, end_byte;
2403 int changed = 0;
2404 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2405 unsigned char *p;
2406 int count = specpdl_ptr - specpdl;
2407 #define COMBINING_NO 0
2408 #define COMBINING_BEFORE 1
2409 #define COMBINING_AFTER 2
2410 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2411 int maybe_byte_combining = COMBINING_NO;
2412 int last_changed;
2413 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2415 validate_region (&start, &end);
2416 CHECK_NUMBER (fromchar, 2);
2417 CHECK_NUMBER (tochar, 3);
2419 if (multibyte_p)
2421 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2422 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2423 error ("Characters in subst-char-in-region have different byte-lengths");
2424 if (!ASCII_BYTE_P (*tostr))
2426 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2427 complete multibyte character, it may be combined with the
2428 after bytes. If it is in the range 0xA0..0xFF, it may be
2429 combined with the before and after bytes. */
2430 if (!CHAR_HEAD_P (*tostr))
2431 maybe_byte_combining = COMBINING_BOTH;
2432 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2433 maybe_byte_combining = COMBINING_AFTER;
2436 else
2438 len = 1;
2439 fromstr[0] = XFASTINT (fromchar);
2440 tostr[0] = XFASTINT (tochar);
2443 pos = XINT (start);
2444 pos_byte = CHAR_TO_BYTE (pos);
2445 stop = CHAR_TO_BYTE (XINT (end));
2446 end_byte = stop;
2448 /* If we don't want undo, turn off putting stuff on the list.
2449 That's faster than getting rid of things,
2450 and it prevents even the entry for a first change.
2451 Also inhibit locking the file. */
2452 if (!NILP (noundo))
2454 record_unwind_protect (subst_char_in_region_unwind,
2455 current_buffer->undo_list);
2456 current_buffer->undo_list = Qt;
2457 /* Don't do file-locking. */
2458 record_unwind_protect (subst_char_in_region_unwind_1,
2459 current_buffer->filename);
2460 current_buffer->filename = Qnil;
2463 if (pos_byte < GPT_BYTE)
2464 stop = min (stop, GPT_BYTE);
2465 while (1)
2467 int pos_byte_next = pos_byte;
2469 if (pos_byte >= stop)
2471 if (pos_byte >= end_byte) break;
2472 stop = end_byte;
2474 p = BYTE_POS_ADDR (pos_byte);
2475 if (multibyte_p)
2476 INC_POS (pos_byte_next);
2477 else
2478 ++pos_byte_next;
2479 if (pos_byte_next - pos_byte == len
2480 && p[0] == fromstr[0]
2481 && (len == 1
2482 || (p[1] == fromstr[1]
2483 && (len == 2 || (p[2] == fromstr[2]
2484 && (len == 3 || p[3] == fromstr[3]))))))
2486 if (! changed)
2488 changed = pos;
2489 modify_region (current_buffer, changed, XINT (end));
2491 if (! NILP (noundo))
2493 if (MODIFF - 1 == SAVE_MODIFF)
2494 SAVE_MODIFF++;
2495 if (MODIFF - 1 == current_buffer->auto_save_modified)
2496 current_buffer->auto_save_modified++;
2500 /* Take care of the case where the new character
2501 combines with neighboring bytes. */
2502 if (maybe_byte_combining
2503 && (maybe_byte_combining == COMBINING_AFTER
2504 ? (pos_byte_next < Z_BYTE
2505 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2506 : ((pos_byte_next < Z_BYTE
2507 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2508 || (pos_byte > BEG_BYTE
2509 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2511 Lisp_Object tem, string;
2513 struct gcpro gcpro1;
2515 tem = current_buffer->undo_list;
2516 GCPRO1 (tem);
2518 /* Make a multibyte string containing this single character. */
2519 string = make_multibyte_string (tostr, 1, len);
2520 /* replace_range is less efficient, because it moves the gap,
2521 but it handles combining correctly. */
2522 replace_range (pos, pos + 1, string,
2523 0, 0, 1);
2524 pos_byte_next = CHAR_TO_BYTE (pos);
2525 if (pos_byte_next > pos_byte)
2526 /* Before combining happened. We should not increment
2527 POS. So, to cancel the later increment of POS,
2528 decrease it now. */
2529 pos--;
2530 else
2531 INC_POS (pos_byte_next);
2533 if (! NILP (noundo))
2534 current_buffer->undo_list = tem;
2536 UNGCPRO;
2538 else
2540 if (NILP (noundo))
2541 record_change (pos, 1);
2542 for (i = 0; i < len; i++) *p++ = tostr[i];
2544 last_changed = pos + 1;
2546 pos_byte = pos_byte_next;
2547 pos++;
2550 if (changed)
2552 signal_after_change (changed,
2553 last_changed - changed, last_changed - changed);
2554 update_compositions (changed, last_changed, CHECK_ALL);
2557 unbind_to (count, Qnil);
2558 return Qnil;
2561 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2562 "From START to END, translate characters according to TABLE.\n\
2563 TABLE is a string; the Nth character in it is the mapping\n\
2564 for the character with code N.\n\
2565 This function does not alter multibyte characters.\n\
2566 It returns the number of characters changed.")
2567 (start, end, table)
2568 Lisp_Object start;
2569 Lisp_Object end;
2570 register Lisp_Object table;
2572 register int pos_byte, stop; /* Limits of the region. */
2573 register unsigned char *tt; /* Trans table. */
2574 register int nc; /* New character. */
2575 int cnt; /* Number of changes made. */
2576 int size; /* Size of translate table. */
2577 int pos;
2578 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2580 validate_region (&start, &end);
2581 CHECK_STRING (table, 2);
2583 size = STRING_BYTES (XSTRING (table));
2584 tt = XSTRING (table)->data;
2586 pos_byte = CHAR_TO_BYTE (XINT (start));
2587 stop = CHAR_TO_BYTE (XINT (end));
2588 modify_region (current_buffer, XINT (start), XINT (end));
2589 pos = XINT (start);
2591 cnt = 0;
2592 for (; pos_byte < stop; )
2594 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2595 int len;
2596 int oc;
2597 int pos_byte_next;
2599 if (multibyte)
2600 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2601 else
2602 oc = *p, len = 1;
2603 pos_byte_next = pos_byte + len;
2604 if (oc < size && len == 1)
2606 nc = tt[oc];
2607 if (nc != oc)
2609 /* Take care of the case where the new character
2610 combines with neighboring bytes. */
2611 if (!ASCII_BYTE_P (nc)
2612 && (CHAR_HEAD_P (nc)
2613 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2614 : (pos_byte > BEG_BYTE
2615 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2617 Lisp_Object string;
2619 string = make_multibyte_string (tt + oc, 1, 1);
2620 /* This is less efficient, because it moves the gap,
2621 but it handles combining correctly. */
2622 replace_range (pos, pos + 1, string,
2623 1, 0, 1);
2624 pos_byte_next = CHAR_TO_BYTE (pos);
2625 if (pos_byte_next > pos_byte)
2626 /* Before combining happened. We should not
2627 increment POS. So, to cancel the later
2628 increment of POS, we decrease it now. */
2629 pos--;
2630 else
2631 INC_POS (pos_byte_next);
2633 else
2635 record_change (pos, 1);
2636 *p = nc;
2637 signal_after_change (pos, 1, 1);
2638 update_compositions (pos, pos + 1, CHECK_BORDER);
2640 ++cnt;
2643 pos_byte = pos_byte_next;
2644 pos++;
2647 return make_number (cnt);
2650 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2651 "Delete the text between point and mark.\n\
2652 When called from a program, expects two arguments,\n\
2653 positions (integers or markers) specifying the stretch to be deleted.")
2654 (start, end)
2655 Lisp_Object start, end;
2657 validate_region (&start, &end);
2658 del_range (XINT (start), XINT (end));
2659 return Qnil;
2662 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2663 Sdelete_and_extract_region, 2, 2, 0,
2664 "Delete the text between START and END and return it.")
2665 (start, end)
2666 Lisp_Object start, end;
2668 validate_region (&start, &end);
2669 return del_range_1 (XINT (start), XINT (end), 1, 1);
2672 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2673 "Remove restrictions (narrowing) from current buffer.\n\
2674 This allows the buffer's full text to be seen and edited.")
2677 if (BEG != BEGV || Z != ZV)
2678 current_buffer->clip_changed = 1;
2679 BEGV = BEG;
2680 BEGV_BYTE = BEG_BYTE;
2681 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2682 /* Changing the buffer bounds invalidates any recorded current column. */
2683 invalidate_current_column ();
2684 return Qnil;
2687 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2688 "Restrict editing in this buffer to the current region.\n\
2689 The rest of the text becomes temporarily invisible and untouchable\n\
2690 but is not deleted; if you save the buffer in a file, the invisible\n\
2691 text is included in the file. \\[widen] makes all visible again.\n\
2692 See also `save-restriction'.\n\
2694 When calling from a program, pass two arguments; positions (integers\n\
2695 or markers) bounding the text that should remain visible.")
2696 (start, end)
2697 register Lisp_Object start, end;
2699 CHECK_NUMBER_COERCE_MARKER (start, 0);
2700 CHECK_NUMBER_COERCE_MARKER (end, 1);
2702 if (XINT (start) > XINT (end))
2704 Lisp_Object tem;
2705 tem = start; start = end; end = tem;
2708 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2709 args_out_of_range (start, end);
2711 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2712 current_buffer->clip_changed = 1;
2714 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2715 SET_BUF_ZV (current_buffer, XFASTINT (end));
2716 if (PT < XFASTINT (start))
2717 SET_PT (XFASTINT (start));
2718 if (PT > XFASTINT (end))
2719 SET_PT (XFASTINT (end));
2720 /* Changing the buffer bounds invalidates any recorded current column. */
2721 invalidate_current_column ();
2722 return Qnil;
2725 Lisp_Object
2726 save_restriction_save ()
2728 if (BEGV == BEG && ZV == Z)
2729 /* The common case that the buffer isn't narrowed.
2730 We return just the buffer object, which save_restriction_restore
2731 recognizes as meaning `no restriction'. */
2732 return Fcurrent_buffer ();
2733 else
2734 /* We have to save a restriction, so return a pair of markers, one
2735 for the beginning and one for the end. */
2737 Lisp_Object beg, end;
2739 beg = buildmark (BEGV, BEGV_BYTE);
2740 end = buildmark (ZV, ZV_BYTE);
2742 /* END must move forward if text is inserted at its exact location. */
2743 XMARKER(end)->insertion_type = 1;
2745 return Fcons (beg, end);
2749 Lisp_Object
2750 save_restriction_restore (data)
2751 Lisp_Object data;
2753 if (CONSP (data))
2754 /* A pair of marks bounding a saved restriction. */
2756 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2757 struct Lisp_Marker *end = XMARKER (XCDR (data));
2758 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2760 if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
2761 /* The restriction has changed from the saved one, so restore
2762 the saved restriction. */
2764 int pt = BUF_PT (buf);
2766 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2767 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2769 if (pt < beg->charpos || pt > end->charpos)
2770 /* The point is outside the new visible range, move it inside. */
2771 SET_BUF_PT_BOTH (buf,
2772 clip_to_bounds (beg->charpos, pt, end->charpos),
2773 clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
2774 end->bytepos));
2776 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2779 else
2780 /* A buffer, which means that there was no old restriction. */
2782 struct buffer *buf = XBUFFER (data);
2784 if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
2785 /* The buffer has been narrowed, get rid of the narrowing. */
2787 SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
2788 SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
2790 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2794 return Qnil;
2797 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2798 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2799 The buffer's restrictions make parts of the beginning and end invisible.\n\
2800 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2801 This special form, `save-restriction', saves the current buffer's restrictions\n\
2802 when it is entered, and restores them when it is exited.\n\
2803 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2804 The old restrictions settings are restored\n\
2805 even in case of abnormal exit (throw or error).\n\
2807 The value returned is the value of the last form in BODY.\n\
2809 Note: if you are using both `save-excursion' and `save-restriction',\n\
2810 use `save-excursion' outermost:\n\
2811 (save-excursion (save-restriction ...))")
2812 (body)
2813 Lisp_Object body;
2815 register Lisp_Object val;
2816 int count = specpdl_ptr - specpdl;
2818 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2819 val = Fprogn (body);
2820 return unbind_to (count, val);
2823 #ifndef HAVE_MENUS
2825 /* Buffer for the most recent text displayed by Fmessage. */
2826 static char *message_text;
2828 /* Allocated length of that buffer. */
2829 static int message_length;
2831 #endif /* not HAVE_MENUS */
2833 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2834 "Print a one-line message at the bottom of the screen.\n\
2835 The first argument is a format control string, and the rest are data\n\
2836 to be formatted under control of the string. See `format' for details.\n\
2838 If the first argument is nil, clear any existing message; let the\n\
2839 minibuffer contents show.")
2840 (nargs, args)
2841 int nargs;
2842 Lisp_Object *args;
2844 if (NILP (args[0]))
2846 message (0);
2847 return Qnil;
2849 else
2851 register Lisp_Object val;
2852 val = Fformat (nargs, args);
2853 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2854 return val;
2858 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2859 "Display a message, in a dialog box if possible.\n\
2860 If a dialog box is not available, use the echo area.\n\
2861 The first argument is a format control string, and the rest are data\n\
2862 to be formatted under control of the string. See `format' for details.\n\
2864 If the first argument is nil, clear any existing message; let the\n\
2865 minibuffer contents show.")
2866 (nargs, args)
2867 int nargs;
2868 Lisp_Object *args;
2870 if (NILP (args[0]))
2872 message (0);
2873 return Qnil;
2875 else
2877 register Lisp_Object val;
2878 val = Fformat (nargs, args);
2879 #ifdef HAVE_MENUS
2881 Lisp_Object pane, menu, obj;
2882 struct gcpro gcpro1;
2883 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2884 GCPRO1 (pane);
2885 menu = Fcons (val, pane);
2886 obj = Fx_popup_dialog (Qt, menu);
2887 UNGCPRO;
2888 return val;
2890 #else /* not HAVE_MENUS */
2891 /* Copy the data so that it won't move when we GC. */
2892 if (! message_text)
2894 message_text = (char *)xmalloc (80);
2895 message_length = 80;
2897 if (STRING_BYTES (XSTRING (val)) > message_length)
2899 message_length = STRING_BYTES (XSTRING (val));
2900 message_text = (char *)xrealloc (message_text, message_length);
2902 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2903 message2 (message_text, STRING_BYTES (XSTRING (val)),
2904 STRING_MULTIBYTE (val));
2905 return val;
2906 #endif /* not HAVE_MENUS */
2909 #ifdef HAVE_MENUS
2910 extern Lisp_Object last_nonmenu_event;
2911 #endif
2913 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2914 "Display a message in a dialog box or in the echo area.\n\
2915 If this command was invoked with the mouse, use a dialog box.\n\
2916 Otherwise, use the echo area.\n\
2917 The first argument is a format control string, and the rest are data\n\
2918 to be formatted under control of the string. See `format' for details.\n\
2920 If the first argument is nil, clear any existing message; let the\n\
2921 minibuffer contents show.")
2922 (nargs, args)
2923 int nargs;
2924 Lisp_Object *args;
2926 #ifdef HAVE_MENUS
2927 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2928 && use_dialog_box)
2929 return Fmessage_box (nargs, args);
2930 #endif
2931 return Fmessage (nargs, args);
2934 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2935 "Return the string currently displayed in the echo area, or nil if none.")
2938 return current_message ();
2942 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
2943 "Return a copy of STRING with text properties added.\n\
2944 First argument is the string to copy.\n\
2945 Remaining arguments form a sequence of PROPERTY VALUE pairs for text\n\
2946 properties to add to the result ")
2947 (nargs, args)
2948 int nargs;
2949 Lisp_Object *args;
2951 Lisp_Object properties, string;
2952 struct gcpro gcpro1, gcpro2;
2953 int i;
2955 /* Number of args must be odd. */
2956 if ((nargs & 1) == 0 || nargs < 3)
2957 error ("Wrong number of arguments");
2959 properties = string = Qnil;
2960 GCPRO2 (properties, string);
2962 /* First argument must be a string. */
2963 CHECK_STRING (args[0], 0);
2964 string = Fcopy_sequence (args[0]);
2966 for (i = 1; i < nargs; i += 2)
2968 CHECK_SYMBOL (args[i], i);
2969 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2972 Fadd_text_properties (make_number (0),
2973 make_number (XSTRING (string)->size),
2974 properties, string);
2975 RETURN_UNGCPRO (string);
2979 /* Number of bytes that STRING will occupy when put into the result.
2980 MULTIBYTE is nonzero if the result should be multibyte. */
2982 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
2983 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
2984 ? count_size_as_multibyte (XSTRING (STRING)->data, \
2985 STRING_BYTES (XSTRING (STRING))) \
2986 : STRING_BYTES (XSTRING (STRING)))
2988 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
2989 "Format a string out of a control-string and arguments.\n\
2990 The first argument is a control string.\n\
2991 The other arguments are substituted into it to make the result, a string.\n\
2992 It may contain %-sequences meaning to substitute the next argument.\n\
2993 %s means print a string argument. Actually, prints any object, with `princ'.\n\
2994 %d means print as number in decimal (%o octal, %x hex).\n\
2995 %e means print a number in exponential notation.\n\
2996 %f means print a number in decimal-point notation.\n\
2997 %g means print a number in exponential notation\n\
2998 or decimal-point notation, whichever uses fewer characters.\n\
2999 %c means print a number as a single character.\n\
3000 %S means print any object as an s-expression (using `prin1').\n\
3001 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
3002 Use %% to put a single % into the output.")
3003 (nargs, args)
3004 int nargs;
3005 register Lisp_Object *args;
3007 register int n; /* The number of the next arg to substitute */
3008 register int total; /* An estimate of the final length */
3009 char *buf, *p;
3010 register unsigned char *format, *end;
3011 int nchars;
3012 /* Nonzero if the output should be a multibyte string,
3013 which is true if any of the inputs is one. */
3014 int multibyte = 0;
3015 /* When we make a multibyte string, we must pay attention to the
3016 byte combining problem, i.e., a byte may be combined with a
3017 multibyte charcter of the previous string. This flag tells if we
3018 must consider such a situation or not. */
3019 int maybe_combine_byte;
3020 unsigned char *this_format;
3021 int longest_format;
3022 Lisp_Object val;
3023 struct info
3025 int start, end;
3026 } *info = 0;
3028 /* It should not be necessary to GCPRO ARGS, because
3029 the caller in the interpreter should take care of that. */
3031 /* Try to determine whether the result should be multibyte.
3032 This is not always right; sometimes the result needs to be multibyte
3033 because of an object that we will pass through prin1,
3034 and in that case, we won't know it here. */
3035 for (n = 0; n < nargs; n++)
3036 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3037 multibyte = 1;
3039 CHECK_STRING (args[0], 0);
3041 /* If we start out planning a unibyte result,
3042 and later find it has to be multibyte, we jump back to retry. */
3043 retry:
3045 format = XSTRING (args[0])->data;
3046 end = format + STRING_BYTES (XSTRING (args[0]));
3047 longest_format = 0;
3049 /* Make room in result for all the non-%-codes in the control string. */
3050 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3052 /* Add to TOTAL enough space to hold the converted arguments. */
3054 n = 0;
3055 while (format != end)
3056 if (*format++ == '%')
3058 int minlen, thissize = 0;
3059 unsigned char *this_format_start = format - 1;
3061 /* Process a numeric arg and skip it. */
3062 minlen = atoi (format);
3063 if (minlen < 0)
3064 minlen = - minlen;
3066 while ((*format >= '0' && *format <= '9')
3067 || *format == '-' || *format == ' ' || *format == '.')
3068 format++;
3070 if (format - this_format_start + 1 > longest_format)
3071 longest_format = format - this_format_start + 1;
3073 if (format == end)
3074 error ("Format string ends in middle of format specifier");
3075 if (*format == '%')
3076 format++;
3077 else if (++n >= nargs)
3078 error ("Not enough arguments for format string");
3079 else if (*format == 'S')
3081 /* For `S', prin1 the argument and then treat like a string. */
3082 register Lisp_Object tem;
3083 tem = Fprin1_to_string (args[n], Qnil);
3084 if (STRING_MULTIBYTE (tem) && ! multibyte)
3086 multibyte = 1;
3087 goto retry;
3089 args[n] = tem;
3090 goto string;
3092 else if (SYMBOLP (args[n]))
3094 /* Use a temp var to avoid problems when ENABLE_CHECKING
3095 is turned on. */
3096 struct Lisp_String *t = XSYMBOL (args[n])->name;
3097 XSETSTRING (args[n], t);
3098 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3100 multibyte = 1;
3101 goto retry;
3103 goto string;
3105 else if (STRINGP (args[n]))
3107 string:
3108 if (*format != 's' && *format != 'S')
3109 error ("Format specifier doesn't match argument type");
3110 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3112 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3113 else if (INTEGERP (args[n]) && *format != 's')
3115 /* The following loop assumes the Lisp type indicates
3116 the proper way to pass the argument.
3117 So make sure we have a flonum if the argument should
3118 be a double. */
3119 if (*format == 'e' || *format == 'f' || *format == 'g')
3120 args[n] = Ffloat (args[n]);
3121 else
3122 if (*format != 'd' && *format != 'o' && *format != 'x'
3123 && *format != 'i' && *format != 'X' && *format != 'c')
3124 error ("Invalid format operation %%%c", *format);
3126 thissize = 30;
3127 if (*format == 'c'
3128 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3129 || XINT (args[n]) == 0))
3131 if (! multibyte)
3133 multibyte = 1;
3134 goto retry;
3136 args[n] = Fchar_to_string (args[n]);
3137 thissize = STRING_BYTES (XSTRING (args[n]));
3140 else if (FLOATP (args[n]) && *format != 's')
3142 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3143 args[n] = Ftruncate (args[n], Qnil);
3144 thissize = 200;
3146 else
3148 /* Anything but a string, convert to a string using princ. */
3149 register Lisp_Object tem;
3150 tem = Fprin1_to_string (args[n], Qt);
3151 if (STRING_MULTIBYTE (tem) & ! multibyte)
3153 multibyte = 1;
3154 goto retry;
3156 args[n] = tem;
3157 goto string;
3160 if (thissize < minlen)
3161 thissize = minlen;
3163 total += thissize + 4;
3166 /* Now we can no longer jump to retry.
3167 TOTAL and LONGEST_FORMAT are known for certain. */
3169 this_format = (unsigned char *) alloca (longest_format + 1);
3171 /* Allocate the space for the result.
3172 Note that TOTAL is an overestimate. */
3173 if (total < 1000)
3174 buf = (char *) alloca (total + 1);
3175 else
3176 buf = (char *) xmalloc (total + 1);
3178 p = buf;
3179 nchars = 0;
3180 n = 0;
3182 /* Scan the format and store result in BUF. */
3183 format = XSTRING (args[0])->data;
3184 maybe_combine_byte = 0;
3185 while (format != end)
3187 if (*format == '%')
3189 int minlen;
3190 int negative = 0;
3191 unsigned char *this_format_start = format;
3193 format++;
3195 /* Process a numeric arg and skip it. */
3196 minlen = atoi (format);
3197 if (minlen < 0)
3198 minlen = - minlen, negative = 1;
3200 while ((*format >= '0' && *format <= '9')
3201 || *format == '-' || *format == ' ' || *format == '.')
3202 format++;
3204 if (*format++ == '%')
3206 *p++ = '%';
3207 nchars++;
3208 continue;
3211 ++n;
3213 if (STRINGP (args[n]))
3215 int padding, nbytes;
3216 int width = strwidth (XSTRING (args[n])->data,
3217 STRING_BYTES (XSTRING (args[n])));
3218 int start = nchars;
3220 /* If spec requires it, pad on right with spaces. */
3221 padding = minlen - width;
3222 if (! negative)
3223 while (padding-- > 0)
3225 *p++ = ' ';
3226 nchars++;
3229 if (p > buf
3230 && multibyte
3231 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3232 && STRING_MULTIBYTE (args[n])
3233 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3234 maybe_combine_byte = 1;
3235 nbytes = copy_text (XSTRING (args[n])->data, p,
3236 STRING_BYTES (XSTRING (args[n])),
3237 STRING_MULTIBYTE (args[n]), multibyte);
3238 p += nbytes;
3239 nchars += XSTRING (args[n])->size;
3241 if (negative)
3242 while (padding-- > 0)
3244 *p++ = ' ';
3245 nchars++;
3248 /* If this argument has text properties, record where
3249 in the result string it appears. */
3250 if (XSTRING (args[n])->intervals)
3252 if (!info)
3254 int nbytes = nargs * sizeof *info;
3255 info = (struct info *) alloca (nbytes);
3256 bzero (info, nbytes);
3259 info[n].start = start;
3260 info[n].end = nchars;
3263 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3265 int this_nchars;
3267 bcopy (this_format_start, this_format,
3268 format - this_format_start);
3269 this_format[format - this_format_start] = 0;
3271 if (INTEGERP (args[n]))
3272 sprintf (p, this_format, XINT (args[n]));
3273 else
3274 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3276 if (p > buf
3277 && multibyte
3278 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3279 && !CHAR_HEAD_P (*((unsigned char *) p)))
3280 maybe_combine_byte = 1;
3281 this_nchars = strlen (p);
3282 if (multibyte)
3283 p += str_to_multibyte (p, buf + total - p, this_nchars);
3284 else
3285 p += this_nchars;
3286 nchars += this_nchars;
3289 else if (STRING_MULTIBYTE (args[0]))
3291 /* Copy a whole multibyte character. */
3292 if (p > buf
3293 && multibyte
3294 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3295 && !CHAR_HEAD_P (*format))
3296 maybe_combine_byte = 1;
3297 *p++ = *format++;
3298 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3299 nchars++;
3301 else if (multibyte)
3303 /* Convert a single-byte character to multibyte. */
3304 int len = copy_text (format, p, 1, 0, 1);
3306 p += len;
3307 format++;
3308 nchars++;
3310 else
3311 *p++ = *format++, nchars++;
3314 if (maybe_combine_byte)
3315 nchars = multibyte_chars_in_text (buf, p - buf);
3316 val = make_specified_string (buf, nchars, p - buf, multibyte);
3318 /* If we allocated BUF with malloc, free it too. */
3319 if (total >= 1000)
3320 xfree (buf);
3322 /* If the format string has text properties, or any of the string
3323 arguments has text properties, set up text properties of the
3324 result string. */
3326 if (XSTRING (args[0])->intervals || info)
3328 Lisp_Object len, new_len, props;
3329 struct gcpro gcpro1;
3331 /* Add text properties from the format string. */
3332 len = make_number (XSTRING (args[0])->size);
3333 props = text_property_list (args[0], make_number (0), len, Qnil);
3334 GCPRO1 (props);
3336 if (CONSP (props))
3338 new_len = make_number (XSTRING (val)->size);
3339 extend_property_ranges (props, len, new_len);
3340 add_text_properties_from_list (val, props, make_number (0));
3343 /* Add text properties from arguments. */
3344 if (info)
3345 for (n = 1; n < nargs; ++n)
3346 if (info[n].end)
3348 len = make_number (XSTRING (args[n])->size);
3349 new_len = make_number (info[n].end - info[n].start);
3350 props = text_property_list (args[n], make_number (0), len, Qnil);
3351 extend_property_ranges (props, len, new_len);
3352 /* If successive arguments have properites, be sure that
3353 the value of `composition' property be the copy. */
3354 if (n > 1 && info[n - 1].end)
3355 make_composition_value_copy (props);
3356 add_text_properties_from_list (val, props,
3357 make_number (info[n].start));
3360 UNGCPRO;
3363 return val;
3367 /* VARARGS 1 */
3368 Lisp_Object
3369 #ifdef NO_ARG_ARRAY
3370 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3371 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3372 #else
3373 format1 (string1)
3374 #endif
3375 char *string1;
3377 char buf[100];
3378 #ifdef NO_ARG_ARRAY
3379 EMACS_INT args[5];
3380 args[0] = arg0;
3381 args[1] = arg1;
3382 args[2] = arg2;
3383 args[3] = arg3;
3384 args[4] = arg4;
3385 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3386 #else
3387 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3388 #endif
3389 return build_string (buf);
3392 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3393 "Return t if two characters match, optionally ignoring case.\n\
3394 Both arguments must be characters (i.e. integers).\n\
3395 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3396 (c1, c2)
3397 register Lisp_Object c1, c2;
3399 int i1, i2;
3400 CHECK_NUMBER (c1, 0);
3401 CHECK_NUMBER (c2, 1);
3403 if (XINT (c1) == XINT (c2))
3404 return Qt;
3405 if (NILP (current_buffer->case_fold_search))
3406 return Qnil;
3408 /* Do these in separate statements,
3409 then compare the variables.
3410 because of the way DOWNCASE uses temp variables. */
3411 i1 = DOWNCASE (XFASTINT (c1));
3412 i2 = DOWNCASE (XFASTINT (c2));
3413 return (i1 == i2 ? Qt : Qnil);
3416 /* Transpose the markers in two regions of the current buffer, and
3417 adjust the ones between them if necessary (i.e.: if the regions
3418 differ in size).
3420 START1, END1 are the character positions of the first region.
3421 START1_BYTE, END1_BYTE are the byte positions.
3422 START2, END2 are the character positions of the second region.
3423 START2_BYTE, END2_BYTE are the byte positions.
3425 Traverses the entire marker list of the buffer to do so, adding an
3426 appropriate amount to some, subtracting from some, and leaving the
3427 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3429 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3431 static void
3432 transpose_markers (start1, end1, start2, end2,
3433 start1_byte, end1_byte, start2_byte, end2_byte)
3434 register int start1, end1, start2, end2;
3435 register int start1_byte, end1_byte, start2_byte, end2_byte;
3437 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3438 register Lisp_Object marker;
3440 /* Update point as if it were a marker. */
3441 if (PT < start1)
3443 else if (PT < end1)
3444 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3445 PT_BYTE + (end2_byte - end1_byte));
3446 else if (PT < start2)
3447 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3448 (PT_BYTE + (end2_byte - start2_byte)
3449 - (end1_byte - start1_byte)));
3450 else if (PT < end2)
3451 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3452 PT_BYTE - (start2_byte - start1_byte));
3454 /* We used to adjust the endpoints here to account for the gap, but that
3455 isn't good enough. Even if we assume the caller has tried to move the
3456 gap out of our way, it might still be at start1 exactly, for example;
3457 and that places it `inside' the interval, for our purposes. The amount
3458 of adjustment is nontrivial if there's a `denormalized' marker whose
3459 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3460 the dirty work to Fmarker_position, below. */
3462 /* The difference between the region's lengths */
3463 diff = (end2 - start2) - (end1 - start1);
3464 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3466 /* For shifting each marker in a region by the length of the other
3467 region plus the distance between the regions. */
3468 amt1 = (end2 - start2) + (start2 - end1);
3469 amt2 = (end1 - start1) + (start2 - end1);
3470 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3471 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3473 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3474 marker = XMARKER (marker)->chain)
3476 mpos = marker_byte_position (marker);
3477 if (mpos >= start1_byte && mpos < end2_byte)
3479 if (mpos < end1_byte)
3480 mpos += amt1_byte;
3481 else if (mpos < start2_byte)
3482 mpos += diff_byte;
3483 else
3484 mpos -= amt2_byte;
3485 XMARKER (marker)->bytepos = mpos;
3487 mpos = XMARKER (marker)->charpos;
3488 if (mpos >= start1 && mpos < end2)
3490 if (mpos < end1)
3491 mpos += amt1;
3492 else if (mpos < start2)
3493 mpos += diff;
3494 else
3495 mpos -= amt2;
3497 XMARKER (marker)->charpos = mpos;
3501 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3502 "Transpose region START1 to END1 with START2 to END2.\n\
3503 The regions may not be overlapping, because the size of the buffer is\n\
3504 never changed in a transposition.\n\
3506 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3507 any markers that happen to be located in the regions.\n\
3509 Transposing beyond buffer boundaries is an error.")
3510 (startr1, endr1, startr2, endr2, leave_markers)
3511 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3513 register int start1, end1, start2, end2;
3514 int start1_byte, start2_byte, len1_byte, len2_byte;
3515 int gap, len1, len_mid, len2;
3516 unsigned char *start1_addr, *start2_addr, *temp;
3517 struct gcpro gcpro1, gcpro2;
3519 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3520 cur_intv = BUF_INTERVALS (current_buffer);
3522 validate_region (&startr1, &endr1);
3523 validate_region (&startr2, &endr2);
3525 start1 = XFASTINT (startr1);
3526 end1 = XFASTINT (endr1);
3527 start2 = XFASTINT (startr2);
3528 end2 = XFASTINT (endr2);
3529 gap = GPT;
3531 /* Swap the regions if they're reversed. */
3532 if (start2 < end1)
3534 register int glumph = start1;
3535 start1 = start2;
3536 start2 = glumph;
3537 glumph = end1;
3538 end1 = end2;
3539 end2 = glumph;
3542 len1 = end1 - start1;
3543 len2 = end2 - start2;
3545 if (start2 < end1)
3546 error ("Transposed regions overlap");
3547 else if (start1 == end1 || start2 == end2)
3548 error ("Transposed region has length 0");
3550 /* The possibilities are:
3551 1. Adjacent (contiguous) regions, or separate but equal regions
3552 (no, really equal, in this case!), or
3553 2. Separate regions of unequal size.
3555 The worst case is usually No. 2. It means that (aside from
3556 potential need for getting the gap out of the way), there also
3557 needs to be a shifting of the text between the two regions. So
3558 if they are spread far apart, we are that much slower... sigh. */
3560 /* It must be pointed out that the really studly thing to do would
3561 be not to move the gap at all, but to leave it in place and work
3562 around it if necessary. This would be extremely efficient,
3563 especially considering that people are likely to do
3564 transpositions near where they are working interactively, which
3565 is exactly where the gap would be found. However, such code
3566 would be much harder to write and to read. So, if you are
3567 reading this comment and are feeling squirrely, by all means have
3568 a go! I just didn't feel like doing it, so I will simply move
3569 the gap the minimum distance to get it out of the way, and then
3570 deal with an unbroken array. */
3572 /* Make sure the gap won't interfere, by moving it out of the text
3573 we will operate on. */
3574 if (start1 < gap && gap < end2)
3576 if (gap - start1 < end2 - gap)
3577 move_gap (start1);
3578 else
3579 move_gap (end2);
3582 start1_byte = CHAR_TO_BYTE (start1);
3583 start2_byte = CHAR_TO_BYTE (start2);
3584 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3585 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3587 #ifdef BYTE_COMBINING_DEBUG
3588 if (end1 == start2)
3590 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3591 len2_byte, start1, start1_byte)
3592 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3593 len1_byte, end2, start2_byte + len2_byte)
3594 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3595 len1_byte, end2, start2_byte + len2_byte))
3596 abort ();
3598 else
3600 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3601 len2_byte, start1, start1_byte)
3602 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3603 len1_byte, start2, start2_byte)
3604 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3605 len2_byte, end1, start1_byte + len1_byte)
3606 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3607 len1_byte, end2, start2_byte + len2_byte))
3608 abort ();
3610 #endif
3612 /* Hmmm... how about checking to see if the gap is large
3613 enough to use as the temporary storage? That would avoid an
3614 allocation... interesting. Later, don't fool with it now. */
3616 /* Working without memmove, for portability (sigh), so must be
3617 careful of overlapping subsections of the array... */
3619 if (end1 == start2) /* adjacent regions */
3621 modify_region (current_buffer, start1, end2);
3622 record_change (start1, len1 + len2);
3624 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3625 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3626 Fset_text_properties (make_number (start1), make_number (end2),
3627 Qnil, Qnil);
3629 /* First region smaller than second. */
3630 if (len1_byte < len2_byte)
3632 /* We use alloca only if it is small,
3633 because we want to avoid stack overflow. */
3634 if (len2_byte > 20000)
3635 temp = (unsigned char *) xmalloc (len2_byte);
3636 else
3637 temp = (unsigned char *) alloca (len2_byte);
3639 /* Don't precompute these addresses. We have to compute them
3640 at the last minute, because the relocating allocator might
3641 have moved the buffer around during the xmalloc. */
3642 start1_addr = BYTE_POS_ADDR (start1_byte);
3643 start2_addr = BYTE_POS_ADDR (start2_byte);
3645 bcopy (start2_addr, temp, len2_byte);
3646 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3647 bcopy (temp, start1_addr, len2_byte);
3648 if (len2_byte > 20000)
3649 xfree (temp);
3651 else
3652 /* First region not smaller than second. */
3654 if (len1_byte > 20000)
3655 temp = (unsigned char *) xmalloc (len1_byte);
3656 else
3657 temp = (unsigned char *) alloca (len1_byte);
3658 start1_addr = BYTE_POS_ADDR (start1_byte);
3659 start2_addr = BYTE_POS_ADDR (start2_byte);
3660 bcopy (start1_addr, temp, len1_byte);
3661 bcopy (start2_addr, start1_addr, len2_byte);
3662 bcopy (temp, start1_addr + len2_byte, len1_byte);
3663 if (len1_byte > 20000)
3664 xfree (temp);
3666 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3667 len1, current_buffer, 0);
3668 graft_intervals_into_buffer (tmp_interval2, start1,
3669 len2, current_buffer, 0);
3670 update_compositions (start1, start1 + len2, CHECK_BORDER);
3671 update_compositions (start1 + len2, end2, CHECK_TAIL);
3673 /* Non-adjacent regions, because end1 != start2, bleagh... */
3674 else
3676 len_mid = start2_byte - (start1_byte + len1_byte);
3678 if (len1_byte == len2_byte)
3679 /* Regions are same size, though, how nice. */
3681 modify_region (current_buffer, start1, end1);
3682 modify_region (current_buffer, start2, end2);
3683 record_change (start1, len1);
3684 record_change (start2, len2);
3685 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3686 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3687 Fset_text_properties (make_number (start1), make_number (end1),
3688 Qnil, Qnil);
3689 Fset_text_properties (make_number (start2), make_number (end2),
3690 Qnil, Qnil);
3692 if (len1_byte > 20000)
3693 temp = (unsigned char *) xmalloc (len1_byte);
3694 else
3695 temp = (unsigned char *) alloca (len1_byte);
3696 start1_addr = BYTE_POS_ADDR (start1_byte);
3697 start2_addr = BYTE_POS_ADDR (start2_byte);
3698 bcopy (start1_addr, temp, len1_byte);
3699 bcopy (start2_addr, start1_addr, len2_byte);
3700 bcopy (temp, start2_addr, len1_byte);
3701 if (len1_byte > 20000)
3702 xfree (temp);
3703 graft_intervals_into_buffer (tmp_interval1, start2,
3704 len1, current_buffer, 0);
3705 graft_intervals_into_buffer (tmp_interval2, start1,
3706 len2, current_buffer, 0);
3709 else if (len1_byte < len2_byte) /* Second region larger than first */
3710 /* Non-adjacent & unequal size, area between must also be shifted. */
3712 modify_region (current_buffer, start1, end2);
3713 record_change (start1, (end2 - start1));
3714 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3715 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3716 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3717 Fset_text_properties (make_number (start1), make_number (end2),
3718 Qnil, Qnil);
3720 /* holds region 2 */
3721 if (len2_byte > 20000)
3722 temp = (unsigned char *) xmalloc (len2_byte);
3723 else
3724 temp = (unsigned char *) alloca (len2_byte);
3725 start1_addr = BYTE_POS_ADDR (start1_byte);
3726 start2_addr = BYTE_POS_ADDR (start2_byte);
3727 bcopy (start2_addr, temp, len2_byte);
3728 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3729 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3730 bcopy (temp, start1_addr, len2_byte);
3731 if (len2_byte > 20000)
3732 xfree (temp);
3733 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3734 len1, current_buffer, 0);
3735 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3736 len_mid, current_buffer, 0);
3737 graft_intervals_into_buffer (tmp_interval2, start1,
3738 len2, current_buffer, 0);
3740 else
3741 /* Second region smaller than first. */
3743 record_change (start1, (end2 - start1));
3744 modify_region (current_buffer, start1, end2);
3746 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3747 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3748 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3749 Fset_text_properties (make_number (start1), make_number (end2),
3750 Qnil, Qnil);
3752 /* holds region 1 */
3753 if (len1_byte > 20000)
3754 temp = (unsigned char *) xmalloc (len1_byte);
3755 else
3756 temp = (unsigned char *) alloca (len1_byte);
3757 start1_addr = BYTE_POS_ADDR (start1_byte);
3758 start2_addr = BYTE_POS_ADDR (start2_byte);
3759 bcopy (start1_addr, temp, len1_byte);
3760 bcopy (start2_addr, start1_addr, len2_byte);
3761 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3762 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3763 if (len1_byte > 20000)
3764 xfree (temp);
3765 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3766 len1, current_buffer, 0);
3767 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3768 len_mid, current_buffer, 0);
3769 graft_intervals_into_buffer (tmp_interval2, start1,
3770 len2, current_buffer, 0);
3773 update_compositions (start1, start1 + len2, CHECK_BORDER);
3774 update_compositions (end2 - len1, end2, CHECK_BORDER);
3777 /* When doing multiple transpositions, it might be nice
3778 to optimize this. Perhaps the markers in any one buffer
3779 should be organized in some sorted data tree. */
3780 if (NILP (leave_markers))
3782 transpose_markers (start1, end1, start2, end2,
3783 start1_byte, start1_byte + len1_byte,
3784 start2_byte, start2_byte + len2_byte);
3785 fix_overlays_in_range (start1, end2);
3788 return Qnil;
3792 void
3793 syms_of_editfns ()
3795 environbuf = 0;
3797 Qbuffer_access_fontify_functions
3798 = intern ("buffer-access-fontify-functions");
3799 staticpro (&Qbuffer_access_fontify_functions);
3801 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
3802 "Non-nil means.text motion commands don't notice fields.");
3803 Vinhibit_field_text_motion = Qnil;
3805 DEFVAR_LISP ("buffer-access-fontify-functions",
3806 &Vbuffer_access_fontify_functions,
3807 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3808 Each function is called with two arguments which specify the range\n\
3809 of the buffer being accessed.");
3810 Vbuffer_access_fontify_functions = Qnil;
3813 Lisp_Object obuf;
3814 extern Lisp_Object Vprin1_to_string_buffer;
3815 obuf = Fcurrent_buffer ();
3816 /* Do this here, because init_buffer_once is too early--it won't work. */
3817 Fset_buffer (Vprin1_to_string_buffer);
3818 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3819 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3820 Qnil);
3821 Fset_buffer (obuf);
3824 DEFVAR_LISP ("buffer-access-fontified-property",
3825 &Vbuffer_access_fontified_property,
3826 "Property which (if non-nil) indicates text has been fontified.\n\
3827 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3828 functions if all the text being accessed has this property.");
3829 Vbuffer_access_fontified_property = Qnil;
3831 DEFVAR_LISP ("system-name", &Vsystem_name,
3832 "The name of the machine Emacs is running on.");
3834 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3835 "The full name of the user logged in.");
3837 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3838 "The user's name, taken from environment variables if possible.");
3840 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3841 "The user's name, based upon the real uid only.");
3843 defsubr (&Spropertize);
3844 defsubr (&Schar_equal);
3845 defsubr (&Sgoto_char);
3846 defsubr (&Sstring_to_char);
3847 defsubr (&Schar_to_string);
3848 defsubr (&Sbuffer_substring);
3849 defsubr (&Sbuffer_substring_no_properties);
3850 defsubr (&Sbuffer_string);
3852 defsubr (&Spoint_marker);
3853 defsubr (&Smark_marker);
3854 defsubr (&Spoint);
3855 defsubr (&Sregion_beginning);
3856 defsubr (&Sregion_end);
3858 staticpro (&Qfield);
3859 Qfield = intern ("field");
3860 staticpro (&Qboundary);
3861 Qboundary = intern ("boundary");
3862 defsubr (&Sfield_beginning);
3863 defsubr (&Sfield_end);
3864 defsubr (&Sfield_string);
3865 defsubr (&Sfield_string_no_properties);
3866 defsubr (&Sdelete_field);
3867 defsubr (&Sconstrain_to_field);
3869 defsubr (&Sline_beginning_position);
3870 defsubr (&Sline_end_position);
3872 /* defsubr (&Smark); */
3873 /* defsubr (&Sset_mark); */
3874 defsubr (&Ssave_excursion);
3875 defsubr (&Ssave_current_buffer);
3877 defsubr (&Sbufsize);
3878 defsubr (&Spoint_max);
3879 defsubr (&Spoint_min);
3880 defsubr (&Spoint_min_marker);
3881 defsubr (&Spoint_max_marker);
3882 defsubr (&Sgap_position);
3883 defsubr (&Sgap_size);
3884 defsubr (&Sposition_bytes);
3885 defsubr (&Sbyte_to_position);
3887 defsubr (&Sbobp);
3888 defsubr (&Seobp);
3889 defsubr (&Sbolp);
3890 defsubr (&Seolp);
3891 defsubr (&Sfollowing_char);
3892 defsubr (&Sprevious_char);
3893 defsubr (&Schar_after);
3894 defsubr (&Schar_before);
3895 defsubr (&Sinsert);
3896 defsubr (&Sinsert_before_markers);
3897 defsubr (&Sinsert_and_inherit);
3898 defsubr (&Sinsert_and_inherit_before_markers);
3899 defsubr (&Sinsert_char);
3901 defsubr (&Suser_login_name);
3902 defsubr (&Suser_real_login_name);
3903 defsubr (&Suser_uid);
3904 defsubr (&Suser_real_uid);
3905 defsubr (&Suser_full_name);
3906 defsubr (&Semacs_pid);
3907 defsubr (&Scurrent_time);
3908 defsubr (&Sformat_time_string);
3909 defsubr (&Sfloat_time);
3910 defsubr (&Sdecode_time);
3911 defsubr (&Sencode_time);
3912 defsubr (&Scurrent_time_string);
3913 defsubr (&Scurrent_time_zone);
3914 defsubr (&Sset_time_zone_rule);
3915 defsubr (&Ssystem_name);
3916 defsubr (&Smessage);
3917 defsubr (&Smessage_box);
3918 defsubr (&Smessage_or_box);
3919 defsubr (&Scurrent_message);
3920 defsubr (&Sformat);
3922 defsubr (&Sinsert_buffer_substring);
3923 defsubr (&Scompare_buffer_substrings);
3924 defsubr (&Ssubst_char_in_region);
3925 defsubr (&Stranslate_region);
3926 defsubr (&Sdelete_region);
3927 defsubr (&Sdelete_and_extract_region);
3928 defsubr (&Swiden);
3929 defsubr (&Snarrow_to_region);
3930 defsubr (&Ssave_restriction);
3931 defsubr (&Stranspose_regions);