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