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