Remove conditional compilation on USE_TEXT_PROPERTIES.
[bpt/emacs.git] / src / editfns.c
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
20
21
22 #include <config.h>
23 #include <sys/types.h>
24
25 #ifdef VMS
26 #include "vms-pwd.h"
27 #else
28 #include <pwd.h>
29 #endif
30
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #include "lisp.h"
36 #include "intervals.h"
37 #include "buffer.h"
38 #include "charset.h"
39 #include "coding.h"
40 #include "window.h"
41
42 #include "systime.h"
43
44 #define min(a, b) ((a) < (b) ? (a) : (b))
45 #define max(a, b) ((a) > (b) ? (a) : (b))
46
47 #ifndef NULL
48 #define NULL 0
49 #endif
50
51 extern char **environ;
52 extern Lisp_Object make_time ();
53 extern void insert_from_buffer ();
54 static int tm_diff ();
55 static void update_buffer_properties ();
56 size_t emacs_strftimeu ();
57 void set_time_zone_rule ();
58
59 Lisp_Object Vbuffer_access_fontify_functions;
60 Lisp_Object Qbuffer_access_fontify_functions;
61 Lisp_Object Vbuffer_access_fontified_property;
62
63 Lisp_Object Fuser_full_name ();
64
65 /* Some static data, and a function to initialize it for each run */
66
67 Lisp_Object Vsystem_name;
68 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
69 Lisp_Object Vuser_full_name; /* full name of current user */
70 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
71
72 void
73 init_editfns ()
74 {
75 char *user_name;
76 register unsigned char *p;
77 struct passwd *pw; /* password entry for the current user */
78 Lisp_Object tem;
79
80 /* Set up system_name even when dumping. */
81 init_system_name ();
82
83 #ifndef CANNOT_DUMP
84 /* Don't bother with this on initial start when just dumping out */
85 if (!initialized)
86 return;
87 #endif /* not CANNOT_DUMP */
88
89 pw = (struct passwd *) getpwuid (getuid ());
90 #ifdef MSDOS
91 /* We let the real user name default to "root" because that's quite
92 accurate on MSDOG and because it lets Emacs find the init file.
93 (The DVX libraries override the Djgpp libraries here.) */
94 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
95 #else
96 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
97 #endif
98
99 /* Get the effective user name, by consulting environment variables,
100 or the effective uid if those are unset. */
101 user_name = (char *) getenv ("LOGNAME");
102 if (!user_name)
103 #ifdef WINDOWSNT
104 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
105 #else /* WINDOWSNT */
106 user_name = (char *) getenv ("USER");
107 #endif /* WINDOWSNT */
108 if (!user_name)
109 {
110 pw = (struct passwd *) getpwuid (geteuid ());
111 user_name = (char *) (pw ? pw->pw_name : "unknown");
112 }
113 Vuser_login_name = build_string (user_name);
114
115 /* If the user name claimed in the environment vars differs from
116 the real uid, use the claimed name to find the full name. */
117 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
118 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
119 : Vuser_login_name);
120
121 p = (unsigned char *) getenv ("NAME");
122 if (p)
123 Vuser_full_name = build_string (p);
124 else if (NILP (Vuser_full_name))
125 Vuser_full_name = build_string ("unknown");
126 }
127 \f
128 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
129 "Convert arg CHAR to a string containing that character.")
130 (character)
131 Lisp_Object character;
132 {
133 int len;
134 unsigned char workbuf[4], *str;
135
136 CHECK_NUMBER (character, 0);
137
138 len = CHAR_STRING (XFASTINT (character), workbuf, str);
139 return make_string_from_bytes (str, 1, len);
140 }
141
142 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
143 "Convert arg STRING to a character, the first character of that string.\n\
144 A multibyte character is handled correctly.")
145 (string)
146 register Lisp_Object string;
147 {
148 register Lisp_Object val;
149 register struct Lisp_String *p;
150 CHECK_STRING (string, 0);
151 p = XSTRING (string);
152 if (p->size)
153 {
154 if (STRING_MULTIBYTE (string))
155 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
156 else
157 XSETFASTINT (val, p->data[0]);
158 }
159 else
160 XSETFASTINT (val, 0);
161 return val;
162 }
163 \f
164 static Lisp_Object
165 buildmark (charpos, bytepos)
166 int charpos, bytepos;
167 {
168 register Lisp_Object mark;
169 mark = Fmake_marker ();
170 set_marker_both (mark, Qnil, charpos, bytepos);
171 return mark;
172 }
173
174 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
175 "Return value of point, as an integer.\n\
176 Beginning of buffer is position (point-min)")
177 ()
178 {
179 Lisp_Object temp;
180 XSETFASTINT (temp, PT);
181 return temp;
182 }
183
184 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
185 "Return value of point, as a marker object.")
186 ()
187 {
188 return buildmark (PT, PT_BYTE);
189 }
190
191 int
192 clip_to_bounds (lower, num, upper)
193 int lower, num, upper;
194 {
195 if (num < lower)
196 return lower;
197 else if (num > upper)
198 return upper;
199 else
200 return num;
201 }
202
203 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
204 "Set point to POSITION, a number or marker.\n\
205 Beginning of buffer is position (point-min), end is (point-max).\n\
206 If the position is in the middle of a multibyte form,\n\
207 the actual point is set at the head of the multibyte form\n\
208 except in the case that `enable-multibyte-characters' is nil.")
209 (position)
210 register Lisp_Object position;
211 {
212 int pos;
213
214 if (MARKERP (position)
215 && current_buffer == XMARKER (position)->buffer)
216 {
217 pos = marker_position (position);
218 if (pos < BEGV)
219 SET_PT_BOTH (BEGV, BEGV_BYTE);
220 else if (pos > ZV)
221 SET_PT_BOTH (ZV, ZV_BYTE);
222 else
223 SET_PT_BOTH (pos, marker_byte_position (position));
224
225 return position;
226 }
227
228 CHECK_NUMBER_COERCE_MARKER (position, 0);
229
230 pos = clip_to_bounds (BEGV, XINT (position), ZV);
231 SET_PT (pos);
232 return position;
233 }
234
235 static Lisp_Object
236 region_limit (beginningp)
237 int beginningp;
238 {
239 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
240 register Lisp_Object m;
241 if (!NILP (Vtransient_mark_mode) && NILP (Vmark_even_if_inactive)
242 && NILP (current_buffer->mark_active))
243 Fsignal (Qmark_inactive, Qnil);
244 m = Fmarker_position (current_buffer->mark);
245 if (NILP (m)) error ("There is no region now");
246 if ((PT < XFASTINT (m)) == beginningp)
247 return (make_number (PT));
248 else
249 return (m);
250 }
251
252 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
253 "Return position of beginning of region, as an integer.")
254 ()
255 {
256 return (region_limit (1));
257 }
258
259 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
260 "Return position of end of region, as an integer.")
261 ()
262 {
263 return (region_limit (0));
264 }
265
266 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
267 "Return this buffer's mark, as a marker object.\n\
268 Watch out! Moving this marker changes the mark position.\n\
269 If you set the marker not to point anywhere, the buffer will have no mark.")
270 ()
271 {
272 return current_buffer->mark;
273 }
274 \f
275 /* Returns the position before POS in the current buffer. POS must not
276 be at the beginning of the buffer. */
277 static Lisp_Object
278 preceding_pos (int pos)
279 {
280 int pos_byte = CHAR_TO_BYTE (pos);
281
282 /* Decrement POS_BYTE (is all this cruft really necessary?). */
283 if (NILP (current_buffer->enable_multibyte_characters))
284 pos_byte--;
285 else
286 DEC_POS (pos_byte);
287
288 return make_number (BYTE_TO_CHAR (pos_byte));
289 }
290
291 /* Returns true if POS1 and POS2 have the same value for text property PROP. */
292 static int
293 text_property_eq (prop, pos1, pos2)
294 Lisp_Object prop;
295 Lisp_Object pos1, pos2;
296 {
297 Lisp_Object pval1, pval2;
298
299 pval1 = Fget_text_property (pos1, prop, Qnil);
300 pval2 = Fget_text_property (pos2, prop, Qnil);
301
302 return EQ (pval1, pval2);
303 }
304
305 /* Returns the direction that the text-property PROP would be inherited
306 by any new text inserted at POS: 1 if it would be inherited from POS,
307 -1 if it would be inherited from POS-1, and 0 if from neither. */
308 static int
309 text_property_stickiness (prop, pos)
310 Lisp_Object prop;
311 Lisp_Object pos;
312 {
313 Lisp_Object front_sticky;
314
315 if (PT > BEGV)
316 /* Consider previous position. */
317 {
318 Lisp_Object prev_pos, rear_non_sticky;
319
320 prev_pos = preceding_pos (pos);
321 rear_non_sticky = Fget_text_property (prev_pos, Qrear_nonsticky, Qnil);
322
323 if (EQ (rear_non_sticky, Qnil)
324 || (CONSP (rear_non_sticky)
325 && !Fmemq (prop, rear_non_sticky)))
326 /* PROP is not rear-non-sticky, and since this takes precedence over
327 any front-stickiness, that must be the answer. */
328 return -1;
329 }
330
331 /* Consider current position. */
332 front_sticky = Fget_text_property (pos, Qfront_sticky, Qnil);
333
334 if (EQ (front_sticky, Qt)
335 || (CONSP (front_sticky)
336 && Fmemq (prop, front_sticky)))
337 /* PROP is front-sticky. */
338 return 1;
339
340 /* PROP is not sticky at all. */
341 return 0;
342 }
343 \f
344 /* Name for the text property we use to distinguish fields. */
345 Lisp_Object Qfield;
346
347 /* Returns the field surrounding POS in *BEG and *END; an
348 `field' is a region of text with the same `field' property.
349 If POS is nil, the position of the current buffer's point is used.
350 If MERGE_AT_BOUNDARY is true, then if POS is at the very first
351 position of a field, then the beginning of the previous field
352 is returned instead of the beginning of POS's field (since the end of
353 a field is actually also the beginning of the next input
354 field, this behavior is sometimes useful). BEG or END may be 0, in
355 which case the corresponding value is not returned. */
356 void
357 find_field (pos, merge_at_boundary, beg, end)
358 Lisp_Object pos;
359 Lisp_Object merge_at_boundary;
360 int *beg, *end;
361 {
362 /* If POS is at the edge of a field, then -1 or 1 depending on
363 whether it should be considered as the beginning of the following
364 field, or the end of the previous field, respectively. If POS is
365 not at a field-boundary, then STICKINESS is 0. */
366 int stickiness = 0;
367
368 if (NILP (pos))
369 XSETFASTINT (pos, PT);
370 else
371 CHECK_NUMBER_COERCE_MARKER (pos, 0);
372
373 if (NILP (merge_at_boundary) && XFASTINT (pos) > BEGV)
374 /* See if we need to handle the case where POS is at beginning of a
375 field, which can also be interpreted as the end of the previous
376 field. We decide which one by seeing which field the `field'
377 property sticks to. The case where if MERGE_AT_BOUNDARY is
378 non-nil (see function comment) is actually the more natural one;
379 then we avoid treating the beginning of a field specially. */
380 {
381 /* First see if POS is actually *at* a boundary. */
382 Lisp_Object after_field, before_field;
383
384 after_field = Fget_text_property (pos, Qfield, Qnil);
385 before_field = Fget_text_property (preceding_pos (pos), Qfield, Qnil);
386
387 if (! EQ (after_field, before_field))
388 /* We are at a boundary, see which direction is inclusive. */
389 {
390 stickiness = text_property_stickiness (Qfield, pos);
391
392 if (stickiness == 0)
393 /* STICKINESS == 0 means that any inserted text will get a
394 `field' text-property of nil, so check to see if that
395 matches either of the adjacent characters (this being a
396 kind of `stickiness by default'). */
397 {
398 if (NILP (before_field))
399 stickiness = -1; /* Sticks to the left. */
400 else if (NILP (after_field))
401 stickiness = 1; /* Sticks to the right. */
402 }
403 }
404 }
405
406 if (beg)
407 {
408 if (stickiness > 0)
409 /* POS is at the edge of a field, and we should consider it as
410 the beginning of the following field. */
411 *beg = XFASTINT (pos);
412 else
413 /* Find the previous field boundary. */
414 {
415 Lisp_Object prev;
416 prev = Fprevious_single_property_change (pos, Qfield, Qnil, Qnil);
417 *beg = NILP(prev) ? BEGV : XFASTINT (prev);
418 }
419 }
420
421 if (end)
422 {
423 if (stickiness < 0)
424 /* POS is at the edge of a field, and we should consider it as
425 the end of the previous field. */
426 *end = XFASTINT (pos);
427 else
428 /* Find the next field boundary. */
429 {
430 Lisp_Object next;
431 next = Fnext_single_property_change (pos, Qfield, Qnil, Qnil);
432 *end = NILP(next) ? ZV : XFASTINT (next);
433 }
434 }
435 }
436 \f
437 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, "d",
438 "Delete the field surrounding POS.\n\
439 A field is a region of text with the same `field' property.\n\
440 If POS is nil, the position of the current buffer's point is used.")
441 (pos)
442 Lisp_Object pos;
443 {
444 int beg, end;
445 find_field (pos, Qnil, &beg, &end);
446 if (beg != end)
447 del_range (beg, end);
448 }
449
450 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
451 "Return the contents of the field surrounding POS as a string.\n\
452 A field is a region of text with the same `field' property.\n\
453 If POS is nil, the position of the current buffer's point is used.")
454 (pos)
455 Lisp_Object pos;
456 {
457 int beg, end;
458 find_field (pos, Qnil, &beg, &end);
459 return make_buffer_string (beg, end, 1);
460 }
461
462 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
463 "Return the contents of the field around POS, without text-properties.\n\
464 A field is a region of text with the same `field' property.\n\
465 If POS is nil, the position of the current buffer's point is used.")
466 (pos)
467 Lisp_Object pos;
468 {
469 int beg, end;
470 find_field (pos, Qnil, &beg, &end);
471 return make_buffer_string (beg, end, 0);
472 }
473
474 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
475 "Return the beginning of the field surrounding POS.\n\
476 A field is a region of text with the same `field' property.\n\
477 If POS is nil, the position of the current buffer's point is used.\n\
478 If ESCAPE-FROM-EDGE is non-nil and POS is already at beginning of an\n\
479 field, then the beginning of the *previous* field is returned.")
480 (pos, escape_from_edge)
481 Lisp_Object pos, escape_from_edge;
482 {
483 int beg;
484 find_field (pos, escape_from_edge, &beg, 0);
485 return make_number (beg);
486 }
487
488 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
489 "Return the end of the field surrounding POS.\n\
490 A field is a region of text with the same `field' property.\n\
491 If POS is nil, the position of the current buffer's point is used.\n\
492 If ESCAPE-FROM-EDGE is non-nil and POS is already at end of a field,\n\
493 then the end of the *following* field is returned.")
494 (pos, escape_from_edge)
495 Lisp_Object pos, escape_from_edge;
496 {
497 int end;
498 find_field (pos, escape_from_edge, 0, &end);
499 return make_number (end);
500 }
501
502 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 4, 0,
503 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
504 A field is a region of text with the same `field' property.\n\
505 If NEW-POS is nil, then the current point is used instead, and set to the\n\
506 constrained position if that is is different.\n\
507 \n\
508 If OLD-POS is at the boundary of two fields, then the allowable\n\
509 positions for NEW-POS depends on the value of the optional argument\n\
510 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
511 constrained to the field that has the same `field' text-property\n\
512 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
513 is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
514 fields.\n\
515 \n\
516 If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
517 NEW-POS would move it to a different line, NEW-POS is returned\n\
518 unconstrained. This useful for commands that move by line, like\n\
519 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
520 only in the case where they can still move to the right line.")
521 (new_pos, old_pos, escape_from_edge, only_in_line)
522 Lisp_Object new_pos, old_pos, escape_from_edge, only_in_line;
523 {
524 /* If non-zero, then the original point, before re-positioning. */
525 int orig_point = 0;
526
527 if (NILP (new_pos))
528 /* Use the current point, and afterwards, set it. */
529 {
530 orig_point = PT;
531 XSETFASTINT (new_pos, PT);
532 }
533
534 if (!EQ (new_pos, old_pos) && !text_property_eq (Qfield, new_pos, old_pos))
535 /* NEW_POS is not within the same field as OLD_POS; try to
536 move NEW_POS so that it is. */
537 {
538 int fwd;
539 Lisp_Object field_bound;
540
541 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
542 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
543
544 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
545
546 if (fwd)
547 field_bound = Ffield_end (old_pos, escape_from_edge);
548 else
549 field_bound = Ffield_beginning (old_pos, escape_from_edge);
550
551 if (/* If ONLY_IN_LINE is non-nil, we only constrain NEW_POS if doing
552 so would remain within the same line. */
553 NILP (only_in_line)
554 /* In that case, see if ESCAPE_FROM_EDGE caused FIELD_BOUND
555 to jump to the other side of NEW_POS, which would mean
556 that NEW_POS is already acceptable, and that we don't
557 have to do the line-check. */
558 || ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? !fwd : fwd)
559 /* If not, see if there's no newline intervening between
560 NEW_POS and FIELD_BOUND. */
561 || (find_before_next_newline (XFASTINT (new_pos),
562 XFASTINT (field_bound),
563 fwd ? -1 : 1)
564 == XFASTINT (field_bound)))
565 /* Constrain NEW_POS to FIELD_BOUND. */
566 new_pos = field_bound;
567
568 if (orig_point && XFASTINT (new_pos) != orig_point)
569 /* The NEW_POS argument was originally nil, so automatically set PT. */
570 SET_PT (XFASTINT (new_pos));
571 }
572
573 return new_pos;
574 }
575 \f
576 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
577 0, 1, 0,
578 "Return the character position of the first character on the current line.\n\
579 With argument N not nil or 1, move forward N - 1 lines first.\n\
580 If scan reaches end of buffer, return that position.\n\
581 This function does not move point.\n\n\
582 In the minibuffer, if point is not within the prompt,\n\
583 the return value is never within the prompt either.")
584
585 (n)
586 Lisp_Object n;
587 {
588 register int orig, orig_byte, end;
589
590 if (NILP (n))
591 XSETFASTINT (n, 1);
592 else
593 CHECK_NUMBER (n, 0);
594
595 orig = PT;
596 orig_byte = PT_BYTE;
597 Fforward_line (make_number (XINT (n) - 1));
598 end = PT;
599
600 SET_PT_BOTH (orig, orig_byte);
601
602 /* Return END constrained to the current input field. */
603 return Fconstrain_to_field (make_number (end), make_number (orig), Qnil, Qt);
604 }
605
606 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
607 0, 1, 0,
608 "Return the character position of the last character on the current line.\n\
609 With argument N not nil or 1, move forward N - 1 lines first.\n\
610 If scan reaches end of buffer, return that position.\n\
611 This function does not move point.")
612 (n)
613 Lisp_Object n;
614 {
615 int end_pos;
616 register int orig = PT;
617
618 if (NILP (n))
619 XSETFASTINT (n, 1);
620 else
621 CHECK_NUMBER (n, 0);
622
623 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
624
625 /* Return END_POS constrained to the current input field. */
626 return
627 Fconstrain_to_field (make_number (end_pos), make_number (orig), Qnil, Qt);
628 }
629 \f
630 Lisp_Object
631 save_excursion_save ()
632 {
633 register int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
634 == current_buffer);
635
636 return Fcons (Fpoint_marker (),
637 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
638 Fcons (visible ? Qt : Qnil,
639 current_buffer->mark_active)));
640 }
641
642 Lisp_Object
643 save_excursion_restore (info)
644 Lisp_Object info;
645 {
646 Lisp_Object tem, tem1, omark, nmark;
647 struct gcpro gcpro1, gcpro2, gcpro3;
648
649 tem = Fmarker_buffer (Fcar (info));
650 /* If buffer being returned to is now deleted, avoid error */
651 /* Otherwise could get error here while unwinding to top level
652 and crash */
653 /* In that case, Fmarker_buffer returns nil now. */
654 if (NILP (tem))
655 return Qnil;
656
657 omark = nmark = Qnil;
658 GCPRO3 (info, omark, nmark);
659
660 Fset_buffer (tem);
661 tem = Fcar (info);
662 Fgoto_char (tem);
663 unchain_marker (tem);
664 tem = Fcar (Fcdr (info));
665 omark = Fmarker_position (current_buffer->mark);
666 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
667 nmark = Fmarker_position (tem);
668 unchain_marker (tem);
669 tem = Fcdr (Fcdr (info));
670 #if 0 /* We used to make the current buffer visible in the selected window
671 if that was true previously. That avoids some anomalies.
672 But it creates others, and it wasn't documented, and it is simpler
673 and cleaner never to alter the window/buffer connections. */
674 tem1 = Fcar (tem);
675 if (!NILP (tem1)
676 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
677 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
678 #endif /* 0 */
679
680 tem1 = current_buffer->mark_active;
681 current_buffer->mark_active = Fcdr (tem);
682 if (!NILP (Vrun_hooks))
683 {
684 /* If mark is active now, and either was not active
685 or was at a different place, run the activate hook. */
686 if (! NILP (current_buffer->mark_active))
687 {
688 if (! EQ (omark, nmark))
689 call1 (Vrun_hooks, intern ("activate-mark-hook"));
690 }
691 /* If mark has ceased to be active, run deactivate hook. */
692 else if (! NILP (tem1))
693 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
694 }
695 UNGCPRO;
696 return Qnil;
697 }
698
699 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
700 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
701 Executes BODY just like `progn'.\n\
702 The values of point, mark and the current buffer are restored\n\
703 even in case of abnormal exit (throw or error).\n\
704 The state of activation of the mark is also restored.\n\
705 \n\
706 This construct does not save `deactivate-mark', and therefore\n\
707 functions that change the buffer will still cause deactivation\n\
708 of the mark at the end of the command. To prevent that, bind\n\
709 `deactivate-mark' with `let'.")
710 (args)
711 Lisp_Object args;
712 {
713 register Lisp_Object val;
714 int count = specpdl_ptr - specpdl;
715
716 record_unwind_protect (save_excursion_restore, save_excursion_save ());
717
718 val = Fprogn (args);
719 return unbind_to (count, val);
720 }
721
722 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
723 "Save the current buffer; execute BODY; restore the current buffer.\n\
724 Executes BODY just like `progn'.")
725 (args)
726 Lisp_Object args;
727 {
728 register Lisp_Object val;
729 int count = specpdl_ptr - specpdl;
730
731 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
732
733 val = Fprogn (args);
734 return unbind_to (count, val);
735 }
736 \f
737 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
738 "Return the number of characters in the current buffer.\n\
739 If BUFFER, return the number of characters in that buffer instead.")
740 (buffer)
741 Lisp_Object buffer;
742 {
743 if (NILP (buffer))
744 return make_number (Z - BEG);
745 else
746 {
747 CHECK_BUFFER (buffer, 1);
748 return make_number (BUF_Z (XBUFFER (buffer))
749 - BUF_BEG (XBUFFER (buffer)));
750 }
751 }
752
753 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
754 "Return the minimum permissible value of point in the current buffer.\n\
755 This is 1, unless narrowing (a buffer restriction) is in effect.")
756 ()
757 {
758 Lisp_Object temp;
759 XSETFASTINT (temp, BEGV);
760 return temp;
761 }
762
763 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
764 "Return a marker to the minimum permissible value of point in this buffer.\n\
765 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
766 ()
767 {
768 return buildmark (BEGV, BEGV_BYTE);
769 }
770
771 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
772 "Return the maximum permissible value of point in the current buffer.\n\
773 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
774 is in effect, in which case it is less.")
775 ()
776 {
777 Lisp_Object temp;
778 XSETFASTINT (temp, ZV);
779 return temp;
780 }
781
782 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
783 "Return a marker to the maximum permissible value of point in this buffer.\n\
784 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
785 is in effect, in which case it is less.")
786 ()
787 {
788 return buildmark (ZV, ZV_BYTE);
789 }
790
791 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
792 "Return the position of the gap, in the current buffer.\n\
793 See also `gap-size'.")
794 ()
795 {
796 Lisp_Object temp;
797 XSETFASTINT (temp, GPT);
798 return temp;
799 }
800
801 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
802 "Return the size of the current buffer's gap.\n\
803 See also `gap-position'.")
804 ()
805 {
806 Lisp_Object temp;
807 XSETFASTINT (temp, GAP_SIZE);
808 return temp;
809 }
810
811 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
812 "Return the byte position for character position POSITION.\n\
813 If POSITION is out of range, the value is nil.")
814 (position)
815 Lisp_Object position;
816 {
817 CHECK_NUMBER_COERCE_MARKER (position, 1);
818 if (XINT (position) < BEG || XINT (position) > Z)
819 return Qnil;
820 return make_number (CHAR_TO_BYTE (XINT (position)));
821 }
822
823 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
824 "Return the character position for byte position BYTEPOS.\n\
825 If BYTEPOS is out of range, the value is nil.")
826 (bytepos)
827 Lisp_Object bytepos;
828 {
829 CHECK_NUMBER (bytepos, 1);
830 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
831 return Qnil;
832 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
833 }
834 \f
835 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
836 "Return the character following point, as a number.\n\
837 At the end of the buffer or accessible region, return 0.\n\
838 If `enable-multibyte-characters' is nil or point is not\n\
839 at character boundary, multibyte form is ignored,\n\
840 and only one byte following point is returned as a character.")
841 ()
842 {
843 Lisp_Object temp;
844 if (PT >= ZV)
845 XSETFASTINT (temp, 0);
846 else
847 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
848 return temp;
849 }
850
851 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
852 "Return the character preceding point, as a number.\n\
853 At the beginning of the buffer or accessible region, return 0.\n\
854 If `enable-multibyte-characters' is nil or point is not\n\
855 at character boundary, multi-byte form is ignored,\n\
856 and only one byte preceding point is returned as a character.")
857 ()
858 {
859 Lisp_Object temp;
860 if (PT <= BEGV)
861 XSETFASTINT (temp, 0);
862 else if (!NILP (current_buffer->enable_multibyte_characters))
863 {
864 int pos = PT_BYTE;
865 DEC_POS (pos);
866 XSETFASTINT (temp, FETCH_CHAR (pos));
867 }
868 else
869 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
870 return temp;
871 }
872
873 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
874 "Return t if point is at the beginning of the buffer.\n\
875 If the buffer is narrowed, this means the beginning of the narrowed part.")
876 ()
877 {
878 if (PT == BEGV)
879 return Qt;
880 return Qnil;
881 }
882
883 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
884 "Return t if point is at the end of the buffer.\n\
885 If the buffer is narrowed, this means the end of the narrowed part.")
886 ()
887 {
888 if (PT == ZV)
889 return Qt;
890 return Qnil;
891 }
892
893 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
894 "Return t if point is at the beginning of a line.")
895 ()
896 {
897 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
898 return Qt;
899 return Qnil;
900 }
901
902 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
903 "Return t if point is at the end of a line.\n\
904 `End of a line' includes point being at the end of the buffer.")
905 ()
906 {
907 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
908 return Qt;
909 return Qnil;
910 }
911
912 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
913 "Return character in current buffer at position POS.\n\
914 POS is an integer or a buffer pointer.\n\
915 If POS is out of range, the value is nil.")
916 (pos)
917 Lisp_Object pos;
918 {
919 register int pos_byte;
920
921 if (NILP (pos))
922 {
923 pos_byte = PT_BYTE;
924 XSETFASTINT (pos, PT);
925 }
926
927 if (MARKERP (pos))
928 {
929 pos_byte = marker_byte_position (pos);
930 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
931 return Qnil;
932 }
933 else
934 {
935 CHECK_NUMBER_COERCE_MARKER (pos, 0);
936 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
937 return Qnil;
938
939 pos_byte = CHAR_TO_BYTE (XINT (pos));
940 }
941
942 return make_number (FETCH_CHAR (pos_byte));
943 }
944
945 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
946 "Return character in current buffer preceding position POS.\n\
947 POS is an integer or a buffer pointer.\n\
948 If POS is out of range, the value is nil.")
949 (pos)
950 Lisp_Object pos;
951 {
952 register Lisp_Object val;
953 register int pos_byte;
954
955 if (NILP (pos))
956 {
957 pos_byte = PT_BYTE;
958 XSETFASTINT (pos, PT);
959 }
960
961 if (MARKERP (pos))
962 {
963 pos_byte = marker_byte_position (pos);
964
965 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
966 return Qnil;
967 }
968 else
969 {
970 CHECK_NUMBER_COERCE_MARKER (pos, 0);
971
972 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
973 return Qnil;
974
975 pos_byte = CHAR_TO_BYTE (XINT (pos));
976 }
977
978 if (!NILP (current_buffer->enable_multibyte_characters))
979 {
980 DEC_POS (pos_byte);
981 XSETFASTINT (val, FETCH_CHAR (pos_byte));
982 }
983 else
984 {
985 pos_byte--;
986 XSETFASTINT (val, FETCH_BYTE (pos_byte));
987 }
988 return val;
989 }
990 \f
991 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
992 "Return the name under which the user logged in, as a string.\n\
993 This is based on the effective uid, not the real uid.\n\
994 Also, if the environment variable LOGNAME or USER is set,\n\
995 that determines the value of this function.\n\n\
996 If optional argument UID is an integer, return the login name of the user\n\
997 with that uid, or nil if there is no such user.")
998 (uid)
999 Lisp_Object uid;
1000 {
1001 struct passwd *pw;
1002
1003 /* Set up the user name info if we didn't do it before.
1004 (That can happen if Emacs is dumpable
1005 but you decide to run `temacs -l loadup' and not dump. */
1006 if (INTEGERP (Vuser_login_name))
1007 init_editfns ();
1008
1009 if (NILP (uid))
1010 return Vuser_login_name;
1011
1012 CHECK_NUMBER (uid, 0);
1013 pw = (struct passwd *) getpwuid (XINT (uid));
1014 return (pw ? build_string (pw->pw_name) : Qnil);
1015 }
1016
1017 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1018 0, 0, 0,
1019 "Return the name of the user's real uid, as a string.\n\
1020 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1021 `user-login-name' when running under `su'.")
1022 ()
1023 {
1024 /* Set up the user name info if we didn't do it before.
1025 (That can happen if Emacs is dumpable
1026 but you decide to run `temacs -l loadup' and not dump. */
1027 if (INTEGERP (Vuser_login_name))
1028 init_editfns ();
1029 return Vuser_real_login_name;
1030 }
1031
1032 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1033 "Return the effective uid of Emacs, as an integer.")
1034 ()
1035 {
1036 return make_number (geteuid ());
1037 }
1038
1039 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1040 "Return the real uid of Emacs, as an integer.")
1041 ()
1042 {
1043 return make_number (getuid ());
1044 }
1045
1046 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1047 "Return the full name of the user logged in, as a string.\n\
1048 If the full name corresponding to Emacs's userid is not known,\n\
1049 return \"unknown\".\n\
1050 \n\
1051 If optional argument UID is an integer, return the full name of the user\n\
1052 with that uid, or nil if there is no such user.\n\
1053 If UID is a string, return the full name of the user with that login\n\
1054 name, or nil if there is no such user.")
1055 (uid)
1056 Lisp_Object uid;
1057 {
1058 struct passwd *pw;
1059 register unsigned char *p, *q;
1060 extern char *index ();
1061 Lisp_Object full;
1062
1063 if (NILP (uid))
1064 return Vuser_full_name;
1065 else if (NUMBERP (uid))
1066 pw = (struct passwd *) getpwuid (XINT (uid));
1067 else if (STRINGP (uid))
1068 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1069 else
1070 error ("Invalid UID specification");
1071
1072 if (!pw)
1073 return Qnil;
1074
1075 p = (unsigned char *) USER_FULL_NAME;
1076 /* Chop off everything after the first comma. */
1077 q = (unsigned char *) index (p, ',');
1078 full = make_string (p, q ? q - p : strlen (p));
1079
1080 #ifdef AMPERSAND_FULL_NAME
1081 p = XSTRING (full)->data;
1082 q = (unsigned char *) index (p, '&');
1083 /* Substitute the login name for the &, upcasing the first character. */
1084 if (q)
1085 {
1086 register unsigned char *r;
1087 Lisp_Object login;
1088
1089 login = Fuser_login_name (make_number (pw->pw_uid));
1090 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1091 bcopy (p, r, q - p);
1092 r[q - p] = 0;
1093 strcat (r, XSTRING (login)->data);
1094 r[q - p] = UPCASE (r[q - p]);
1095 strcat (r, q + 1);
1096 full = build_string (r);
1097 }
1098 #endif /* AMPERSAND_FULL_NAME */
1099
1100 return full;
1101 }
1102
1103 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1104 "Return the name of the machine you are running on, as a string.")
1105 ()
1106 {
1107 return Vsystem_name;
1108 }
1109
1110 /* For the benefit of callers who don't want to include lisp.h */
1111 char *
1112 get_system_name ()
1113 {
1114 if (STRINGP (Vsystem_name))
1115 return (char *) XSTRING (Vsystem_name)->data;
1116 else
1117 return "";
1118 }
1119
1120 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1121 "Return the process ID of Emacs, as an integer.")
1122 ()
1123 {
1124 return make_number (getpid ());
1125 }
1126
1127 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1128 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1129 The time is returned as a list of three integers. The first has the\n\
1130 most significant 16 bits of the seconds, while the second has the\n\
1131 least significant 16 bits. The third integer gives the microsecond\n\
1132 count.\n\
1133 \n\
1134 The microsecond count is zero on systems that do not provide\n\
1135 resolution finer than a second.")
1136 ()
1137 {
1138 EMACS_TIME t;
1139 Lisp_Object result[3];
1140
1141 EMACS_GET_TIME (t);
1142 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1143 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1144 XSETINT (result[2], EMACS_USECS (t));
1145
1146 return Flist (3, result);
1147 }
1148 \f
1149
1150 static int
1151 lisp_time_argument (specified_time, result)
1152 Lisp_Object specified_time;
1153 time_t *result;
1154 {
1155 if (NILP (specified_time))
1156 return time (result) != -1;
1157 else
1158 {
1159 Lisp_Object high, low;
1160 high = Fcar (specified_time);
1161 CHECK_NUMBER (high, 0);
1162 low = Fcdr (specified_time);
1163 if (CONSP (low))
1164 low = Fcar (low);
1165 CHECK_NUMBER (low, 0);
1166 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1167 return *result >> 16 == XINT (high);
1168 }
1169 }
1170
1171 /* Write information into buffer S of size MAXSIZE, according to the
1172 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1173 Default to Universal Time if UT is nonzero, local time otherwise.
1174 Return the number of bytes written, not including the terminating
1175 '\0'. If S is NULL, nothing will be written anywhere; so to
1176 determine how many bytes would be written, use NULL for S and
1177 ((size_t) -1) for MAXSIZE.
1178
1179 This function behaves like emacs_strftimeu, except it allows null
1180 bytes in FORMAT. */
1181 static size_t
1182 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1183 char *s;
1184 size_t maxsize;
1185 const char *format;
1186 size_t format_len;
1187 const struct tm *tp;
1188 int ut;
1189 {
1190 size_t total = 0;
1191
1192 /* Loop through all the null-terminated strings in the format
1193 argument. Normally there's just one null-terminated string, but
1194 there can be arbitrarily many, concatenated together, if the
1195 format contains '\0' bytes. emacs_strftimeu stops at the first
1196 '\0' byte so we must invoke it separately for each such string. */
1197 for (;;)
1198 {
1199 size_t len;
1200 size_t result;
1201
1202 if (s)
1203 s[0] = '\1';
1204
1205 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1206
1207 if (s)
1208 {
1209 if (result == 0 && s[0] != '\0')
1210 return 0;
1211 s += result + 1;
1212 }
1213
1214 maxsize -= result + 1;
1215 total += result;
1216 len = strlen (format);
1217 if (len == format_len)
1218 return total;
1219 total++;
1220 format += len + 1;
1221 format_len -= len + 1;
1222 }
1223 }
1224
1225 /*
1226 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1227 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1228 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1229 `current-time' or `file-attributes'.\n\
1230 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1231 as Universal Time; nil means describe TIME in the local time zone.\n\
1232 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1233 by text that describes the specified date and time in TIME:\n\
1234 \n\
1235 %Y is the year, %y within the century, %C the century.\n\
1236 %G is the year corresponding to the ISO week, %g within the century.\n\
1237 %m is the numeric month.\n\
1238 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1239 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1240 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1241 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1242 %U is the week number starting on Sunday, %W starting on Monday,\n\
1243 %V according to ISO 8601.\n\
1244 %j is the day of the year.\n\
1245 \n\
1246 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1247 only blank-padded, %l is like %I blank-padded.\n\
1248 %p is the locale's equivalent of either AM or PM.\n\
1249 %M is the minute.\n\
1250 %S is the second.\n\
1251 %Z is the time zone name, %z is the numeric form.\n\
1252 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1253 \n\
1254 %c is the locale's date and time format.\n\
1255 %x is the locale's \"preferred\" date format.\n\
1256 %D is like \"%m/%d/%y\".\n\
1257 \n\
1258 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1259 %X is the locale's \"preferred\" time format.\n\
1260 \n\
1261 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1262 \n\
1263 Certain flags and modifiers are available with some format controls.\n\
1264 The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
1265 but padded with blanks; %-X is like %X, but without padding.\n\
1266 %NX (where N stands for an integer) is like %X,\n\
1267 but takes up at least N (a number) positions.\n\
1268 The modifiers are `E' and `O'. For certain characters X,\n\
1269 %EX is a locale's alternative version of %X;\n\
1270 %OX is like %X, but uses the locale's number symbols.\n\
1271 \n\
1272 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1273 (format_string, time, universal)
1274 */
1275
1276 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1277 0 /* See immediately above */)
1278 (format_string, time, universal)
1279 Lisp_Object format_string, time, universal;
1280 {
1281 time_t value;
1282 int size;
1283 struct tm *tm;
1284 int ut = ! NILP (universal);
1285
1286 CHECK_STRING (format_string, 1);
1287
1288 if (! lisp_time_argument (time, &value))
1289 error ("Invalid time specification");
1290
1291 format_string = code_convert_string_norecord (format_string,
1292 Vlocale_coding_system, 1);
1293
1294 /* This is probably enough. */
1295 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1296
1297 tm = ut ? gmtime (&value) : localtime (&value);
1298 if (! tm)
1299 error ("Specified time is not representable");
1300
1301 synchronize_time_locale ();
1302
1303 while (1)
1304 {
1305 char *buf = (char *) alloca (size + 1);
1306 int result;
1307
1308 buf[0] = '\1';
1309 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1310 STRING_BYTES (XSTRING (format_string)),
1311 tm, ut);
1312 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1313 return code_convert_string_norecord (make_string (buf, result),
1314 Vlocale_coding_system, 0);
1315
1316 /* If buffer was too small, make it bigger and try again. */
1317 result = emacs_memftimeu (NULL, (size_t) -1,
1318 XSTRING (format_string)->data,
1319 STRING_BYTES (XSTRING (format_string)),
1320 tm, ut);
1321 size = result + 1;
1322 }
1323 }
1324
1325 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1326 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1327 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1328 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1329 to use the current time. The list has the following nine members:\n\
1330 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1331 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1332 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1333 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1334 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1335 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1336 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1337 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1338 (specified_time)
1339 Lisp_Object specified_time;
1340 {
1341 time_t time_spec;
1342 struct tm save_tm;
1343 struct tm *decoded_time;
1344 Lisp_Object list_args[9];
1345
1346 if (! lisp_time_argument (specified_time, &time_spec))
1347 error ("Invalid time specification");
1348
1349 decoded_time = localtime (&time_spec);
1350 if (! decoded_time)
1351 error ("Specified time is not representable");
1352 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1353 XSETFASTINT (list_args[1], decoded_time->tm_min);
1354 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1355 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1356 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1357 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1358 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1359 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1360
1361 /* Make a copy, in case gmtime modifies the struct. */
1362 save_tm = *decoded_time;
1363 decoded_time = gmtime (&time_spec);
1364 if (decoded_time == 0)
1365 list_args[8] = Qnil;
1366 else
1367 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1368 return Flist (9, list_args);
1369 }
1370
1371 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1372 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1373 This is the reverse operation of `decode-time', which see.\n\
1374 ZONE defaults to the current time zone rule. This can\n\
1375 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1376 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1377 applied without consideration for daylight savings time.\n\
1378 \n\
1379 You can pass more than 7 arguments; then the first six arguments\n\
1380 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1381 The intervening arguments are ignored.\n\
1382 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1383 \n\
1384 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1385 for example, a DAY of 0 means the day preceding the given month.\n\
1386 Year numbers less than 100 are treated just like other year numbers.\n\
1387 If you want them to stand for years in this century, you must do that yourself.")
1388 (nargs, args)
1389 int nargs;
1390 register Lisp_Object *args;
1391 {
1392 time_t time;
1393 struct tm tm;
1394 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1395
1396 CHECK_NUMBER (args[0], 0); /* second */
1397 CHECK_NUMBER (args[1], 1); /* minute */
1398 CHECK_NUMBER (args[2], 2); /* hour */
1399 CHECK_NUMBER (args[3], 3); /* day */
1400 CHECK_NUMBER (args[4], 4); /* month */
1401 CHECK_NUMBER (args[5], 5); /* year */
1402
1403 tm.tm_sec = XINT (args[0]);
1404 tm.tm_min = XINT (args[1]);
1405 tm.tm_hour = XINT (args[2]);
1406 tm.tm_mday = XINT (args[3]);
1407 tm.tm_mon = XINT (args[4]) - 1;
1408 tm.tm_year = XINT (args[5]) - 1900;
1409 tm.tm_isdst = -1;
1410
1411 if (CONSP (zone))
1412 zone = Fcar (zone);
1413 if (NILP (zone))
1414 time = mktime (&tm);
1415 else
1416 {
1417 char tzbuf[100];
1418 char *tzstring;
1419 char **oldenv = environ, **newenv;
1420
1421 if (EQ (zone, Qt))
1422 tzstring = "UTC0";
1423 else if (STRINGP (zone))
1424 tzstring = (char *) XSTRING (zone)->data;
1425 else if (INTEGERP (zone))
1426 {
1427 int abszone = abs (XINT (zone));
1428 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1429 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1430 tzstring = tzbuf;
1431 }
1432 else
1433 error ("Invalid time zone specification");
1434
1435 /* Set TZ before calling mktime; merely adjusting mktime's returned
1436 value doesn't suffice, since that would mishandle leap seconds. */
1437 set_time_zone_rule (tzstring);
1438
1439 time = mktime (&tm);
1440
1441 /* Restore TZ to previous value. */
1442 newenv = environ;
1443 environ = oldenv;
1444 xfree (newenv);
1445 #ifdef LOCALTIME_CACHE
1446 tzset ();
1447 #endif
1448 }
1449
1450 if (time == (time_t) -1)
1451 error ("Specified time is not representable");
1452
1453 return make_time (time);
1454 }
1455
1456 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1457 "Return the current time, as a human-readable string.\n\
1458 Programs can use this function to decode a time,\n\
1459 since the number of columns in each field is fixed.\n\
1460 The format is `Sun Sep 16 01:03:52 1973'.\n\
1461 However, see also the functions `decode-time' and `format-time-string'\n\
1462 which provide a much more powerful and general facility.\n\
1463 \n\
1464 If an argument is given, it specifies a time to format\n\
1465 instead of the current time. The argument should have the form:\n\
1466 (HIGH . LOW)\n\
1467 or the form:\n\
1468 (HIGH LOW . IGNORED).\n\
1469 Thus, you can use times obtained from `current-time'\n\
1470 and from `file-attributes'.")
1471 (specified_time)
1472 Lisp_Object specified_time;
1473 {
1474 time_t value;
1475 char buf[30];
1476 register char *tem;
1477
1478 if (! lisp_time_argument (specified_time, &value))
1479 value = -1;
1480 tem = (char *) ctime (&value);
1481
1482 strncpy (buf, tem, 24);
1483 buf[24] = 0;
1484
1485 return build_string (buf);
1486 }
1487
1488 #define TM_YEAR_BASE 1900
1489
1490 /* Yield A - B, measured in seconds.
1491 This function is copied from the GNU C Library. */
1492 static int
1493 tm_diff (a, b)
1494 struct tm *a, *b;
1495 {
1496 /* Compute intervening leap days correctly even if year is negative.
1497 Take care to avoid int overflow in leap day calculations,
1498 but it's OK to assume that A and B are close to each other. */
1499 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1500 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1501 int a100 = a4 / 25 - (a4 % 25 < 0);
1502 int b100 = b4 / 25 - (b4 % 25 < 0);
1503 int a400 = a100 >> 2;
1504 int b400 = b100 >> 2;
1505 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1506 int years = a->tm_year - b->tm_year;
1507 int days = (365 * years + intervening_leap_days
1508 + (a->tm_yday - b->tm_yday));
1509 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1510 + (a->tm_min - b->tm_min))
1511 + (a->tm_sec - b->tm_sec));
1512 }
1513
1514 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1515 "Return the offset and name for the local time zone.\n\
1516 This returns a list of the form (OFFSET NAME).\n\
1517 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1518 A negative value means west of Greenwich.\n\
1519 NAME is a string giving the name of the time zone.\n\
1520 If an argument is given, it specifies when the time zone offset is determined\n\
1521 instead of using the current time. The argument should have the form:\n\
1522 (HIGH . LOW)\n\
1523 or the form:\n\
1524 (HIGH LOW . IGNORED).\n\
1525 Thus, you can use times obtained from `current-time'\n\
1526 and from `file-attributes'.\n\
1527 \n\
1528 Some operating systems cannot provide all this information to Emacs;\n\
1529 in this case, `current-time-zone' returns a list containing nil for\n\
1530 the data it can't find.")
1531 (specified_time)
1532 Lisp_Object specified_time;
1533 {
1534 time_t value;
1535 struct tm *t;
1536 struct tm gmt;
1537
1538 if (lisp_time_argument (specified_time, &value)
1539 && (t = gmtime (&value)) != 0
1540 && (gmt = *t, t = localtime (&value)) != 0)
1541 {
1542 int offset = tm_diff (t, &gmt);
1543 char *s = 0;
1544 char buf[6];
1545 #ifdef HAVE_TM_ZONE
1546 if (t->tm_zone)
1547 s = (char *)t->tm_zone;
1548 #else /* not HAVE_TM_ZONE */
1549 #ifdef HAVE_TZNAME
1550 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1551 s = tzname[t->tm_isdst];
1552 #endif
1553 #endif /* not HAVE_TM_ZONE */
1554 if (!s)
1555 {
1556 /* No local time zone name is available; use "+-NNNN" instead. */
1557 int am = (offset < 0 ? -offset : offset) / 60;
1558 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1559 s = buf;
1560 }
1561 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1562 }
1563 else
1564 return Fmake_list (make_number (2), Qnil);
1565 }
1566
1567 /* This holds the value of `environ' produced by the previous
1568 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1569 has never been called. */
1570 static char **environbuf;
1571
1572 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1573 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1574 If TZ is nil, use implementation-defined default time zone information.\n\
1575 If TZ is t, use Universal Time.")
1576 (tz)
1577 Lisp_Object tz;
1578 {
1579 char *tzstring;
1580
1581 if (NILP (tz))
1582 tzstring = 0;
1583 else if (EQ (tz, Qt))
1584 tzstring = "UTC0";
1585 else
1586 {
1587 CHECK_STRING (tz, 0);
1588 tzstring = (char *) XSTRING (tz)->data;
1589 }
1590
1591 set_time_zone_rule (tzstring);
1592 if (environbuf)
1593 free (environbuf);
1594 environbuf = environ;
1595
1596 return Qnil;
1597 }
1598
1599 #ifdef LOCALTIME_CACHE
1600
1601 /* These two values are known to load tz files in buggy implementations,
1602 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1603 Their values shouldn't matter in non-buggy implementations.
1604 We don't use string literals for these strings,
1605 since if a string in the environment is in readonly
1606 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1607 See Sun bugs 1113095 and 1114114, ``Timezone routines
1608 improperly modify environment''. */
1609
1610 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1611 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1612
1613 #endif
1614
1615 /* Set the local time zone rule to TZSTRING.
1616 This allocates memory into `environ', which it is the caller's
1617 responsibility to free. */
1618 void
1619 set_time_zone_rule (tzstring)
1620 char *tzstring;
1621 {
1622 int envptrs;
1623 char **from, **to, **newenv;
1624
1625 /* Make the ENVIRON vector longer with room for TZSTRING. */
1626 for (from = environ; *from; from++)
1627 continue;
1628 envptrs = from - environ + 2;
1629 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1630 + (tzstring ? strlen (tzstring) + 4 : 0));
1631
1632 /* Add TZSTRING to the end of environ, as a value for TZ. */
1633 if (tzstring)
1634 {
1635 char *t = (char *) (to + envptrs);
1636 strcpy (t, "TZ=");
1637 strcat (t, tzstring);
1638 *to++ = t;
1639 }
1640
1641 /* Copy the old environ vector elements into NEWENV,
1642 but don't copy the TZ variable.
1643 So we have only one definition of TZ, which came from TZSTRING. */
1644 for (from = environ; *from; from++)
1645 if (strncmp (*from, "TZ=", 3) != 0)
1646 *to++ = *from;
1647 *to = 0;
1648
1649 environ = newenv;
1650
1651 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1652 the TZ variable is stored. If we do not have a TZSTRING,
1653 TO points to the vector slot which has the terminating null. */
1654
1655 #ifdef LOCALTIME_CACHE
1656 {
1657 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1658 "US/Pacific" that loads a tz file, then changes to a value like
1659 "XXX0" that does not load a tz file, and then changes back to
1660 its original value, the last change is (incorrectly) ignored.
1661 Also, if TZ changes twice in succession to values that do
1662 not load a tz file, tzset can dump core (see Sun bug#1225179).
1663 The following code works around these bugs. */
1664
1665 if (tzstring)
1666 {
1667 /* Temporarily set TZ to a value that loads a tz file
1668 and that differs from tzstring. */
1669 char *tz = *newenv;
1670 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1671 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1672 tzset ();
1673 *newenv = tz;
1674 }
1675 else
1676 {
1677 /* The implied tzstring is unknown, so temporarily set TZ to
1678 two different values that each load a tz file. */
1679 *to = set_time_zone_rule_tz1;
1680 to[1] = 0;
1681 tzset ();
1682 *to = set_time_zone_rule_tz2;
1683 tzset ();
1684 *to = 0;
1685 }
1686
1687 /* Now TZ has the desired value, and tzset can be invoked safely. */
1688 }
1689
1690 tzset ();
1691 #endif
1692 }
1693 \f
1694 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1695 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1696 type of object is Lisp_String). INHERIT is passed to
1697 INSERT_FROM_STRING_FUNC as the last argument. */
1698
1699 void
1700 general_insert_function (insert_func, insert_from_string_func,
1701 inherit, nargs, args)
1702 void (*insert_func) P_ ((unsigned char *, int));
1703 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1704 int inherit, nargs;
1705 register Lisp_Object *args;
1706 {
1707 register int argnum;
1708 register Lisp_Object val;
1709
1710 for (argnum = 0; argnum < nargs; argnum++)
1711 {
1712 val = args[argnum];
1713 retry:
1714 if (INTEGERP (val))
1715 {
1716 unsigned char workbuf[4], *str;
1717 int len;
1718
1719 if (!NILP (current_buffer->enable_multibyte_characters))
1720 len = CHAR_STRING (XFASTINT (val), workbuf, str);
1721 else
1722 {
1723 workbuf[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1724 ? XINT (val)
1725 : multibyte_char_to_unibyte (XINT (val), Qnil));
1726 str = workbuf;
1727 len = 1;
1728 }
1729 (*insert_func) (str, len);
1730 }
1731 else if (STRINGP (val))
1732 {
1733 (*insert_from_string_func) (val, 0, 0,
1734 XSTRING (val)->size,
1735 STRING_BYTES (XSTRING (val)),
1736 inherit);
1737 }
1738 else
1739 {
1740 val = wrong_type_argument (Qchar_or_string_p, val);
1741 goto retry;
1742 }
1743 }
1744 }
1745
1746 void
1747 insert1 (arg)
1748 Lisp_Object arg;
1749 {
1750 Finsert (1, &arg);
1751 }
1752
1753
1754 /* Callers passing one argument to Finsert need not gcpro the
1755 argument "array", since the only element of the array will
1756 not be used after calling insert or insert_from_string, so
1757 we don't care if it gets trashed. */
1758
1759 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1760 "Insert the arguments, either strings or characters, at point.\n\
1761 Point and before-insertion markers move forward to end up\n\
1762 after the inserted text.\n\
1763 Any other markers at the point of insertion remain before the text.\n\
1764 \n\
1765 If the current buffer is multibyte, unibyte strings are converted\n\
1766 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1767 If the current buffer is unibyte, multibyte strings are converted\n\
1768 to unibyte for insertion.")
1769 (nargs, args)
1770 int nargs;
1771 register Lisp_Object *args;
1772 {
1773 general_insert_function (insert, insert_from_string, 0, nargs, args);
1774 return Qnil;
1775 }
1776
1777 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1778 0, MANY, 0,
1779 "Insert the arguments at point, inheriting properties from adjoining text.\n\
1780 Point and before-insertion markers move forward to end up\n\
1781 after the inserted text.\n\
1782 Any other markers at the point of insertion remain before the text.\n\
1783 \n\
1784 If the current buffer is multibyte, unibyte strings are converted\n\
1785 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1786 If the current buffer is unibyte, multibyte strings are converted\n\
1787 to unibyte for insertion.")
1788 (nargs, args)
1789 int nargs;
1790 register Lisp_Object *args;
1791 {
1792 general_insert_function (insert_and_inherit, insert_from_string, 1,
1793 nargs, args);
1794 return Qnil;
1795 }
1796
1797 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1798 "Insert strings or characters at point, relocating markers after the text.\n\
1799 Point and markers move forward to end up after the inserted text.\n\
1800 \n\
1801 If the current buffer is multibyte, unibyte strings are converted\n\
1802 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1803 If the current buffer is unibyte, multibyte strings are converted\n\
1804 to unibyte for insertion.")
1805 (nargs, args)
1806 int nargs;
1807 register Lisp_Object *args;
1808 {
1809 general_insert_function (insert_before_markers,
1810 insert_from_string_before_markers, 0,
1811 nargs, args);
1812 return Qnil;
1813 }
1814
1815 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1816 Sinsert_and_inherit_before_markers, 0, MANY, 0,
1817 "Insert text at point, relocating markers and inheriting properties.\n\
1818 Point and markers move forward to end up after the inserted text.\n\
1819 \n\
1820 If the current buffer is multibyte, unibyte strings are converted\n\
1821 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1822 If the current buffer is unibyte, multibyte strings are converted\n\
1823 to unibyte for insertion.")
1824 (nargs, args)
1825 int nargs;
1826 register Lisp_Object *args;
1827 {
1828 general_insert_function (insert_before_markers_and_inherit,
1829 insert_from_string_before_markers, 1,
1830 nargs, args);
1831 return Qnil;
1832 }
1833 \f
1834 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
1835 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
1836 Both arguments are required.\n\
1837 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
1838 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1839 from adjoining text, if those properties are sticky.")
1840 (character, count, inherit)
1841 Lisp_Object character, count, inherit;
1842 {
1843 register unsigned char *string;
1844 register int strlen;
1845 register int i, n;
1846 int len;
1847 unsigned char workbuf[4], *str;
1848
1849 CHECK_NUMBER (character, 0);
1850 CHECK_NUMBER (count, 1);
1851
1852 if (!NILP (current_buffer->enable_multibyte_characters))
1853 len = CHAR_STRING (XFASTINT (character), workbuf, str);
1854 else
1855 workbuf[0] = XFASTINT (character), str = workbuf, len = 1;
1856 n = XINT (count) * len;
1857 if (n <= 0)
1858 return Qnil;
1859 strlen = min (n, 256 * len);
1860 string = (unsigned char *) alloca (strlen);
1861 for (i = 0; i < strlen; i++)
1862 string[i] = str[i % len];
1863 while (n >= strlen)
1864 {
1865 QUIT;
1866 if (!NILP (inherit))
1867 insert_and_inherit (string, strlen);
1868 else
1869 insert (string, strlen);
1870 n -= strlen;
1871 }
1872 if (n > 0)
1873 {
1874 if (!NILP (inherit))
1875 insert_and_inherit (string, n);
1876 else
1877 insert (string, n);
1878 }
1879 return Qnil;
1880 }
1881
1882 \f
1883 /* Making strings from buffer contents. */
1884
1885 /* Return a Lisp_String containing the text of the current buffer from
1886 START to END. If text properties are in use and the current buffer
1887 has properties in the range specified, the resulting string will also
1888 have them, if PROPS is nonzero.
1889
1890 We don't want to use plain old make_string here, because it calls
1891 make_uninit_string, which can cause the buffer arena to be
1892 compacted. make_string has no way of knowing that the data has
1893 been moved, and thus copies the wrong data into the string. This
1894 doesn't effect most of the other users of make_string, so it should
1895 be left as is. But we should use this function when conjuring
1896 buffer substrings. */
1897
1898 Lisp_Object
1899 make_buffer_string (start, end, props)
1900 int start, end;
1901 int props;
1902 {
1903 int start_byte = CHAR_TO_BYTE (start);
1904 int end_byte = CHAR_TO_BYTE (end);
1905
1906 return make_buffer_string_both (start, start_byte, end, end_byte, props);
1907 }
1908
1909 /* Return a Lisp_String containing the text of the current buffer from
1910 START / START_BYTE to END / END_BYTE.
1911
1912 If text properties are in use and the current buffer
1913 has properties in the range specified, the resulting string will also
1914 have them, if PROPS is nonzero.
1915
1916 We don't want to use plain old make_string here, because it calls
1917 make_uninit_string, which can cause the buffer arena to be
1918 compacted. make_string has no way of knowing that the data has
1919 been moved, and thus copies the wrong data into the string. This
1920 doesn't effect most of the other users of make_string, so it should
1921 be left as is. But we should use this function when conjuring
1922 buffer substrings. */
1923
1924 Lisp_Object
1925 make_buffer_string_both (start, start_byte, end, end_byte, props)
1926 int start, start_byte, end, end_byte;
1927 int props;
1928 {
1929 Lisp_Object result, tem, tem1;
1930
1931 if (start < GPT && GPT < end)
1932 move_gap (start);
1933
1934 if (! NILP (current_buffer->enable_multibyte_characters))
1935 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
1936 else
1937 result = make_uninit_string (end - start);
1938 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
1939 end_byte - start_byte);
1940
1941 /* If desired, update and copy the text properties. */
1942 if (props)
1943 {
1944 update_buffer_properties (start, end);
1945
1946 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
1947 tem1 = Ftext_properties_at (make_number (start), Qnil);
1948
1949 if (XINT (tem) != end || !NILP (tem1))
1950 copy_intervals_to_string (result, current_buffer, start,
1951 end - start);
1952 }
1953
1954 return result;
1955 }
1956
1957 /* Call Vbuffer_access_fontify_functions for the range START ... END
1958 in the current buffer, if necessary. */
1959
1960 static void
1961 update_buffer_properties (start, end)
1962 int start, end;
1963 {
1964 /* If this buffer has some access functions,
1965 call them, specifying the range of the buffer being accessed. */
1966 if (!NILP (Vbuffer_access_fontify_functions))
1967 {
1968 Lisp_Object args[3];
1969 Lisp_Object tem;
1970
1971 args[0] = Qbuffer_access_fontify_functions;
1972 XSETINT (args[1], start);
1973 XSETINT (args[2], end);
1974
1975 /* But don't call them if we can tell that the work
1976 has already been done. */
1977 if (!NILP (Vbuffer_access_fontified_property))
1978 {
1979 tem = Ftext_property_any (args[1], args[2],
1980 Vbuffer_access_fontified_property,
1981 Qnil, Qnil);
1982 if (! NILP (tem))
1983 Frun_hook_with_args (3, args);
1984 }
1985 else
1986 Frun_hook_with_args (3, args);
1987 }
1988 }
1989
1990 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
1991 "Return the contents of part of the current buffer as a string.\n\
1992 The two arguments START and END are character positions;\n\
1993 they can be in either order.\n\
1994 The string returned is multibyte if the buffer is multibyte.")
1995 (start, end)
1996 Lisp_Object start, end;
1997 {
1998 register int b, e;
1999
2000 validate_region (&start, &end);
2001 b = XINT (start);
2002 e = XINT (end);
2003
2004 return make_buffer_string (b, e, 1);
2005 }
2006
2007 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2008 Sbuffer_substring_no_properties, 2, 2, 0,
2009 "Return the characters of part of the buffer, without the text properties.\n\
2010 The two arguments START and END are character positions;\n\
2011 they can be in either order.")
2012 (start, end)
2013 Lisp_Object start, end;
2014 {
2015 register int b, e;
2016
2017 validate_region (&start, &end);
2018 b = XINT (start);
2019 e = XINT (end);
2020
2021 return make_buffer_string (b, e, 0);
2022 }
2023
2024 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2025 "Return the contents of the current buffer as a string.\n\
2026 If narrowing is in effect, this function returns only the visible part\n\
2027 of the buffer. If in a mini-buffer, don't include the prompt in the\n\
2028 string returned.")
2029 ()
2030 {
2031 return make_buffer_string (BEGV, ZV, 1);
2032 }
2033
2034 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2035 1, 3, 0,
2036 "Insert before point a substring of the contents of buffer BUFFER.\n\
2037 BUFFER may be a buffer or a buffer name.\n\
2038 Arguments START and END are character numbers specifying the substring.\n\
2039 They default to the beginning and the end of BUFFER.")
2040 (buf, start, end)
2041 Lisp_Object buf, start, end;
2042 {
2043 register int b, e, temp;
2044 register struct buffer *bp, *obuf;
2045 Lisp_Object buffer;
2046
2047 buffer = Fget_buffer (buf);
2048 if (NILP (buffer))
2049 nsberror (buf);
2050 bp = XBUFFER (buffer);
2051 if (NILP (bp->name))
2052 error ("Selecting deleted buffer");
2053
2054 if (NILP (start))
2055 b = BUF_BEGV (bp);
2056 else
2057 {
2058 CHECK_NUMBER_COERCE_MARKER (start, 0);
2059 b = XINT (start);
2060 }
2061 if (NILP (end))
2062 e = BUF_ZV (bp);
2063 else
2064 {
2065 CHECK_NUMBER_COERCE_MARKER (end, 1);
2066 e = XINT (end);
2067 }
2068
2069 if (b > e)
2070 temp = b, b = e, e = temp;
2071
2072 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2073 args_out_of_range (start, end);
2074
2075 obuf = current_buffer;
2076 set_buffer_internal_1 (bp);
2077 update_buffer_properties (b, e);
2078 set_buffer_internal_1 (obuf);
2079
2080 insert_from_buffer (bp, b, e - b, 0);
2081 return Qnil;
2082 }
2083
2084 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2085 6, 6, 0,
2086 "Compare two substrings of two buffers; return result as number.\n\
2087 the value is -N if first string is less after N-1 chars,\n\
2088 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2089 Each substring is represented as three arguments: BUFFER, START and END.\n\
2090 That makes six args in all, three for each substring.\n\n\
2091 The value of `case-fold-search' in the current buffer\n\
2092 determines whether case is significant or ignored.")
2093 (buffer1, start1, end1, buffer2, start2, end2)
2094 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2095 {
2096 register int begp1, endp1, begp2, endp2, temp;
2097 register struct buffer *bp1, *bp2;
2098 register Lisp_Object *trt
2099 = (!NILP (current_buffer->case_fold_search)
2100 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2101 int chars = 0;
2102 int i1, i2, i1_byte, i2_byte;
2103
2104 /* Find the first buffer and its substring. */
2105
2106 if (NILP (buffer1))
2107 bp1 = current_buffer;
2108 else
2109 {
2110 Lisp_Object buf1;
2111 buf1 = Fget_buffer (buffer1);
2112 if (NILP (buf1))
2113 nsberror (buffer1);
2114 bp1 = XBUFFER (buf1);
2115 if (NILP (bp1->name))
2116 error ("Selecting deleted buffer");
2117 }
2118
2119 if (NILP (start1))
2120 begp1 = BUF_BEGV (bp1);
2121 else
2122 {
2123 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2124 begp1 = XINT (start1);
2125 }
2126 if (NILP (end1))
2127 endp1 = BUF_ZV (bp1);
2128 else
2129 {
2130 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2131 endp1 = XINT (end1);
2132 }
2133
2134 if (begp1 > endp1)
2135 temp = begp1, begp1 = endp1, endp1 = temp;
2136
2137 if (!(BUF_BEGV (bp1) <= begp1
2138 && begp1 <= endp1
2139 && endp1 <= BUF_ZV (bp1)))
2140 args_out_of_range (start1, end1);
2141
2142 /* Likewise for second substring. */
2143
2144 if (NILP (buffer2))
2145 bp2 = current_buffer;
2146 else
2147 {
2148 Lisp_Object buf2;
2149 buf2 = Fget_buffer (buffer2);
2150 if (NILP (buf2))
2151 nsberror (buffer2);
2152 bp2 = XBUFFER (buf2);
2153 if (NILP (bp2->name))
2154 error ("Selecting deleted buffer");
2155 }
2156
2157 if (NILP (start2))
2158 begp2 = BUF_BEGV (bp2);
2159 else
2160 {
2161 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2162 begp2 = XINT (start2);
2163 }
2164 if (NILP (end2))
2165 endp2 = BUF_ZV (bp2);
2166 else
2167 {
2168 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2169 endp2 = XINT (end2);
2170 }
2171
2172 if (begp2 > endp2)
2173 temp = begp2, begp2 = endp2, endp2 = temp;
2174
2175 if (!(BUF_BEGV (bp2) <= begp2
2176 && begp2 <= endp2
2177 && endp2 <= BUF_ZV (bp2)))
2178 args_out_of_range (start2, end2);
2179
2180 i1 = begp1;
2181 i2 = begp2;
2182 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2183 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2184
2185 while (i1 < endp1 && i2 < endp2)
2186 {
2187 /* When we find a mismatch, we must compare the
2188 characters, not just the bytes. */
2189 int c1, c2;
2190
2191 if (! NILP (bp1->enable_multibyte_characters))
2192 {
2193 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2194 BUF_INC_POS (bp1, i1_byte);
2195 i1++;
2196 }
2197 else
2198 {
2199 c1 = BUF_FETCH_BYTE (bp1, i1);
2200 c1 = unibyte_char_to_multibyte (c1);
2201 i1++;
2202 }
2203
2204 if (! NILP (bp2->enable_multibyte_characters))
2205 {
2206 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2207 BUF_INC_POS (bp2, i2_byte);
2208 i2++;
2209 }
2210 else
2211 {
2212 c2 = BUF_FETCH_BYTE (bp2, i2);
2213 c2 = unibyte_char_to_multibyte (c2);
2214 i2++;
2215 }
2216
2217 if (trt)
2218 {
2219 c1 = XINT (trt[c1]);
2220 c2 = XINT (trt[c2]);
2221 }
2222 if (c1 < c2)
2223 return make_number (- 1 - chars);
2224 if (c1 > c2)
2225 return make_number (chars + 1);
2226
2227 chars++;
2228 }
2229
2230 /* The strings match as far as they go.
2231 If one is shorter, that one is less. */
2232 if (chars < endp1 - begp1)
2233 return make_number (chars + 1);
2234 else if (chars < endp2 - begp2)
2235 return make_number (- chars - 1);
2236
2237 /* Same length too => they are equal. */
2238 return make_number (0);
2239 }
2240 \f
2241 static Lisp_Object
2242 subst_char_in_region_unwind (arg)
2243 Lisp_Object arg;
2244 {
2245 return current_buffer->undo_list = arg;
2246 }
2247
2248 static Lisp_Object
2249 subst_char_in_region_unwind_1 (arg)
2250 Lisp_Object arg;
2251 {
2252 return current_buffer->filename = arg;
2253 }
2254
2255 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2256 Ssubst_char_in_region, 4, 5, 0,
2257 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2258 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2259 and don't mark the buffer as really changed.\n\
2260 Both characters must have the same length of multi-byte form.")
2261 (start, end, fromchar, tochar, noundo)
2262 Lisp_Object start, end, fromchar, tochar, noundo;
2263 {
2264 register int pos, pos_byte, stop, i, len, end_byte;
2265 int changed = 0;
2266 unsigned char fromwork[4], *fromstr, towork[4], *tostr, *p;
2267 int count = specpdl_ptr - specpdl;
2268 #define COMBINING_NO 0
2269 #define COMBINING_BEFORE 1
2270 #define COMBINING_AFTER 2
2271 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2272 int maybe_byte_combining = COMBINING_NO;
2273
2274 validate_region (&start, &end);
2275 CHECK_NUMBER (fromchar, 2);
2276 CHECK_NUMBER (tochar, 3);
2277
2278 if (! NILP (current_buffer->enable_multibyte_characters))
2279 {
2280 len = CHAR_STRING (XFASTINT (fromchar), fromwork, fromstr);
2281 if (CHAR_STRING (XFASTINT (tochar), towork, tostr) != len)
2282 error ("Characters in subst-char-in-region have different byte-lengths");
2283 if (!ASCII_BYTE_P (*tostr))
2284 {
2285 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2286 complete multibyte character, it may be combined with the
2287 after bytes. If it is in the range 0xA0..0xFF, it may be
2288 combined with the before and after bytes. */
2289 if (!CHAR_HEAD_P (*tostr))
2290 maybe_byte_combining = COMBINING_BOTH;
2291 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2292 maybe_byte_combining = COMBINING_AFTER;
2293 }
2294 }
2295 else
2296 {
2297 len = 1;
2298 fromwork[0] = XFASTINT (fromchar), fromstr = fromwork;
2299 towork[0] = XFASTINT (tochar), tostr = towork;
2300 }
2301
2302 pos = XINT (start);
2303 pos_byte = CHAR_TO_BYTE (pos);
2304 stop = CHAR_TO_BYTE (XINT (end));
2305 end_byte = stop;
2306
2307 /* If we don't want undo, turn off putting stuff on the list.
2308 That's faster than getting rid of things,
2309 and it prevents even the entry for a first change.
2310 Also inhibit locking the file. */
2311 if (!NILP (noundo))
2312 {
2313 record_unwind_protect (subst_char_in_region_unwind,
2314 current_buffer->undo_list);
2315 current_buffer->undo_list = Qt;
2316 /* Don't do file-locking. */
2317 record_unwind_protect (subst_char_in_region_unwind_1,
2318 current_buffer->filename);
2319 current_buffer->filename = Qnil;
2320 }
2321
2322 if (pos_byte < GPT_BYTE)
2323 stop = min (stop, GPT_BYTE);
2324 while (1)
2325 {
2326 int pos_byte_next = pos_byte;
2327
2328 if (pos_byte >= stop)
2329 {
2330 if (pos_byte >= end_byte) break;
2331 stop = end_byte;
2332 }
2333 p = BYTE_POS_ADDR (pos_byte);
2334 INC_POS (pos_byte_next);
2335 if (pos_byte_next - pos_byte == len
2336 && p[0] == fromstr[0]
2337 && (len == 1
2338 || (p[1] == fromstr[1]
2339 && (len == 2 || (p[2] == fromstr[2]
2340 && (len == 3 || p[3] == fromstr[3]))))))
2341 {
2342 if (! changed)
2343 {
2344 modify_region (current_buffer, XINT (start), XINT (end));
2345
2346 if (! NILP (noundo))
2347 {
2348 if (MODIFF - 1 == SAVE_MODIFF)
2349 SAVE_MODIFF++;
2350 if (MODIFF - 1 == current_buffer->auto_save_modified)
2351 current_buffer->auto_save_modified++;
2352 }
2353
2354 changed = 1;
2355 }
2356
2357 /* Take care of the case where the new character
2358 combines with neighboring bytes. */
2359 if (maybe_byte_combining
2360 && (maybe_byte_combining == COMBINING_AFTER
2361 ? (pos_byte_next < Z_BYTE
2362 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2363 : ((pos_byte_next < Z_BYTE
2364 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2365 || (pos_byte > BEG_BYTE
2366 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2367 {
2368 Lisp_Object tem, string;
2369
2370 struct gcpro gcpro1;
2371
2372 tem = current_buffer->undo_list;
2373 GCPRO1 (tem);
2374
2375 /* Make a multibyte string containing this single character. */
2376 string = make_multibyte_string (tostr, 1, len);
2377 /* replace_range is less efficient, because it moves the gap,
2378 but it handles combining correctly. */
2379 replace_range (pos, pos + 1, string,
2380 0, 0, 1);
2381 pos_byte_next = CHAR_TO_BYTE (pos);
2382 if (pos_byte_next > pos_byte)
2383 /* Before combining happened. We should not increment
2384 POS. So, to cancel the later increment of POS,
2385 decrease it now. */
2386 pos--;
2387 else
2388 INC_POS (pos_byte_next);
2389
2390 if (! NILP (noundo))
2391 current_buffer->undo_list = tem;
2392
2393 UNGCPRO;
2394 }
2395 else
2396 {
2397 if (NILP (noundo))
2398 record_change (pos, 1);
2399 for (i = 0; i < len; i++) *p++ = tostr[i];
2400 }
2401 }
2402 pos_byte = pos_byte_next;
2403 pos++;
2404 }
2405
2406 if (changed)
2407 signal_after_change (XINT (start),
2408 XINT (end) - XINT (start), XINT (end) - XINT (start));
2409
2410 unbind_to (count, Qnil);
2411 return Qnil;
2412 }
2413
2414 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2415 "From START to END, translate characters according to TABLE.\n\
2416 TABLE is a string; the Nth character in it is the mapping\n\
2417 for the character with code N.\n\
2418 This function does not alter multibyte characters.\n\
2419 It returns the number of characters changed.")
2420 (start, end, table)
2421 Lisp_Object start;
2422 Lisp_Object end;
2423 register Lisp_Object table;
2424 {
2425 register int pos_byte, stop; /* Limits of the region. */
2426 register unsigned char *tt; /* Trans table. */
2427 register int nc; /* New character. */
2428 int cnt; /* Number of changes made. */
2429 int size; /* Size of translate table. */
2430 int pos;
2431
2432 validate_region (&start, &end);
2433 CHECK_STRING (table, 2);
2434
2435 size = STRING_BYTES (XSTRING (table));
2436 tt = XSTRING (table)->data;
2437
2438 pos_byte = CHAR_TO_BYTE (XINT (start));
2439 stop = CHAR_TO_BYTE (XINT (end));
2440 modify_region (current_buffer, XINT (start), XINT (end));
2441 pos = XINT (start);
2442
2443 cnt = 0;
2444 for (; pos_byte < stop; )
2445 {
2446 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2447 int len;
2448 int oc;
2449 int pos_byte_next;
2450
2451 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2452 pos_byte_next = pos_byte + len;
2453 if (oc < size && len == 1)
2454 {
2455 nc = tt[oc];
2456 if (nc != oc)
2457 {
2458 /* Take care of the case where the new character
2459 combines with neighboring bytes. */
2460 if (!ASCII_BYTE_P (nc)
2461 && (CHAR_HEAD_P (nc)
2462 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2463 : (pos_byte > BEG_BYTE
2464 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2465 {
2466 Lisp_Object string;
2467
2468 string = make_multibyte_string (tt + oc, 1, 1);
2469 /* This is less efficient, because it moves the gap,
2470 but it handles combining correctly. */
2471 replace_range (pos, pos + 1, string,
2472 1, 0, 1);
2473 pos_byte_next = CHAR_TO_BYTE (pos);
2474 if (pos_byte_next > pos_byte)
2475 /* Before combining happened. We should not
2476 increment POS. So, to cancel the later
2477 increment of POS, we decrease it now. */
2478 pos--;
2479 else
2480 INC_POS (pos_byte_next);
2481 }
2482 else
2483 {
2484 record_change (pos, 1);
2485 *p = nc;
2486 signal_after_change (pos, 1, 1);
2487 }
2488 ++cnt;
2489 }
2490 }
2491 pos_byte = pos_byte_next;
2492 pos++;
2493 }
2494
2495 return make_number (cnt);
2496 }
2497
2498 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2499 "Delete the text between point and mark.\n\
2500 When called from a program, expects two arguments,\n\
2501 positions (integers or markers) specifying the stretch to be deleted.")
2502 (start, end)
2503 Lisp_Object start, end;
2504 {
2505 validate_region (&start, &end);
2506 del_range (XINT (start), XINT (end));
2507 return Qnil;
2508 }
2509 \f
2510 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2511 "Remove restrictions (narrowing) from current buffer.\n\
2512 This allows the buffer's full text to be seen and edited.")
2513 ()
2514 {
2515 if (BEG != BEGV || Z != ZV)
2516 current_buffer->clip_changed = 1;
2517 BEGV = BEG;
2518 BEGV_BYTE = BEG_BYTE;
2519 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2520 /* Changing the buffer bounds invalidates any recorded current column. */
2521 invalidate_current_column ();
2522 return Qnil;
2523 }
2524
2525 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2526 "Restrict editing in this buffer to the current region.\n\
2527 The rest of the text becomes temporarily invisible and untouchable\n\
2528 but is not deleted; if you save the buffer in a file, the invisible\n\
2529 text is included in the file. \\[widen] makes all visible again.\n\
2530 See also `save-restriction'.\n\
2531 \n\
2532 When calling from a program, pass two arguments; positions (integers\n\
2533 or markers) bounding the text that should remain visible.")
2534 (start, end)
2535 register Lisp_Object start, end;
2536 {
2537 CHECK_NUMBER_COERCE_MARKER (start, 0);
2538 CHECK_NUMBER_COERCE_MARKER (end, 1);
2539
2540 if (XINT (start) > XINT (end))
2541 {
2542 Lisp_Object tem;
2543 tem = start; start = end; end = tem;
2544 }
2545
2546 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2547 args_out_of_range (start, end);
2548
2549 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2550 current_buffer->clip_changed = 1;
2551
2552 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2553 SET_BUF_ZV (current_buffer, XFASTINT (end));
2554 if (PT < XFASTINT (start))
2555 SET_PT (XFASTINT (start));
2556 if (PT > XFASTINT (end))
2557 SET_PT (XFASTINT (end));
2558 /* Changing the buffer bounds invalidates any recorded current column. */
2559 invalidate_current_column ();
2560 return Qnil;
2561 }
2562
2563 Lisp_Object
2564 save_restriction_save ()
2565 {
2566 register Lisp_Object bottom, top;
2567 /* Note: I tried using markers here, but it does not win
2568 because insertion at the end of the saved region
2569 does not advance mh and is considered "outside" the saved region. */
2570 XSETFASTINT (bottom, BEGV - BEG);
2571 XSETFASTINT (top, Z - ZV);
2572
2573 return Fcons (Fcurrent_buffer (), Fcons (bottom, top));
2574 }
2575
2576 Lisp_Object
2577 save_restriction_restore (data)
2578 Lisp_Object data;
2579 {
2580 register struct buffer *buf;
2581 register int newhead, newtail;
2582 register Lisp_Object tem;
2583 int obegv, ozv;
2584
2585 buf = XBUFFER (XCAR (data));
2586
2587 data = XCDR (data);
2588
2589 tem = XCAR (data);
2590 newhead = XINT (tem);
2591 tem = XCDR (data);
2592 newtail = XINT (tem);
2593 if (newhead + newtail > BUF_Z (buf) - BUF_BEG (buf))
2594 {
2595 newhead = 0;
2596 newtail = 0;
2597 }
2598
2599 obegv = BUF_BEGV (buf);
2600 ozv = BUF_ZV (buf);
2601
2602 SET_BUF_BEGV (buf, BUF_BEG (buf) + newhead);
2603 SET_BUF_ZV (buf, BUF_Z (buf) - newtail);
2604
2605 if (obegv != BUF_BEGV (buf) || ozv != BUF_ZV (buf))
2606 current_buffer->clip_changed = 1;
2607
2608 /* If point is outside the new visible range, move it inside. */
2609 SET_BUF_PT_BOTH (buf,
2610 clip_to_bounds (BUF_BEGV (buf), BUF_PT (buf), BUF_ZV (buf)),
2611 clip_to_bounds (BUF_BEGV_BYTE (buf), BUF_PT_BYTE (buf),
2612 BUF_ZV_BYTE (buf)));
2613
2614 return Qnil;
2615 }
2616
2617 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2618 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2619 The buffer's restrictions make parts of the beginning and end invisible.\n\
2620 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2621 This special form, `save-restriction', saves the current buffer's restrictions\n\
2622 when it is entered, and restores them when it is exited.\n\
2623 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2624 The old restrictions settings are restored\n\
2625 even in case of abnormal exit (throw or error).\n\
2626 \n\
2627 The value returned is the value of the last form in BODY.\n\
2628 \n\
2629 `save-restriction' can get confused if, within the BODY, you widen\n\
2630 and then make changes outside the area within the saved restrictions.\n\
2631 See Info node `(elisp)Narrowing' for details and an appropriate technique.\n\
2632 \n\
2633 Note: if you are using both `save-excursion' and `save-restriction',\n\
2634 use `save-excursion' outermost:\n\
2635 (save-excursion (save-restriction ...))")
2636 (body)
2637 Lisp_Object body;
2638 {
2639 register Lisp_Object val;
2640 int count = specpdl_ptr - specpdl;
2641
2642 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2643 val = Fprogn (body);
2644 return unbind_to (count, val);
2645 }
2646 \f
2647 #ifndef HAVE_MENUS
2648
2649 /* Buffer for the most recent text displayed by Fmessage. */
2650 static char *message_text;
2651
2652 /* Allocated length of that buffer. */
2653 static int message_length;
2654
2655 #endif /* not HAVE_MENUS */
2656
2657 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2658 "Print a one-line message at the bottom of the screen.\n\
2659 The first argument is a format control string, and the rest are data\n\
2660 to be formatted under control of the string. See `format' for details.\n\
2661 \n\
2662 If the first argument is nil, clear any existing message; let the\n\
2663 minibuffer contents show.")
2664 (nargs, args)
2665 int nargs;
2666 Lisp_Object *args;
2667 {
2668 if (NILP (args[0]))
2669 {
2670 message (0);
2671 return Qnil;
2672 }
2673 else
2674 {
2675 register Lisp_Object val;
2676 val = Fformat (nargs, args);
2677 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2678 return val;
2679 }
2680 }
2681
2682 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2683 "Display a message, in a dialog box if possible.\n\
2684 If a dialog box is not available, use the echo area.\n\
2685 The first argument is a format control string, and the rest are data\n\
2686 to be formatted under control of the string. See `format' for details.\n\
2687 \n\
2688 If the first argument is nil, clear any existing message; let the\n\
2689 minibuffer contents show.")
2690 (nargs, args)
2691 int nargs;
2692 Lisp_Object *args;
2693 {
2694 if (NILP (args[0]))
2695 {
2696 message (0);
2697 return Qnil;
2698 }
2699 else
2700 {
2701 register Lisp_Object val;
2702 val = Fformat (nargs, args);
2703 #ifdef HAVE_MENUS
2704 {
2705 Lisp_Object pane, menu, obj;
2706 struct gcpro gcpro1;
2707 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2708 GCPRO1 (pane);
2709 menu = Fcons (val, pane);
2710 obj = Fx_popup_dialog (Qt, menu);
2711 UNGCPRO;
2712 return val;
2713 }
2714 #else /* not HAVE_MENUS */
2715 /* Copy the data so that it won't move when we GC. */
2716 if (! message_text)
2717 {
2718 message_text = (char *)xmalloc (80);
2719 message_length = 80;
2720 }
2721 if (STRING_BYTES (XSTRING (val)) > message_length)
2722 {
2723 message_length = STRING_BYTES (XSTRING (val));
2724 message_text = (char *)xrealloc (message_text, message_length);
2725 }
2726 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2727 message2 (message_text, STRING_BYTES (XSTRING (val)),
2728 STRING_MULTIBYTE (val));
2729 return val;
2730 #endif /* not HAVE_MENUS */
2731 }
2732 }
2733 #ifdef HAVE_MENUS
2734 extern Lisp_Object last_nonmenu_event;
2735 #endif
2736
2737 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2738 "Display a message in a dialog box or in the echo area.\n\
2739 If this command was invoked with the mouse, use a dialog box.\n\
2740 Otherwise, use the echo area.\n\
2741 The first argument is a format control string, and the rest are data\n\
2742 to be formatted under control of the string. See `format' for details.\n\
2743 \n\
2744 If the first argument is nil, clear any existing message; let the\n\
2745 minibuffer contents show.")
2746 (nargs, args)
2747 int nargs;
2748 Lisp_Object *args;
2749 {
2750 #ifdef HAVE_MENUS
2751 if (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2752 return Fmessage_box (nargs, args);
2753 #endif
2754 return Fmessage (nargs, args);
2755 }
2756
2757 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2758 "Return the string currently displayed in the echo area, or nil if none.")
2759 ()
2760 {
2761 return current_message ();
2762 }
2763
2764
2765 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
2766 "Return a copy of STRING with text properties added.\n\
2767 First argument is the string to copy.\n\
2768 Remaining arguments are sequences of PROPERTY VALUE pairs for text\n\
2769 properties to add to the result ")
2770 (nargs, args)
2771 int nargs;
2772 Lisp_Object *args;
2773 {
2774 Lisp_Object properties, string;
2775 struct gcpro gcpro1, gcpro2;
2776 int i;
2777
2778 /* Number of args must be odd. */
2779 if ((nargs & 1) == 0 || nargs < 3)
2780 error ("Wrong number of arguments");
2781
2782 properties = string = Qnil;
2783 GCPRO2 (properties, string);
2784
2785 /* First argument must be a string. */
2786 CHECK_STRING (args[0], 0);
2787 string = Fcopy_sequence (args[0]);
2788
2789 for (i = 1; i < nargs; i += 2)
2790 {
2791 CHECK_SYMBOL (args[i], i);
2792 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2793 }
2794
2795 Fadd_text_properties (make_number (0),
2796 make_number (XSTRING (string)->size),
2797 properties, string);
2798 RETURN_UNGCPRO (string);
2799 }
2800
2801
2802 /* Number of bytes that STRING will occupy when put into the result.
2803 MULTIBYTE is nonzero if the result should be multibyte. */
2804
2805 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
2806 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
2807 ? count_size_as_multibyte (XSTRING (STRING)->data, \
2808 STRING_BYTES (XSTRING (STRING))) \
2809 : STRING_BYTES (XSTRING (STRING)))
2810
2811 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
2812 "Format a string out of a control-string and arguments.\n\
2813 The first argument is a control string.\n\
2814 The other arguments are substituted into it to make the result, a string.\n\
2815 It may contain %-sequences meaning to substitute the next argument.\n\
2816 %s means print a string argument. Actually, prints any object, with `princ'.\n\
2817 %d means print as number in decimal (%o octal, %x hex).\n\
2818 %e means print a number in exponential notation.\n\
2819 %f means print a number in decimal-point notation.\n\
2820 %g means print a number in exponential notation\n\
2821 or decimal-point notation, whichever uses fewer characters.\n\
2822 %c means print a number as a single character.\n\
2823 %S means print any object as an s-expression (using `prin1').\n\
2824 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
2825 Use %% to put a single % into the output.")
2826 (nargs, args)
2827 int nargs;
2828 register Lisp_Object *args;
2829 {
2830 register int n; /* The number of the next arg to substitute */
2831 register int total; /* An estimate of the final length */
2832 char *buf, *p;
2833 register unsigned char *format, *end;
2834 int nchars;
2835 /* Nonzero if the output should be a multibyte string,
2836 which is true if any of the inputs is one. */
2837 int multibyte = 0;
2838 /* When we make a multibyte string, we must pay attention to the
2839 byte combining problem, i.e., a byte may be combined with a
2840 multibyte charcter of the previous string. This flag tells if we
2841 must consider such a situation or not. */
2842 int maybe_combine_byte;
2843 unsigned char *this_format;
2844 int longest_format;
2845 Lisp_Object val;
2846 struct info
2847 {
2848 int start, end;
2849 } *info = 0;
2850
2851 extern char *index ();
2852
2853 /* It should not be necessary to GCPRO ARGS, because
2854 the caller in the interpreter should take care of that. */
2855
2856 /* Try to determine whether the result should be multibyte.
2857 This is not always right; sometimes the result needs to be multibyte
2858 because of an object that we will pass through prin1,
2859 and in that case, we won't know it here. */
2860 for (n = 0; n < nargs; n++)
2861 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
2862 multibyte = 1;
2863
2864 CHECK_STRING (args[0], 0);
2865
2866 /* If we start out planning a unibyte result,
2867 and later find it has to be multibyte, we jump back to retry. */
2868 retry:
2869
2870 format = XSTRING (args[0])->data;
2871 end = format + STRING_BYTES (XSTRING (args[0]));
2872 longest_format = 0;
2873
2874 /* Make room in result for all the non-%-codes in the control string. */
2875 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
2876
2877 /* Add to TOTAL enough space to hold the converted arguments. */
2878
2879 n = 0;
2880 while (format != end)
2881 if (*format++ == '%')
2882 {
2883 int minlen, thissize = 0;
2884 unsigned char *this_format_start = format - 1;
2885
2886 /* Process a numeric arg and skip it. */
2887 minlen = atoi (format);
2888 if (minlen < 0)
2889 minlen = - minlen;
2890
2891 while ((*format >= '0' && *format <= '9')
2892 || *format == '-' || *format == ' ' || *format == '.')
2893 format++;
2894
2895 if (format - this_format_start + 1 > longest_format)
2896 longest_format = format - this_format_start + 1;
2897
2898 if (format == end)
2899 error ("Format string ends in middle of format specifier");
2900 if (*format == '%')
2901 format++;
2902 else if (++n >= nargs)
2903 error ("Not enough arguments for format string");
2904 else if (*format == 'S')
2905 {
2906 /* For `S', prin1 the argument and then treat like a string. */
2907 register Lisp_Object tem;
2908 tem = Fprin1_to_string (args[n], Qnil);
2909 if (STRING_MULTIBYTE (tem) && ! multibyte)
2910 {
2911 multibyte = 1;
2912 goto retry;
2913 }
2914 args[n] = tem;
2915 goto string;
2916 }
2917 else if (SYMBOLP (args[n]))
2918 {
2919 XSETSTRING (args[n], XSYMBOL (args[n])->name);
2920 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
2921 {
2922 multibyte = 1;
2923 goto retry;
2924 }
2925 goto string;
2926 }
2927 else if (STRINGP (args[n]))
2928 {
2929 string:
2930 if (*format != 's' && *format != 'S')
2931 error ("Format specifier doesn't match argument type");
2932 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
2933 }
2934 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
2935 else if (INTEGERP (args[n]) && *format != 's')
2936 {
2937 #ifdef LISP_FLOAT_TYPE
2938 /* The following loop assumes the Lisp type indicates
2939 the proper way to pass the argument.
2940 So make sure we have a flonum if the argument should
2941 be a double. */
2942 if (*format == 'e' || *format == 'f' || *format == 'g')
2943 args[n] = Ffloat (args[n]);
2944 else
2945 #endif
2946 if (*format != 'd' && *format != 'o' && *format != 'x'
2947 && *format != 'i' && *format != 'X' && *format != 'c')
2948 error ("Invalid format operation %%%c", *format);
2949
2950 thissize = 30;
2951 if (*format == 'c'
2952 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
2953 || XINT (args[n]) == 0))
2954 {
2955 if (! multibyte)
2956 {
2957 multibyte = 1;
2958 goto retry;
2959 }
2960 args[n] = Fchar_to_string (args[n]);
2961 thissize = STRING_BYTES (XSTRING (args[n]));
2962 }
2963 }
2964 #ifdef LISP_FLOAT_TYPE
2965 else if (FLOATP (args[n]) && *format != 's')
2966 {
2967 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
2968 args[n] = Ftruncate (args[n], Qnil);
2969 thissize = 200;
2970 }
2971 #endif
2972 else
2973 {
2974 /* Anything but a string, convert to a string using princ. */
2975 register Lisp_Object tem;
2976 tem = Fprin1_to_string (args[n], Qt);
2977 if (STRING_MULTIBYTE (tem) & ! multibyte)
2978 {
2979 multibyte = 1;
2980 goto retry;
2981 }
2982 args[n] = tem;
2983 goto string;
2984 }
2985
2986 if (thissize < minlen)
2987 thissize = minlen;
2988
2989 total += thissize + 4;
2990 }
2991
2992 /* Now we can no longer jump to retry.
2993 TOTAL and LONGEST_FORMAT are known for certain. */
2994
2995 this_format = (unsigned char *) alloca (longest_format + 1);
2996
2997 /* Allocate the space for the result.
2998 Note that TOTAL is an overestimate. */
2999 if (total < 1000)
3000 buf = (char *) alloca (total + 1);
3001 else
3002 buf = (char *) xmalloc (total + 1);
3003
3004 p = buf;
3005 nchars = 0;
3006 n = 0;
3007
3008 /* Scan the format and store result in BUF. */
3009 format = XSTRING (args[0])->data;
3010 maybe_combine_byte = 0;
3011 while (format != end)
3012 {
3013 if (*format == '%')
3014 {
3015 int minlen;
3016 int negative = 0;
3017 unsigned char *this_format_start = format;
3018
3019 format++;
3020
3021 /* Process a numeric arg and skip it. */
3022 minlen = atoi (format);
3023 if (minlen < 0)
3024 minlen = - minlen, negative = 1;
3025
3026 while ((*format >= '0' && *format <= '9')
3027 || *format == '-' || *format == ' ' || *format == '.')
3028 format++;
3029
3030 if (*format++ == '%')
3031 {
3032 *p++ = '%';
3033 nchars++;
3034 continue;
3035 }
3036
3037 ++n;
3038
3039 if (STRINGP (args[n]))
3040 {
3041 int padding, nbytes;
3042 int width = strwidth (XSTRING (args[n])->data,
3043 STRING_BYTES (XSTRING (args[n])));
3044 int start = nchars;
3045
3046 /* If spec requires it, pad on right with spaces. */
3047 padding = minlen - width;
3048 if (! negative)
3049 while (padding-- > 0)
3050 {
3051 *p++ = ' ';
3052 nchars++;
3053 }
3054
3055 if (p > buf
3056 && multibyte
3057 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3058 && STRING_MULTIBYTE (args[n])
3059 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3060 maybe_combine_byte = 1;
3061 nbytes = copy_text (XSTRING (args[n])->data, p,
3062 STRING_BYTES (XSTRING (args[n])),
3063 STRING_MULTIBYTE (args[n]), multibyte);
3064 p += nbytes;
3065 nchars += XSTRING (args[n])->size;
3066
3067 if (negative)
3068 while (padding-- > 0)
3069 {
3070 *p++ = ' ';
3071 nchars++;
3072 }
3073
3074 /* If this argument has text properties, record where
3075 in the result string it appears. */
3076 if (XSTRING (args[n])->intervals)
3077 {
3078 if (!info)
3079 {
3080 int nbytes = nargs * sizeof *info;
3081 info = (struct info *) alloca (nbytes);
3082 bzero (info, nbytes);
3083 }
3084
3085 info[n].start = start;
3086 info[n].end = nchars;
3087 }
3088 }
3089 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3090 {
3091 int this_nchars;
3092
3093 bcopy (this_format_start, this_format,
3094 format - this_format_start);
3095 this_format[format - this_format_start] = 0;
3096
3097 if (INTEGERP (args[n]))
3098 sprintf (p, this_format, XINT (args[n]));
3099 else
3100 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3101
3102 if (p > buf
3103 && multibyte
3104 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3105 && !CHAR_HEAD_P (*((unsigned char *) p)))
3106 maybe_combine_byte = 1;
3107 this_nchars = strlen (p);
3108 p += this_nchars;
3109 nchars += this_nchars;
3110 }
3111 }
3112 else if (STRING_MULTIBYTE (args[0]))
3113 {
3114 /* Copy a whole multibyte character. */
3115 if (p > buf
3116 && multibyte
3117 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3118 && !CHAR_HEAD_P (*format))
3119 maybe_combine_byte = 1;
3120 *p++ = *format++;
3121 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3122 nchars++;
3123 }
3124 else if (multibyte)
3125 {
3126 /* Convert a single-byte character to multibyte. */
3127 int len = copy_text (format, p, 1, 0, 1);
3128
3129 p += len;
3130 format++;
3131 nchars++;
3132 }
3133 else
3134 *p++ = *format++, nchars++;
3135 }
3136
3137 if (maybe_combine_byte)
3138 nchars = multibyte_chars_in_text (buf, p - buf);
3139 val = make_specified_string (buf, nchars, p - buf, multibyte);
3140
3141 /* If we allocated BUF with malloc, free it too. */
3142 if (total >= 1000)
3143 xfree (buf);
3144
3145 /* If the format string has text properties, or any of the string
3146 arguments has text properties, set up text properties of the
3147 result string. */
3148
3149 if (XSTRING (args[0])->intervals || info)
3150 {
3151 Lisp_Object len, new_len, props;
3152 struct gcpro gcpro1;
3153
3154 /* Add text properties from the format string. */
3155 len = make_number (XSTRING (args[0])->size);
3156 props = text_property_list (args[0], make_number (0), len, Qnil);
3157 GCPRO1 (props);
3158
3159 if (CONSP (props))
3160 {
3161 new_len = make_number (XSTRING (val)->size);
3162 extend_property_ranges (props, len, new_len);
3163 add_text_properties_from_list (val, props, make_number (0));
3164 }
3165
3166 /* Add text properties from arguments. */
3167 if (info)
3168 for (n = 1; n < nargs; ++n)
3169 if (info[n].end)
3170 {
3171 len = make_number (XSTRING (args[n])->size);
3172 new_len = make_number (info[n].end - info[n].start);
3173 props = text_property_list (args[n], make_number (0), len, Qnil);
3174 extend_property_ranges (props, len, new_len);
3175 add_text_properties_from_list (val, props,
3176 make_number (info[n].start));
3177 }
3178
3179 UNGCPRO;
3180 }
3181
3182 return val;
3183 }
3184
3185
3186 /* VARARGS 1 */
3187 Lisp_Object
3188 #ifdef NO_ARG_ARRAY
3189 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3190 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3191 #else
3192 format1 (string1)
3193 #endif
3194 char *string1;
3195 {
3196 char buf[100];
3197 #ifdef NO_ARG_ARRAY
3198 EMACS_INT args[5];
3199 args[0] = arg0;
3200 args[1] = arg1;
3201 args[2] = arg2;
3202 args[3] = arg3;
3203 args[4] = arg4;
3204 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3205 #else
3206 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3207 #endif
3208 return build_string (buf);
3209 }
3210 \f
3211 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3212 "Return t if two characters match, optionally ignoring case.\n\
3213 Both arguments must be characters (i.e. integers).\n\
3214 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3215 (c1, c2)
3216 register Lisp_Object c1, c2;
3217 {
3218 int i1, i2;
3219 CHECK_NUMBER (c1, 0);
3220 CHECK_NUMBER (c2, 1);
3221
3222 if (XINT (c1) == XINT (c2))
3223 return Qt;
3224 if (NILP (current_buffer->case_fold_search))
3225 return Qnil;
3226
3227 /* Do these in separate statements,
3228 then compare the variables.
3229 because of the way DOWNCASE uses temp variables. */
3230 i1 = DOWNCASE (XFASTINT (c1));
3231 i2 = DOWNCASE (XFASTINT (c2));
3232 return (i1 == i2 ? Qt : Qnil);
3233 }
3234 \f
3235 /* Transpose the markers in two regions of the current buffer, and
3236 adjust the ones between them if necessary (i.e.: if the regions
3237 differ in size).
3238
3239 START1, END1 are the character positions of the first region.
3240 START1_BYTE, END1_BYTE are the byte positions.
3241 START2, END2 are the character positions of the second region.
3242 START2_BYTE, END2_BYTE are the byte positions.
3243
3244 Traverses the entire marker list of the buffer to do so, adding an
3245 appropriate amount to some, subtracting from some, and leaving the
3246 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3247
3248 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3249
3250 void
3251 transpose_markers (start1, end1, start2, end2,
3252 start1_byte, end1_byte, start2_byte, end2_byte)
3253 register int start1, end1, start2, end2;
3254 register int start1_byte, end1_byte, start2_byte, end2_byte;
3255 {
3256 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3257 register Lisp_Object marker;
3258
3259 /* Update point as if it were a marker. */
3260 if (PT < start1)
3261 ;
3262 else if (PT < end1)
3263 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3264 PT_BYTE + (end2_byte - end1_byte));
3265 else if (PT < start2)
3266 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3267 (PT_BYTE + (end2_byte - start2_byte)
3268 - (end1_byte - start1_byte)));
3269 else if (PT < end2)
3270 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3271 PT_BYTE - (start2_byte - start1_byte));
3272
3273 /* We used to adjust the endpoints here to account for the gap, but that
3274 isn't good enough. Even if we assume the caller has tried to move the
3275 gap out of our way, it might still be at start1 exactly, for example;
3276 and that places it `inside' the interval, for our purposes. The amount
3277 of adjustment is nontrivial if there's a `denormalized' marker whose
3278 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3279 the dirty work to Fmarker_position, below. */
3280
3281 /* The difference between the region's lengths */
3282 diff = (end2 - start2) - (end1 - start1);
3283 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3284
3285 /* For shifting each marker in a region by the length of the other
3286 region plus the distance between the regions. */
3287 amt1 = (end2 - start2) + (start2 - end1);
3288 amt2 = (end1 - start1) + (start2 - end1);
3289 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3290 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3291
3292 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3293 marker = XMARKER (marker)->chain)
3294 {
3295 mpos = marker_byte_position (marker);
3296 if (mpos >= start1_byte && mpos < end2_byte)
3297 {
3298 if (mpos < end1_byte)
3299 mpos += amt1_byte;
3300 else if (mpos < start2_byte)
3301 mpos += diff_byte;
3302 else
3303 mpos -= amt2_byte;
3304 XMARKER (marker)->bytepos = mpos;
3305 }
3306 mpos = XMARKER (marker)->charpos;
3307 if (mpos >= start1 && mpos < end2)
3308 {
3309 if (mpos < end1)
3310 mpos += amt1;
3311 else if (mpos < start2)
3312 mpos += diff;
3313 else
3314 mpos -= amt2;
3315 }
3316 XMARKER (marker)->charpos = mpos;
3317 }
3318 }
3319
3320 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3321 "Transpose region START1 to END1 with START2 to END2.\n\
3322 The regions may not be overlapping, because the size of the buffer is\n\
3323 never changed in a transposition.\n\
3324 \n\
3325 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3326 any markers that happen to be located in the regions.\n\
3327 \n\
3328 Transposing beyond buffer boundaries is an error.")
3329 (startr1, endr1, startr2, endr2, leave_markers)
3330 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3331 {
3332 register int start1, end1, start2, end2;
3333 int start1_byte, start2_byte, len1_byte, len2_byte;
3334 int gap, len1, len_mid, len2;
3335 unsigned char *start1_addr, *start2_addr, *temp;
3336 int combined_before_bytes_1, combined_after_bytes_1;
3337 int combined_before_bytes_2, combined_after_bytes_2;
3338 struct gcpro gcpro1, gcpro2;
3339
3340 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3341 cur_intv = BUF_INTERVALS (current_buffer);
3342
3343 validate_region (&startr1, &endr1);
3344 validate_region (&startr2, &endr2);
3345
3346 start1 = XFASTINT (startr1);
3347 end1 = XFASTINT (endr1);
3348 start2 = XFASTINT (startr2);
3349 end2 = XFASTINT (endr2);
3350 gap = GPT;
3351
3352 /* Swap the regions if they're reversed. */
3353 if (start2 < end1)
3354 {
3355 register int glumph = start1;
3356 start1 = start2;
3357 start2 = glumph;
3358 glumph = end1;
3359 end1 = end2;
3360 end2 = glumph;
3361 }
3362
3363 len1 = end1 - start1;
3364 len2 = end2 - start2;
3365
3366 if (start2 < end1)
3367 error ("Transposed regions overlap");
3368 else if (start1 == end1 || start2 == end2)
3369 error ("Transposed region has length 0");
3370
3371 /* The possibilities are:
3372 1. Adjacent (contiguous) regions, or separate but equal regions
3373 (no, really equal, in this case!), or
3374 2. Separate regions of unequal size.
3375
3376 The worst case is usually No. 2. It means that (aside from
3377 potential need for getting the gap out of the way), there also
3378 needs to be a shifting of the text between the two regions. So
3379 if they are spread far apart, we are that much slower... sigh. */
3380
3381 /* It must be pointed out that the really studly thing to do would
3382 be not to move the gap at all, but to leave it in place and work
3383 around it if necessary. This would be extremely efficient,
3384 especially considering that people are likely to do
3385 transpositions near where they are working interactively, which
3386 is exactly where the gap would be found. However, such code
3387 would be much harder to write and to read. So, if you are
3388 reading this comment and are feeling squirrely, by all means have
3389 a go! I just didn't feel like doing it, so I will simply move
3390 the gap the minimum distance to get it out of the way, and then
3391 deal with an unbroken array. */
3392
3393 /* Make sure the gap won't interfere, by moving it out of the text
3394 we will operate on. */
3395 if (start1 < gap && gap < end2)
3396 {
3397 if (gap - start1 < end2 - gap)
3398 move_gap (start1);
3399 else
3400 move_gap (end2);
3401 }
3402
3403 start1_byte = CHAR_TO_BYTE (start1);
3404 start2_byte = CHAR_TO_BYTE (start2);
3405 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3406 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3407
3408 if (end1 == start2)
3409 {
3410 combined_before_bytes_2
3411 = count_combining_before (BYTE_POS_ADDR (start2_byte),
3412 len2_byte, start1, start1_byte);
3413 combined_before_bytes_1
3414 = count_combining_before (BYTE_POS_ADDR (start1_byte),
3415 len1_byte, end2, start2_byte + len2_byte);
3416 combined_after_bytes_1
3417 = count_combining_after (BYTE_POS_ADDR (start1_byte),
3418 len1_byte, end2, start2_byte + len2_byte);
3419 combined_after_bytes_2 = 0;
3420 }
3421 else
3422 {
3423 combined_before_bytes_2
3424 = count_combining_before (BYTE_POS_ADDR (start2_byte),
3425 len2_byte, start1, start1_byte);
3426 combined_before_bytes_1
3427 = count_combining_before (BYTE_POS_ADDR (start1_byte),
3428 len1_byte, start2, start2_byte);
3429 combined_after_bytes_2
3430 = count_combining_after (BYTE_POS_ADDR (start2_byte),
3431 len2_byte, end1, start1_byte + len1_byte);
3432 combined_after_bytes_1
3433 = count_combining_after (BYTE_POS_ADDR (start1_byte),
3434 len1_byte, end2, start2_byte + len2_byte);
3435 }
3436
3437 /* If any combining is going to happen, do this the stupid way,
3438 because replace handles combining properly. */
3439 if (combined_before_bytes_1 || combined_before_bytes_2
3440 || combined_after_bytes_1 || combined_after_bytes_2)
3441 {
3442 Lisp_Object text1, text2;
3443
3444 text1 = text2 = Qnil;
3445 GCPRO2 (text1, text2);
3446
3447 text1 = make_buffer_string_both (start1, start1_byte,
3448 end1, start1_byte + len1_byte, 1);
3449 text2 = make_buffer_string_both (start2, start2_byte,
3450 end2, start2_byte + len2_byte, 1);
3451
3452 transpose_markers (start1, end1, start2, end2,
3453 start1_byte, start1_byte + len1_byte,
3454 start2_byte, start2_byte + len2_byte);
3455
3456 replace_range (start2, end2, text1, 1, 0, 0);
3457 replace_range (start1, end1, text2, 1, 0, 0);
3458
3459 UNGCPRO;
3460 return Qnil;
3461 }
3462
3463 /* Hmmm... how about checking to see if the gap is large
3464 enough to use as the temporary storage? That would avoid an
3465 allocation... interesting. Later, don't fool with it now. */
3466
3467 /* Working without memmove, for portability (sigh), so must be
3468 careful of overlapping subsections of the array... */
3469
3470 if (end1 == start2) /* adjacent regions */
3471 {
3472 modify_region (current_buffer, start1, end2);
3473 record_change (start1, len1 + len2);
3474
3475 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3476 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3477 Fset_text_properties (make_number (start1), make_number (end2),
3478 Qnil, Qnil);
3479
3480 /* First region smaller than second. */
3481 if (len1_byte < len2_byte)
3482 {
3483 /* We use alloca only if it is small,
3484 because we want to avoid stack overflow. */
3485 if (len2_byte > 20000)
3486 temp = (unsigned char *) xmalloc (len2_byte);
3487 else
3488 temp = (unsigned char *) alloca (len2_byte);
3489
3490 /* Don't precompute these addresses. We have to compute them
3491 at the last minute, because the relocating allocator might
3492 have moved the buffer around during the xmalloc. */
3493 start1_addr = BYTE_POS_ADDR (start1_byte);
3494 start2_addr = BYTE_POS_ADDR (start2_byte);
3495
3496 bcopy (start2_addr, temp, len2_byte);
3497 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3498 bcopy (temp, start1_addr, len2_byte);
3499 if (len2_byte > 20000)
3500 free (temp);
3501 }
3502 else
3503 /* First region not smaller than second. */
3504 {
3505 if (len1_byte > 20000)
3506 temp = (unsigned char *) xmalloc (len1_byte);
3507 else
3508 temp = (unsigned char *) alloca (len1_byte);
3509 start1_addr = BYTE_POS_ADDR (start1_byte);
3510 start2_addr = BYTE_POS_ADDR (start2_byte);
3511 bcopy (start1_addr, temp, len1_byte);
3512 bcopy (start2_addr, start1_addr, len2_byte);
3513 bcopy (temp, start1_addr + len2_byte, len1_byte);
3514 if (len1_byte > 20000)
3515 free (temp);
3516 }
3517 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3518 len1, current_buffer, 0);
3519 graft_intervals_into_buffer (tmp_interval2, start1,
3520 len2, current_buffer, 0);
3521 }
3522 /* Non-adjacent regions, because end1 != start2, bleagh... */
3523 else
3524 {
3525 len_mid = start2_byte - (start1_byte + len1_byte);
3526
3527 if (len1_byte == len2_byte)
3528 /* Regions are same size, though, how nice. */
3529 {
3530 modify_region (current_buffer, start1, end1);
3531 modify_region (current_buffer, start2, end2);
3532 record_change (start1, len1);
3533 record_change (start2, len2);
3534 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3535 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3536 Fset_text_properties (make_number (start1), make_number (end1),
3537 Qnil, Qnil);
3538 Fset_text_properties (make_number (start2), make_number (end2),
3539 Qnil, Qnil);
3540
3541 if (len1_byte > 20000)
3542 temp = (unsigned char *) xmalloc (len1_byte);
3543 else
3544 temp = (unsigned char *) alloca (len1_byte);
3545 start1_addr = BYTE_POS_ADDR (start1_byte);
3546 start2_addr = BYTE_POS_ADDR (start2_byte);
3547 bcopy (start1_addr, temp, len1_byte);
3548 bcopy (start2_addr, start1_addr, len2_byte);
3549 bcopy (temp, start2_addr, len1_byte);
3550 if (len1_byte > 20000)
3551 free (temp);
3552 graft_intervals_into_buffer (tmp_interval1, start2,
3553 len1, current_buffer, 0);
3554 graft_intervals_into_buffer (tmp_interval2, start1,
3555 len2, current_buffer, 0);
3556 }
3557
3558 else if (len1_byte < len2_byte) /* Second region larger than first */
3559 /* Non-adjacent & unequal size, area between must also be shifted. */
3560 {
3561 modify_region (current_buffer, start1, end2);
3562 record_change (start1, (end2 - start1));
3563 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3564 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3565 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3566 Fset_text_properties (make_number (start1), make_number (end2),
3567 Qnil, Qnil);
3568
3569 /* holds region 2 */
3570 if (len2_byte > 20000)
3571 temp = (unsigned char *) xmalloc (len2_byte);
3572 else
3573 temp = (unsigned char *) alloca (len2_byte);
3574 start1_addr = BYTE_POS_ADDR (start1_byte);
3575 start2_addr = BYTE_POS_ADDR (start2_byte);
3576 bcopy (start2_addr, temp, len2_byte);
3577 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3578 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3579 bcopy (temp, start1_addr, len2_byte);
3580 if (len2_byte > 20000)
3581 free (temp);
3582 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3583 len1, current_buffer, 0);
3584 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3585 len_mid, current_buffer, 0);
3586 graft_intervals_into_buffer (tmp_interval2, start1,
3587 len2, current_buffer, 0);
3588 }
3589 else
3590 /* Second region smaller than first. */
3591 {
3592 record_change (start1, (end2 - start1));
3593 modify_region (current_buffer, start1, end2);
3594
3595 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3596 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3597 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3598 Fset_text_properties (make_number (start1), make_number (end2),
3599 Qnil, Qnil);
3600
3601 /* holds region 1 */
3602 if (len1_byte > 20000)
3603 temp = (unsigned char *) xmalloc (len1_byte);
3604 else
3605 temp = (unsigned char *) alloca (len1_byte);
3606 start1_addr = BYTE_POS_ADDR (start1_byte);
3607 start2_addr = BYTE_POS_ADDR (start2_byte);
3608 bcopy (start1_addr, temp, len1_byte);
3609 bcopy (start2_addr, start1_addr, len2_byte);
3610 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3611 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3612 if (len1_byte > 20000)
3613 free (temp);
3614 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3615 len1, current_buffer, 0);
3616 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3617 len_mid, current_buffer, 0);
3618 graft_intervals_into_buffer (tmp_interval2, start1,
3619 len2, current_buffer, 0);
3620 }
3621 }
3622
3623 /* When doing multiple transpositions, it might be nice
3624 to optimize this. Perhaps the markers in any one buffer
3625 should be organized in some sorted data tree. */
3626 if (NILP (leave_markers))
3627 {
3628 transpose_markers (start1, end1, start2, end2,
3629 start1_byte, start1_byte + len1_byte,
3630 start2_byte, start2_byte + len2_byte);
3631 fix_overlays_in_range (start1, end2);
3632 }
3633
3634 return Qnil;
3635 }
3636
3637 \f
3638 void
3639 syms_of_editfns ()
3640 {
3641 environbuf = 0;
3642
3643 Qbuffer_access_fontify_functions
3644 = intern ("buffer-access-fontify-functions");
3645 staticpro (&Qbuffer_access_fontify_functions);
3646
3647 DEFVAR_LISP ("buffer-access-fontify-functions",
3648 &Vbuffer_access_fontify_functions,
3649 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3650 Each function is called with two arguments which specify the range\n\
3651 of the buffer being accessed.");
3652 Vbuffer_access_fontify_functions = Qnil;
3653
3654 {
3655 Lisp_Object obuf;
3656 extern Lisp_Object Vprin1_to_string_buffer;
3657 obuf = Fcurrent_buffer ();
3658 /* Do this here, because init_buffer_once is too early--it won't work. */
3659 Fset_buffer (Vprin1_to_string_buffer);
3660 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3661 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3662 Qnil);
3663 Fset_buffer (obuf);
3664 }
3665
3666 DEFVAR_LISP ("buffer-access-fontified-property",
3667 &Vbuffer_access_fontified_property,
3668 "Property which (if non-nil) indicates text has been fontified.\n\
3669 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3670 functions if all the text being accessed has this property.");
3671 Vbuffer_access_fontified_property = Qnil;
3672
3673 DEFVAR_LISP ("system-name", &Vsystem_name,
3674 "The name of the machine Emacs is running on.");
3675
3676 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3677 "The full name of the user logged in.");
3678
3679 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3680 "The user's name, taken from environment variables if possible.");
3681
3682 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3683 "The user's name, based upon the real uid only.");
3684
3685 defsubr (&Spropertize);
3686 defsubr (&Schar_equal);
3687 defsubr (&Sgoto_char);
3688 defsubr (&Sstring_to_char);
3689 defsubr (&Schar_to_string);
3690 defsubr (&Sbuffer_substring);
3691 defsubr (&Sbuffer_substring_no_properties);
3692 defsubr (&Sbuffer_string);
3693
3694 defsubr (&Spoint_marker);
3695 defsubr (&Smark_marker);
3696 defsubr (&Spoint);
3697 defsubr (&Sregion_beginning);
3698 defsubr (&Sregion_end);
3699
3700 staticpro (&Qfield);
3701 Qfield = intern ("field");
3702 defsubr (&Sfield_beginning);
3703 defsubr (&Sfield_end);
3704 defsubr (&Sfield_string);
3705 defsubr (&Sfield_string_no_properties);
3706 defsubr (&Sdelete_field);
3707 defsubr (&Sconstrain_to_field);
3708
3709 defsubr (&Sline_beginning_position);
3710 defsubr (&Sline_end_position);
3711
3712 /* defsubr (&Smark); */
3713 /* defsubr (&Sset_mark); */
3714 defsubr (&Ssave_excursion);
3715 defsubr (&Ssave_current_buffer);
3716
3717 defsubr (&Sbufsize);
3718 defsubr (&Spoint_max);
3719 defsubr (&Spoint_min);
3720 defsubr (&Spoint_min_marker);
3721 defsubr (&Spoint_max_marker);
3722 defsubr (&Sgap_position);
3723 defsubr (&Sgap_size);
3724 defsubr (&Sposition_bytes);
3725 defsubr (&Sbyte_to_position);
3726
3727 defsubr (&Sbobp);
3728 defsubr (&Seobp);
3729 defsubr (&Sbolp);
3730 defsubr (&Seolp);
3731 defsubr (&Sfollowing_char);
3732 defsubr (&Sprevious_char);
3733 defsubr (&Schar_after);
3734 defsubr (&Schar_before);
3735 defsubr (&Sinsert);
3736 defsubr (&Sinsert_before_markers);
3737 defsubr (&Sinsert_and_inherit);
3738 defsubr (&Sinsert_and_inherit_before_markers);
3739 defsubr (&Sinsert_char);
3740
3741 defsubr (&Suser_login_name);
3742 defsubr (&Suser_real_login_name);
3743 defsubr (&Suser_uid);
3744 defsubr (&Suser_real_uid);
3745 defsubr (&Suser_full_name);
3746 defsubr (&Semacs_pid);
3747 defsubr (&Scurrent_time);
3748 defsubr (&Sformat_time_string);
3749 defsubr (&Sdecode_time);
3750 defsubr (&Sencode_time);
3751 defsubr (&Scurrent_time_string);
3752 defsubr (&Scurrent_time_zone);
3753 defsubr (&Sset_time_zone_rule);
3754 defsubr (&Ssystem_name);
3755 defsubr (&Smessage);
3756 defsubr (&Smessage_box);
3757 defsubr (&Smessage_or_box);
3758 defsubr (&Scurrent_message);
3759 defsubr (&Sformat);
3760
3761 defsubr (&Sinsert_buffer_substring);
3762 defsubr (&Scompare_buffer_substrings);
3763 defsubr (&Ssubst_char_in_region);
3764 defsubr (&Stranslate_region);
3765 defsubr (&Sdelete_region);
3766 defsubr (&Swiden);
3767 defsubr (&Snarrow_to_region);
3768 defsubr (&Ssave_restriction);
3769 defsubr (&Stranspose_regions);
3770 }