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