(Fcompare_buffer_substrings): Rewrite to loop by chars.
[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;
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 i1, i2, i1_byte, i2_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 i1 = begp1;
1774 i2 = begp2;
1775 i1_byte = buf_charpos_to_bytepos (bp1, i1);
1776 i2_byte = buf_charpos_to_bytepos (bp2, i2);
1777
1778 while (i1 < endp1 && i2 < endp2)
1779 {
1780 /* When we find a mismatch, we must compare the
1781 characters, not just the bytes. */
1782 int c1, c2;
1783
1784 if (! NILP (bp1->enable_multibyte_characters))
1785 {
1786 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
1787 BUF_INC_POS (bp1, i1_byte);
1788 i1++;
1789 }
1790 else
1791 {
1792 c1 = BUF_FETCH_BYTE (bp1, i1);
1793 c1 = unibyte_char_to_multibyte (c1);
1794 i1++;
1795 }
1796
1797 if (! NILP (bp2->enable_multibyte_characters))
1798 {
1799 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
1800 BUF_INC_POS (bp2, i2_byte);
1801 i2++;
1802 }
1803 else
1804 {
1805 c2 = BUF_FETCH_BYTE (bp2, i2);
1806 c2 = unibyte_char_to_multibyte (c2);
1807 i2++;
1808 }
1809
1810 if (trt)
1811 {
1812 c1 = XINT (trt[c1]);
1813 c2 = XINT (trt[c2]);
1814 }
1815 if (c1 < c2)
1816 return make_number (- 1 - chars);
1817 if (c1 > c2)
1818 return make_number (chars + 1);
1819
1820 chars++;
1821 }
1822
1823 /* The strings match as far as they go.
1824 If one is shorter, that one is less. */
1825 if (chars < endp1 - begp1)
1826 return make_number (chars + 1);
1827 else if (chars < endp2 - begp2)
1828 return make_number (- chars - 1);
1829
1830 /* Same length too => they are equal. */
1831 return make_number (0);
1832 }
1833 \f
1834 static Lisp_Object
1835 subst_char_in_region_unwind (arg)
1836 Lisp_Object arg;
1837 {
1838 return current_buffer->undo_list = arg;
1839 }
1840
1841 static Lisp_Object
1842 subst_char_in_region_unwind_1 (arg)
1843 Lisp_Object arg;
1844 {
1845 return current_buffer->filename = arg;
1846 }
1847
1848 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
1849 Ssubst_char_in_region, 4, 5, 0,
1850 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
1851 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
1852 and don't mark the buffer as really changed.\n\
1853 Both characters must have the same length of multi-byte form.")
1854 (start, end, fromchar, tochar, noundo)
1855 Lisp_Object start, end, fromchar, tochar, noundo;
1856 {
1857 register int pos, pos_byte, stop, i, len, end_byte;
1858 int changed = 0;
1859 unsigned char fromwork[4], *fromstr, towork[4], *tostr, *p;
1860 int count = specpdl_ptr - specpdl;
1861
1862 validate_region (&start, &end);
1863 CHECK_NUMBER (fromchar, 2);
1864 CHECK_NUMBER (tochar, 3);
1865
1866 if (! NILP (current_buffer->enable_multibyte_characters))
1867 {
1868 len = CHAR_STRING (XFASTINT (fromchar), fromwork, fromstr);
1869 if (CHAR_STRING (XFASTINT (tochar), towork, tostr) != len)
1870 error ("Characters in subst-char-in-region have different byte-lengths");
1871 }
1872 else
1873 {
1874 len = 1;
1875 fromwork[0] = XFASTINT (fromchar), fromstr = fromwork;
1876 towork[0] = XFASTINT (tochar), tostr = towork;
1877 }
1878
1879 pos = XINT (start);
1880 pos_byte = CHAR_TO_BYTE (pos);
1881 stop = CHAR_TO_BYTE (XINT (end));
1882 end_byte = stop;
1883
1884 /* If we don't want undo, turn off putting stuff on the list.
1885 That's faster than getting rid of things,
1886 and it prevents even the entry for a first change.
1887 Also inhibit locking the file. */
1888 if (!NILP (noundo))
1889 {
1890 record_unwind_protect (subst_char_in_region_unwind,
1891 current_buffer->undo_list);
1892 current_buffer->undo_list = Qt;
1893 /* Don't do file-locking. */
1894 record_unwind_protect (subst_char_in_region_unwind_1,
1895 current_buffer->filename);
1896 current_buffer->filename = Qnil;
1897 }
1898
1899 if (pos_byte < GPT_BYTE)
1900 stop = min (stop, GPT_BYTE);
1901 while (1)
1902 {
1903 if (pos_byte >= stop)
1904 {
1905 if (pos_byte >= end_byte) break;
1906 stop = end_byte;
1907 }
1908 p = BYTE_POS_ADDR (pos_byte);
1909 if (p[0] == fromstr[0]
1910 && (len == 1
1911 || (p[1] == fromstr[1]
1912 && (len == 2 || (p[2] == fromstr[2]
1913 && (len == 3 || p[3] == fromstr[3]))))))
1914 {
1915 if (! changed)
1916 {
1917 modify_region (current_buffer, XINT (start), XINT (end));
1918
1919 if (! NILP (noundo))
1920 {
1921 if (MODIFF - 1 == SAVE_MODIFF)
1922 SAVE_MODIFF++;
1923 if (MODIFF - 1 == current_buffer->auto_save_modified)
1924 current_buffer->auto_save_modified++;
1925 }
1926
1927 changed = 1;
1928 }
1929
1930 if (NILP (noundo))
1931 record_change (pos, 1);
1932 for (i = 0; i < len; i++) *p++ = tostr[i];
1933 }
1934 INC_BOTH (pos, pos_byte);
1935 }
1936
1937 if (changed)
1938 signal_after_change (XINT (start),
1939 XINT (end) - XINT (start), XINT (end) - XINT (start));
1940
1941 unbind_to (count, Qnil);
1942 return Qnil;
1943 }
1944
1945 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
1946 "From START to END, translate characters according to TABLE.\n\
1947 TABLE is a string; the Nth character in it is the mapping\n\
1948 for the character with code N.\n\
1949 This function does not alter multibyte characters.\n\
1950 It returns the number of characters changed.")
1951 (start, end, table)
1952 Lisp_Object start;
1953 Lisp_Object end;
1954 register Lisp_Object table;
1955 {
1956 register int pos_byte, stop; /* Limits of the region. */
1957 register unsigned char *tt; /* Trans table. */
1958 register int nc; /* New character. */
1959 int cnt; /* Number of changes made. */
1960 int size; /* Size of translate table. */
1961 int pos;
1962
1963 validate_region (&start, &end);
1964 CHECK_STRING (table, 2);
1965
1966 size = STRING_BYTES (XSTRING (table));
1967 tt = XSTRING (table)->data;
1968
1969 pos_byte = CHAR_TO_BYTE (XINT (start));
1970 stop = CHAR_TO_BYTE (XINT (end));
1971 modify_region (current_buffer, XINT (start), XINT (end));
1972 pos = XINT (start);
1973
1974 cnt = 0;
1975 for (; pos_byte < stop; )
1976 {
1977 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
1978 int len;
1979 int oc;
1980
1981 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
1982 if (oc < size && len == 1)
1983 {
1984 nc = tt[oc];
1985 if (nc != oc)
1986 {
1987 record_change (pos, 1);
1988 *p = nc;
1989 signal_after_change (pos, 1, 1);
1990 ++cnt;
1991 }
1992 }
1993 pos_byte += len;
1994 pos++;
1995 }
1996
1997 return make_number (cnt);
1998 }
1999
2000 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2001 "Delete the text between point and mark.\n\
2002 When called from a program, expects two arguments,\n\
2003 positions (integers or markers) specifying the stretch to be deleted.")
2004 (start, end)
2005 Lisp_Object start, end;
2006 {
2007 validate_region (&start, &end);
2008 del_range (XINT (start), XINT (end));
2009 return Qnil;
2010 }
2011 \f
2012 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2013 "Remove restrictions (narrowing) from current buffer.\n\
2014 This allows the buffer's full text to be seen and edited.")
2015 ()
2016 {
2017 if (BEG != BEGV || Z != ZV)
2018 current_buffer->clip_changed = 1;
2019 BEGV = BEG;
2020 BEGV_BYTE = BEG_BYTE;
2021 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2022 /* Changing the buffer bounds invalidates any recorded current column. */
2023 invalidate_current_column ();
2024 return Qnil;
2025 }
2026
2027 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2028 "Restrict editing in this buffer to the current region.\n\
2029 The rest of the text becomes temporarily invisible and untouchable\n\
2030 but is not deleted; if you save the buffer in a file, the invisible\n\
2031 text is included in the file. \\[widen] makes all visible again.\n\
2032 See also `save-restriction'.\n\
2033 \n\
2034 When calling from a program, pass two arguments; positions (integers\n\
2035 or markers) bounding the text that should remain visible.")
2036 (start, end)
2037 register Lisp_Object start, end;
2038 {
2039 CHECK_NUMBER_COERCE_MARKER (start, 0);
2040 CHECK_NUMBER_COERCE_MARKER (end, 1);
2041
2042 if (XINT (start) > XINT (end))
2043 {
2044 Lisp_Object tem;
2045 tem = start; start = end; end = tem;
2046 }
2047
2048 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2049 args_out_of_range (start, end);
2050
2051 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2052 current_buffer->clip_changed = 1;
2053
2054 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2055 SET_BUF_ZV (current_buffer, XFASTINT (end));
2056 if (PT < XFASTINT (start))
2057 SET_PT (XFASTINT (start));
2058 if (PT > XFASTINT (end))
2059 SET_PT (XFASTINT (end));
2060 /* Changing the buffer bounds invalidates any recorded current column. */
2061 invalidate_current_column ();
2062 return Qnil;
2063 }
2064
2065 Lisp_Object
2066 save_restriction_save ()
2067 {
2068 register Lisp_Object bottom, top;
2069 /* Note: I tried using markers here, but it does not win
2070 because insertion at the end of the saved region
2071 does not advance mh and is considered "outside" the saved region. */
2072 XSETFASTINT (bottom, BEGV - BEG);
2073 XSETFASTINT (top, Z - ZV);
2074
2075 return Fcons (Fcurrent_buffer (), Fcons (bottom, top));
2076 }
2077
2078 Lisp_Object
2079 save_restriction_restore (data)
2080 Lisp_Object data;
2081 {
2082 register struct buffer *buf;
2083 register int newhead, newtail;
2084 register Lisp_Object tem;
2085 int obegv, ozv;
2086
2087 buf = XBUFFER (XCONS (data)->car);
2088
2089 data = XCONS (data)->cdr;
2090
2091 tem = XCONS (data)->car;
2092 newhead = XINT (tem);
2093 tem = XCONS (data)->cdr;
2094 newtail = XINT (tem);
2095 if (newhead + newtail > BUF_Z (buf) - BUF_BEG (buf))
2096 {
2097 newhead = 0;
2098 newtail = 0;
2099 }
2100
2101 obegv = BUF_BEGV (buf);
2102 ozv = BUF_ZV (buf);
2103
2104 SET_BUF_BEGV (buf, BUF_BEG (buf) + newhead);
2105 SET_BUF_ZV (buf, BUF_Z (buf) - newtail);
2106
2107 if (obegv != BUF_BEGV (buf) || ozv != BUF_ZV (buf))
2108 current_buffer->clip_changed = 1;
2109
2110 /* If point is outside the new visible range, move it inside. */
2111 SET_BUF_PT_BOTH (buf,
2112 clip_to_bounds (BUF_BEGV (buf), BUF_PT (buf), BUF_ZV (buf)),
2113 clip_to_bounds (BUF_BEGV_BYTE (buf), BUF_PT_BYTE (buf),
2114 BUF_ZV_BYTE (buf)));
2115
2116 return Qnil;
2117 }
2118
2119 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2120 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2121 The buffer's restrictions make parts of the beginning and end invisible.\n\
2122 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2123 This special form, `save-restriction', saves the current buffer's restrictions\n\
2124 when it is entered, and restores them when it is exited.\n\
2125 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2126 The old restrictions settings are restored\n\
2127 even in case of abnormal exit (throw or error).\n\
2128 \n\
2129 The value returned is the value of the last form in BODY.\n\
2130 \n\
2131 `save-restriction' can get confused if, within the BODY, you widen\n\
2132 and then make changes outside the area within the saved restrictions.\n\
2133 \n\
2134 Note: if you are using both `save-excursion' and `save-restriction',\n\
2135 use `save-excursion' outermost:\n\
2136 (save-excursion (save-restriction ...))")
2137 (body)
2138 Lisp_Object body;
2139 {
2140 register Lisp_Object val;
2141 int count = specpdl_ptr - specpdl;
2142
2143 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2144 val = Fprogn (body);
2145 return unbind_to (count, val);
2146 }
2147 \f
2148 /* Buffer for the most recent text displayed by Fmessage. */
2149 static char *message_text;
2150
2151 /* Allocated length of that buffer. */
2152 static int message_length;
2153
2154 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2155 "Print a one-line message at the bottom of the screen.\n\
2156 The first argument is a format control string, and the rest are data\n\
2157 to be formatted under control of the string. See `format' for details.\n\
2158 \n\
2159 If the first argument is nil, clear any existing message; let the\n\
2160 minibuffer contents show.")
2161 (nargs, args)
2162 int nargs;
2163 Lisp_Object *args;
2164 {
2165 if (NILP (args[0]))
2166 {
2167 message (0);
2168 return Qnil;
2169 }
2170 else
2171 {
2172 register Lisp_Object val;
2173 val = Fformat (nargs, args);
2174 /* Copy the data so that it won't move when we GC. */
2175 if (! message_text)
2176 {
2177 message_text = (char *)xmalloc (80);
2178 message_length = 80;
2179 }
2180 if (STRING_BYTES (XSTRING (val)) > message_length)
2181 {
2182 message_length = STRING_BYTES (XSTRING (val));
2183 message_text = (char *)xrealloc (message_text, message_length);
2184 }
2185 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2186 message2 (message_text, STRING_BYTES (XSTRING (val)),
2187 STRING_MULTIBYTE (val));
2188 return val;
2189 }
2190 }
2191
2192 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2193 "Display a message, in a dialog box if possible.\n\
2194 If a dialog box is not available, use the echo area.\n\
2195 The first argument is a format control string, and the rest are data\n\
2196 to be formatted under control of the string. See `format' for details.\n\
2197 \n\
2198 If the first argument is nil, clear any existing message; let the\n\
2199 minibuffer contents show.")
2200 (nargs, args)
2201 int nargs;
2202 Lisp_Object *args;
2203 {
2204 if (NILP (args[0]))
2205 {
2206 message (0);
2207 return Qnil;
2208 }
2209 else
2210 {
2211 register Lisp_Object val;
2212 val = Fformat (nargs, args);
2213 #ifdef HAVE_MENUS
2214 {
2215 Lisp_Object pane, menu, obj;
2216 struct gcpro gcpro1;
2217 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2218 GCPRO1 (pane);
2219 menu = Fcons (val, pane);
2220 obj = Fx_popup_dialog (Qt, menu);
2221 UNGCPRO;
2222 return val;
2223 }
2224 #else /* not HAVE_MENUS */
2225 /* Copy the data so that it won't move when we GC. */
2226 if (! message_text)
2227 {
2228 message_text = (char *)xmalloc (80);
2229 message_length = 80;
2230 }
2231 if (STRING_BYTES (XSTRING (val)) > message_length)
2232 {
2233 message_length = STRING_BYTES (XSTRING (val));
2234 message_text = (char *)xrealloc (message_text, message_length);
2235 }
2236 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2237 message2 (message_text, STRING_BYTES (XSTRING (val)),
2238 STRING_MULTIBYTE (val));
2239 return val;
2240 #endif /* not HAVE_MENUS */
2241 }
2242 }
2243 #ifdef HAVE_MENUS
2244 extern Lisp_Object last_nonmenu_event;
2245 #endif
2246
2247 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2248 "Display a message in a dialog box or in the echo area.\n\
2249 If this command was invoked with the mouse, use a dialog box.\n\
2250 Otherwise, use the echo area.\n\
2251 The first argument is a format control string, and the rest are data\n\
2252 to be formatted under control of the string. See `format' for details.\n\
2253 \n\
2254 If the first argument is nil, clear any existing message; let the\n\
2255 minibuffer contents show.")
2256 (nargs, args)
2257 int nargs;
2258 Lisp_Object *args;
2259 {
2260 #ifdef HAVE_MENUS
2261 if (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2262 return Fmessage_box (nargs, args);
2263 #endif
2264 return Fmessage (nargs, args);
2265 }
2266
2267 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2268 "Return the string currently displayed in the echo area, or nil if none.")
2269 ()
2270 {
2271 return (echo_area_glyphs
2272 ? make_string (echo_area_glyphs, echo_area_glyphs_length)
2273 : Qnil);
2274 }
2275
2276 /* Number of bytes that STRING will occupy when put into the result.
2277 MULTIBYTE is nonzero if the result should be multibyte. */
2278
2279 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
2280 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
2281 ? count_size_as_multibyte (XSTRING (STRING)->data, \
2282 STRING_BYTES (XSTRING (STRING))) \
2283 : STRING_BYTES (XSTRING (STRING)))
2284
2285 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
2286 "Format a string out of a control-string and arguments.\n\
2287 The first argument is a control string.\n\
2288 The other arguments are substituted into it to make the result, a string.\n\
2289 It may contain %-sequences meaning to substitute the next argument.\n\
2290 %s means print a string argument. Actually, prints any object, with `princ'.\n\
2291 %d means print as number in decimal (%o octal, %x hex).\n\
2292 %e means print a number in exponential notation.\n\
2293 %f means print a number in decimal-point notation.\n\
2294 %g means print a number in exponential notation\n\
2295 or decimal-point notation, whichever uses fewer characters.\n\
2296 %c means print a number as a single character.\n\
2297 %S means print any object as an s-expression (using prin1).\n\
2298 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
2299 Use %% to put a single % into the output.")
2300 (nargs, args)
2301 int nargs;
2302 register Lisp_Object *args;
2303 {
2304 register int n; /* The number of the next arg to substitute */
2305 register int total; /* An estimate of the final length */
2306 char *buf, *p;
2307 register unsigned char *format, *end;
2308 int length, nchars;
2309 /* Nonzero if the output should be a multibyte string,
2310 which is true if any of the inputs is one. */
2311 int multibyte = 0;
2312 unsigned char *this_format;
2313 int longest_format;
2314 Lisp_Object val;
2315
2316 extern char *index ();
2317
2318 /* It should not be necessary to GCPRO ARGS, because
2319 the caller in the interpreter should take care of that. */
2320
2321 /* Try to determine whether the result should be multibyte.
2322 This is not always right; sometimes the result needs to be multibyte
2323 because of an object that we will pass through prin1,
2324 and in that case, we won't know it here. */
2325 for (n = 0; n < nargs; n++)
2326 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
2327 multibyte = 1;
2328
2329 CHECK_STRING (args[0], 0);
2330
2331 /* If we start out planning a unibyte result,
2332 and later find it has to be multibyte, we jump back to retry. */
2333 retry:
2334
2335 format = XSTRING (args[0])->data;
2336 end = format + STRING_BYTES (XSTRING (args[0]));
2337 longest_format = 0;
2338
2339 /* Make room in result for all the non-%-codes in the control string. */
2340 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
2341
2342 /* Add to TOTAL enough space to hold the converted arguments. */
2343
2344 n = 0;
2345 while (format != end)
2346 if (*format++ == '%')
2347 {
2348 int minlen, thissize = 0;
2349 unsigned char *this_format_start = format - 1;
2350
2351 /* Process a numeric arg and skip it. */
2352 minlen = atoi (format);
2353 if (minlen < 0)
2354 minlen = - minlen;
2355
2356 while ((*format >= '0' && *format <= '9')
2357 || *format == '-' || *format == ' ' || *format == '.')
2358 format++;
2359
2360 if (format - this_format_start + 1 > longest_format)
2361 longest_format = format - this_format_start + 1;
2362
2363 if (*format == '%')
2364 format++;
2365 else if (++n >= nargs)
2366 error ("Not enough arguments for format string");
2367 else if (*format == 'S')
2368 {
2369 /* For `S', prin1 the argument and then treat like a string. */
2370 register Lisp_Object tem;
2371 tem = Fprin1_to_string (args[n], Qnil);
2372 if (STRING_MULTIBYTE (tem) && ! multibyte)
2373 {
2374 multibyte = 1;
2375 goto retry;
2376 }
2377 args[n] = tem;
2378 goto string;
2379 }
2380 else if (SYMBOLP (args[n]))
2381 {
2382 XSETSTRING (args[n], XSYMBOL (args[n])->name);
2383 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
2384 {
2385 multibyte = 1;
2386 goto retry;
2387 }
2388 goto string;
2389 }
2390 else if (STRINGP (args[n]))
2391 {
2392 string:
2393 if (*format != 's' && *format != 'S')
2394 error ("format specifier doesn't match argument type");
2395 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
2396 }
2397 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
2398 else if (INTEGERP (args[n]) && *format != 's')
2399 {
2400 #ifdef LISP_FLOAT_TYPE
2401 /* The following loop assumes the Lisp type indicates
2402 the proper way to pass the argument.
2403 So make sure we have a flonum if the argument should
2404 be a double. */
2405 if (*format == 'e' || *format == 'f' || *format == 'g')
2406 args[n] = Ffloat (args[n]);
2407 #endif
2408 thissize = 30;
2409 if (*format == 'c'
2410 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
2411 || XINT (args[n]) == 0))
2412 {
2413 if (! multibyte)
2414 {
2415 multibyte = 1;
2416 goto retry;
2417 }
2418 args[n] = Fchar_to_string (args[n]);
2419 thissize = STRING_BYTES (XSTRING (args[n]));
2420 }
2421 }
2422 #ifdef LISP_FLOAT_TYPE
2423 else if (FLOATP (args[n]) && *format != 's')
2424 {
2425 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
2426 args[n] = Ftruncate (args[n], Qnil);
2427 thissize = 60;
2428 }
2429 #endif
2430 else
2431 {
2432 /* Anything but a string, convert to a string using princ. */
2433 register Lisp_Object tem;
2434 tem = Fprin1_to_string (args[n], Qt);
2435 if (STRING_MULTIBYTE (tem) & ! multibyte)
2436 {
2437 multibyte = 1;
2438 goto retry;
2439 }
2440 args[n] = tem;
2441 goto string;
2442 }
2443
2444 if (thissize < minlen)
2445 thissize = minlen;
2446
2447 total += thissize + 4;
2448 }
2449
2450 /* Now we can no longer jump to retry.
2451 TOTAL and LONGEST_FORMAT are known for certain. */
2452
2453 this_format = (unsigned char *) alloca (longest_format + 1);
2454
2455 /* Allocate the space for the result.
2456 Note that TOTAL is an overestimate. */
2457 if (total < 1000)
2458 buf = (unsigned char *) alloca (total + 1);
2459 else
2460 buf = (unsigned char *) xmalloc (total + 1);
2461
2462 p = buf;
2463 nchars = 0;
2464 n = 0;
2465
2466 /* Scan the format and store result in BUF. */
2467 format = XSTRING (args[0])->data;
2468 while (format != end)
2469 {
2470 if (*format == '%')
2471 {
2472 int minlen;
2473 int negative = 0;
2474 unsigned char *this_format_start = format;
2475
2476 format++;
2477
2478 /* Process a numeric arg and skip it. */
2479 minlen = atoi (format);
2480 if (minlen < 0)
2481 minlen = - minlen, negative = 1;
2482
2483 while ((*format >= '0' && *format <= '9')
2484 || *format == '-' || *format == ' ' || *format == '.')
2485 format++;
2486
2487 if (*format++ == '%')
2488 {
2489 *p++ = '%';
2490 nchars++;
2491 continue;
2492 }
2493
2494 ++n;
2495
2496 if (STRINGP (args[n]))
2497 {
2498 int padding, nbytes;
2499 int width = strwidth (XSTRING (args[n])->data,
2500 STRING_BYTES (XSTRING (args[n])));
2501
2502 /* If spec requires it, pad on right with spaces. */
2503 padding = minlen - width;
2504 if (! negative)
2505 while (padding-- > 0)
2506 {
2507 *p++ = ' ';
2508 nchars++;
2509 }
2510
2511 nbytes = copy_text (XSTRING (args[n])->data, p,
2512 STRING_BYTES (XSTRING (args[n])),
2513 STRING_MULTIBYTE (args[n]), multibyte);
2514 p += nbytes;
2515 nchars += XSTRING (args[n])->size;
2516
2517 if (negative)
2518 while (padding-- > 0)
2519 {
2520 *p++ = ' ';
2521 nchars++;
2522 }
2523 }
2524 else if (INTEGERP (args[n]) || FLOATP (args[n]))
2525 {
2526 int this_nchars;
2527
2528 bcopy (this_format_start, this_format,
2529 format - this_format_start);
2530 this_format[format - this_format_start] = 0;
2531
2532 if (INTEGERP (args[n]))
2533 sprintf (p, this_format, XINT (args[n]));
2534 else
2535 sprintf (p, this_format, XFLOAT (args[n])->data);
2536
2537 this_nchars = strlen (p);
2538 p += this_nchars;
2539 nchars += this_nchars;
2540 }
2541 }
2542 else if (STRING_MULTIBYTE (args[0]))
2543 {
2544 /* Copy a whole multibyte character. */
2545 *p++ = *format++;
2546 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
2547 nchars++;
2548 }
2549 else if (multibyte)
2550 {
2551 /* Convert a single-byte character to multibyte. */
2552 int len = copy_text (format, p, 1, 0, 1);
2553
2554 p += len;
2555 format++;
2556 nchars++;
2557 }
2558 else
2559 *p++ = *format++, nchars++;
2560 }
2561
2562 val = make_specified_string (buf, nchars, p - buf, multibyte);
2563
2564 /* If we allocated BUF with malloc, free it too. */
2565 if (total >= 1000)
2566 xfree (buf);
2567
2568 return val;
2569 }
2570
2571 /* VARARGS 1 */
2572 Lisp_Object
2573 #ifdef NO_ARG_ARRAY
2574 format1 (string1, arg0, arg1, arg2, arg3, arg4)
2575 EMACS_INT arg0, arg1, arg2, arg3, arg4;
2576 #else
2577 format1 (string1)
2578 #endif
2579 char *string1;
2580 {
2581 char buf[100];
2582 #ifdef NO_ARG_ARRAY
2583 EMACS_INT args[5];
2584 args[0] = arg0;
2585 args[1] = arg1;
2586 args[2] = arg2;
2587 args[3] = arg3;
2588 args[4] = arg4;
2589 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
2590 #else
2591 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
2592 #endif
2593 return build_string (buf);
2594 }
2595 \f
2596 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
2597 "Return t if two characters match, optionally ignoring case.\n\
2598 Both arguments must be characters (i.e. integers).\n\
2599 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
2600 (c1, c2)
2601 register Lisp_Object c1, c2;
2602 {
2603 int i1, i2;
2604 CHECK_NUMBER (c1, 0);
2605 CHECK_NUMBER (c2, 1);
2606
2607 if (XINT (c1) == XINT (c2))
2608 return Qt;
2609 if (NILP (current_buffer->case_fold_search))
2610 return Qnil;
2611
2612 /* Do these in separate statements,
2613 then compare the variables.
2614 because of the way DOWNCASE uses temp variables. */
2615 i1 = DOWNCASE (XFASTINT (c1));
2616 i2 = DOWNCASE (XFASTINT (c2));
2617 return (i1 == i2 ? Qt : Qnil);
2618 }
2619 \f
2620 /* Transpose the markers in two regions of the current buffer, and
2621 adjust the ones between them if necessary (i.e.: if the regions
2622 differ in size).
2623
2624 START1, END1 are the character positions of the first region.
2625 START1_BYTE, END1_BYTE are the byte positions.
2626 START2, END2 are the character positions of the second region.
2627 START2_BYTE, END2_BYTE are the byte positions.
2628
2629 Traverses the entire marker list of the buffer to do so, adding an
2630 appropriate amount to some, subtracting from some, and leaving the
2631 rest untouched. Most of this is copied from adjust_markers in insdel.c.
2632
2633 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
2634
2635 void
2636 transpose_markers (start1, end1, start2, end2,
2637 start1_byte, end1_byte, start2_byte, end2_byte)
2638 register int start1, end1, start2, end2;
2639 register int start1_byte, end1_byte, start2_byte, end2_byte;
2640 {
2641 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
2642 register Lisp_Object marker;
2643
2644 /* Update point as if it were a marker. */
2645 if (PT < start1)
2646 ;
2647 else if (PT < end1)
2648 TEMP_SET_PT_BOTH (PT + (end2 - end1),
2649 PT_BYTE + (end2_byte - end1_byte));
2650 else if (PT < start2)
2651 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
2652 (PT_BYTE + (end2_byte - start2_byte)
2653 - (end1_byte - start1_byte)));
2654 else if (PT < end2)
2655 TEMP_SET_PT_BOTH (PT - (start2 - start1),
2656 PT_BYTE - (start2_byte - start1_byte));
2657
2658 /* We used to adjust the endpoints here to account for the gap, but that
2659 isn't good enough. Even if we assume the caller has tried to move the
2660 gap out of our way, it might still be at start1 exactly, for example;
2661 and that places it `inside' the interval, for our purposes. The amount
2662 of adjustment is nontrivial if there's a `denormalized' marker whose
2663 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
2664 the dirty work to Fmarker_position, below. */
2665
2666 /* The difference between the region's lengths */
2667 diff = (end2 - start2) - (end1 - start1);
2668 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
2669
2670 /* For shifting each marker in a region by the length of the other
2671 region plus the distance between the regions. */
2672 amt1 = (end2 - start2) + (start2 - end1);
2673 amt2 = (end1 - start1) + (start2 - end1);
2674 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
2675 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
2676
2677 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
2678 marker = XMARKER (marker)->chain)
2679 {
2680 mpos = marker_byte_position (marker);
2681 if (mpos >= start1_byte && mpos < end2_byte)
2682 {
2683 if (mpos < end1_byte)
2684 mpos += amt1_byte;
2685 else if (mpos < start2_byte)
2686 mpos += diff_byte;
2687 else
2688 mpos -= amt2_byte;
2689 XMARKER (marker)->bytepos = mpos;
2690 }
2691 mpos = XMARKER (marker)->charpos;
2692 if (mpos >= start1 && mpos < end2)
2693 {
2694 if (mpos < end1)
2695 mpos += amt1;
2696 else if (mpos < start2)
2697 mpos += diff;
2698 else
2699 mpos -= amt2;
2700 }
2701 XMARKER (marker)->charpos = mpos;
2702 }
2703 }
2704
2705 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
2706 "Transpose region START1 to END1 with START2 to END2.\n\
2707 The regions may not be overlapping, because the size of the buffer is\n\
2708 never changed in a transposition.\n\
2709 \n\
2710 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
2711 any markers that happen to be located in the regions.\n\
2712 \n\
2713 Transposing beyond buffer boundaries is an error.")
2714 (startr1, endr1, startr2, endr2, leave_markers)
2715 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
2716 {
2717 register int start1, end1, start2, end2;
2718 int start1_byte, start2_byte, len1_byte, len2_byte;
2719 int gap, len1, len_mid, len2;
2720 unsigned char *start1_addr, *start2_addr, *temp;
2721 int combined_before_bytes_1, combined_after_bytes_1;
2722 int combined_before_bytes_2, combined_after_bytes_2;
2723 struct gcpro gcpro1, gcpro2;
2724
2725 #ifdef USE_TEXT_PROPERTIES
2726 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
2727 cur_intv = BUF_INTERVALS (current_buffer);
2728 #endif /* USE_TEXT_PROPERTIES */
2729
2730 validate_region (&startr1, &endr1);
2731 validate_region (&startr2, &endr2);
2732
2733 start1 = XFASTINT (startr1);
2734 end1 = XFASTINT (endr1);
2735 start2 = XFASTINT (startr2);
2736 end2 = XFASTINT (endr2);
2737 gap = GPT;
2738
2739 /* Swap the regions if they're reversed. */
2740 if (start2 < end1)
2741 {
2742 register int glumph = start1;
2743 start1 = start2;
2744 start2 = glumph;
2745 glumph = end1;
2746 end1 = end2;
2747 end2 = glumph;
2748 }
2749
2750 len1 = end1 - start1;
2751 len2 = end2 - start2;
2752
2753 if (start2 < end1)
2754 error ("Transposed regions overlap");
2755 else if (start1 == end1 || start2 == end2)
2756 error ("Transposed region has length 0");
2757
2758 /* The possibilities are:
2759 1. Adjacent (contiguous) regions, or separate but equal regions
2760 (no, really equal, in this case!), or
2761 2. Separate regions of unequal size.
2762
2763 The worst case is usually No. 2. It means that (aside from
2764 potential need for getting the gap out of the way), there also
2765 needs to be a shifting of the text between the two regions. So
2766 if they are spread far apart, we are that much slower... sigh. */
2767
2768 /* It must be pointed out that the really studly thing to do would
2769 be not to move the gap at all, but to leave it in place and work
2770 around it if necessary. This would be extremely efficient,
2771 especially considering that people are likely to do
2772 transpositions near where they are working interactively, which
2773 is exactly where the gap would be found. However, such code
2774 would be much harder to write and to read. So, if you are
2775 reading this comment and are feeling squirrely, by all means have
2776 a go! I just didn't feel like doing it, so I will simply move
2777 the gap the minimum distance to get it out of the way, and then
2778 deal with an unbroken array. */
2779
2780 /* Make sure the gap won't interfere, by moving it out of the text
2781 we will operate on. */
2782 if (start1 < gap && gap < end2)
2783 {
2784 if (gap - start1 < end2 - gap)
2785 move_gap (start1);
2786 else
2787 move_gap (end2);
2788 }
2789
2790 start1_byte = CHAR_TO_BYTE (start1);
2791 start2_byte = CHAR_TO_BYTE (start2);
2792 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
2793 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
2794
2795 if (end1 == start2)
2796 {
2797 combined_before_bytes_2
2798 = count_combining_before (BYTE_POS_ADDR (start2_byte),
2799 len2_byte, start1, start1_byte);
2800 combined_before_bytes_1
2801 = count_combining_before (BYTE_POS_ADDR (start1_byte),
2802 len1_byte, end2, start2_byte + len2_byte);
2803 combined_after_bytes_1
2804 = count_combining_after (BYTE_POS_ADDR (start1_byte),
2805 len1_byte, end2, start2_byte + len2_byte);
2806 combined_after_bytes_2 = 0;
2807 }
2808 else
2809 {
2810 combined_before_bytes_2
2811 = count_combining_before (BYTE_POS_ADDR (start2_byte),
2812 len2_byte, start1, start1_byte);
2813 combined_before_bytes_1
2814 = count_combining_before (BYTE_POS_ADDR (start1_byte),
2815 len1_byte, start2, start2_byte);
2816 combined_after_bytes_2
2817 = count_combining_after (BYTE_POS_ADDR (start2_byte),
2818 len2_byte, end1, start1_byte + len1_byte);
2819 combined_after_bytes_1
2820 = count_combining_after (BYTE_POS_ADDR (start1_byte),
2821 len1_byte, end2, start2_byte + len2_byte);
2822 }
2823
2824 /* If any combining is going to happen, do this the stupid way,
2825 because replace handles combining properly. */
2826 if (combined_before_bytes_1 || combined_before_bytes_2
2827 || combined_after_bytes_1 || combined_after_bytes_2)
2828 {
2829 Lisp_Object text1, text2;
2830
2831 text1 = text2 = Qnil;
2832 GCPRO2 (text1, text2);
2833
2834 text1 = make_buffer_string_both (start1, start1_byte,
2835 end1, start1_byte + len1_byte, 1);
2836 text2 = make_buffer_string_both (start2, start2_byte,
2837 end2, start2_byte + len2_byte, 1);
2838
2839 transpose_markers (start1, end1, start2, end2,
2840 start1_byte, start1_byte + len1_byte,
2841 start2_byte, start2_byte + len2_byte);
2842
2843 replace_range (start2, end2, text1, 1, 0, 1);
2844 replace_range (start1, end1, text2, 1, 0, 1);
2845
2846 UNGCPRO;
2847 return Qnil;
2848 }
2849
2850 /* Hmmm... how about checking to see if the gap is large
2851 enough to use as the temporary storage? That would avoid an
2852 allocation... interesting. Later, don't fool with it now. */
2853
2854 /* Working without memmove, for portability (sigh), so must be
2855 careful of overlapping subsections of the array... */
2856
2857 if (end1 == start2) /* adjacent regions */
2858 {
2859 modify_region (current_buffer, start1, end2);
2860 record_change (start1, len1 + len2);
2861
2862 #ifdef USE_TEXT_PROPERTIES
2863 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2864 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2865 Fset_text_properties (make_number (start1), make_number (end2),
2866 Qnil, Qnil);
2867 #endif /* USE_TEXT_PROPERTIES */
2868
2869 /* First region smaller than second. */
2870 if (len1_byte < len2_byte)
2871 {
2872 /* We use alloca only if it is small,
2873 because we want to avoid stack overflow. */
2874 if (len2_byte > 20000)
2875 temp = (unsigned char *) xmalloc (len2_byte);
2876 else
2877 temp = (unsigned char *) alloca (len2_byte);
2878
2879 /* Don't precompute these addresses. We have to compute them
2880 at the last minute, because the relocating allocator might
2881 have moved the buffer around during the xmalloc. */
2882 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1_byte);
2883 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2_byte);
2884
2885 bcopy (start2_addr, temp, len2_byte);
2886 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
2887 bcopy (temp, start1_addr, len2_byte);
2888 if (len2_byte > 20000)
2889 free (temp);
2890 }
2891 else
2892 /* First region not smaller than second. */
2893 {
2894 if (len1_byte > 20000)
2895 temp = (unsigned char *) xmalloc (len1_byte);
2896 else
2897 temp = (unsigned char *) alloca (len1_byte);
2898 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1_byte);
2899 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2_byte);
2900 bcopy (start1_addr, temp, len1_byte);
2901 bcopy (start2_addr, start1_addr, len2_byte);
2902 bcopy (temp, start1_addr + len2_byte, len1_byte);
2903 if (len1_byte > 20000)
2904 free (temp);
2905 }
2906 #ifdef USE_TEXT_PROPERTIES
2907 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
2908 len1, current_buffer, 0);
2909 graft_intervals_into_buffer (tmp_interval2, start1,
2910 len2, current_buffer, 0);
2911 #endif /* USE_TEXT_PROPERTIES */
2912 }
2913 /* Non-adjacent regions, because end1 != start2, bleagh... */
2914 else
2915 {
2916 len_mid = start2_byte - (start1_byte + len1_byte);
2917
2918 if (len1_byte == len2_byte)
2919 /* Regions are same size, though, how nice. */
2920 {
2921 modify_region (current_buffer, start1, end1);
2922 modify_region (current_buffer, start2, end2);
2923 record_change (start1, len1);
2924 record_change (start2, len2);
2925 #ifdef USE_TEXT_PROPERTIES
2926 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2927 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2928 Fset_text_properties (make_number (start1), make_number (end1),
2929 Qnil, Qnil);
2930 Fset_text_properties (make_number (start2), make_number (end2),
2931 Qnil, Qnil);
2932 #endif /* USE_TEXT_PROPERTIES */
2933
2934 if (len1_byte > 20000)
2935 temp = (unsigned char *) xmalloc (len1_byte);
2936 else
2937 temp = (unsigned char *) alloca (len1_byte);
2938 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1_byte);
2939 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2_byte);
2940 bcopy (start1_addr, temp, len1_byte);
2941 bcopy (start2_addr, start1_addr, len2_byte);
2942 bcopy (temp, start2_addr, len1_byte);
2943 if (len1_byte > 20000)
2944 free (temp);
2945 #ifdef USE_TEXT_PROPERTIES
2946 graft_intervals_into_buffer (tmp_interval1, start2,
2947 len1, current_buffer, 0);
2948 graft_intervals_into_buffer (tmp_interval2, start1,
2949 len2, current_buffer, 0);
2950 #endif /* USE_TEXT_PROPERTIES */
2951 }
2952
2953 else if (len1_byte < len2_byte) /* Second region larger than first */
2954 /* Non-adjacent & unequal size, area between must also be shifted. */
2955 {
2956 modify_region (current_buffer, start1, end2);
2957 record_change (start1, (end2 - start1));
2958 #ifdef USE_TEXT_PROPERTIES
2959 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2960 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
2961 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2962 Fset_text_properties (make_number (start1), make_number (end2),
2963 Qnil, Qnil);
2964 #endif /* USE_TEXT_PROPERTIES */
2965
2966 /* holds region 2 */
2967 if (len2_byte > 20000)
2968 temp = (unsigned char *) xmalloc (len2_byte);
2969 else
2970 temp = (unsigned char *) alloca (len2_byte);
2971 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1_byte);
2972 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2_byte);
2973 bcopy (start2_addr, temp, len2_byte);
2974 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
2975 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
2976 bcopy (temp, start1_addr, len2_byte);
2977 if (len2_byte > 20000)
2978 free (temp);
2979 #ifdef USE_TEXT_PROPERTIES
2980 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
2981 len1, current_buffer, 0);
2982 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
2983 len_mid, current_buffer, 0);
2984 graft_intervals_into_buffer (tmp_interval2, start1,
2985 len2, current_buffer, 0);
2986 #endif /* USE_TEXT_PROPERTIES */
2987 }
2988 else
2989 /* Second region smaller than first. */
2990 {
2991 record_change (start1, (end2 - start1));
2992 modify_region (current_buffer, start1, end2);
2993
2994 #ifdef USE_TEXT_PROPERTIES
2995 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2996 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
2997 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2998 Fset_text_properties (make_number (start1), make_number (end2),
2999 Qnil, Qnil);
3000 #endif /* USE_TEXT_PROPERTIES */
3001
3002 /* holds region 1 */
3003 if (len1_byte > 20000)
3004 temp = (unsigned char *) xmalloc (len1_byte);
3005 else
3006 temp = (unsigned char *) alloca (len1_byte);
3007 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1_byte);
3008 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2_byte);
3009 bcopy (start1_addr, temp, len1_byte);
3010 bcopy (start2_addr, start1_addr, len2_byte);
3011 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3012 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3013 if (len1_byte > 20000)
3014 free (temp);
3015 #ifdef USE_TEXT_PROPERTIES
3016 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3017 len1, current_buffer, 0);
3018 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3019 len_mid, current_buffer, 0);
3020 graft_intervals_into_buffer (tmp_interval2, start1,
3021 len2, current_buffer, 0);
3022 #endif /* USE_TEXT_PROPERTIES */
3023 }
3024 }
3025
3026 /* When doing multiple transpositions, it might be nice
3027 to optimize this. Perhaps the markers in any one buffer
3028 should be organized in some sorted data tree. */
3029 if (NILP (leave_markers))
3030 {
3031 transpose_markers (start1, end1, start2, end2,
3032 start1_byte, start1_byte + len1_byte,
3033 start2_byte, start2_byte + len2_byte);
3034 fix_overlays_in_range (start1, end2);
3035 }
3036
3037 return Qnil;
3038 }
3039
3040 \f
3041 void
3042 syms_of_editfns ()
3043 {
3044 environbuf = 0;
3045
3046 Qbuffer_access_fontify_functions
3047 = intern ("buffer-access-fontify-functions");
3048 staticpro (&Qbuffer_access_fontify_functions);
3049
3050 DEFVAR_LISP ("buffer-access-fontify-functions",
3051 &Vbuffer_access_fontify_functions,
3052 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3053 Each function is called with two arguments which specify the range\n\
3054 of the buffer being accessed.");
3055 Vbuffer_access_fontify_functions = Qnil;
3056
3057 {
3058 Lisp_Object obuf;
3059 extern Lisp_Object Vprin1_to_string_buffer;
3060 obuf = Fcurrent_buffer ();
3061 /* Do this here, because init_buffer_once is too early--it won't work. */
3062 Fset_buffer (Vprin1_to_string_buffer);
3063 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3064 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3065 Qnil);
3066 Fset_buffer (obuf);
3067 }
3068
3069 DEFVAR_LISP ("buffer-access-fontified-property",
3070 &Vbuffer_access_fontified_property,
3071 "Property which (if non-nil) indicates text has been fontified.\n\
3072 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3073 functions if all the text being accessed has this property.");
3074 Vbuffer_access_fontified_property = Qnil;
3075
3076 DEFVAR_LISP ("system-name", &Vsystem_name,
3077 "The name of the machine Emacs is running on.");
3078
3079 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3080 "The full name of the user logged in.");
3081
3082 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3083 "The user's name, taken from environment variables if possible.");
3084
3085 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3086 "The user's name, based upon the real uid only.");
3087
3088 defsubr (&Schar_equal);
3089 defsubr (&Sgoto_char);
3090 defsubr (&Sstring_to_char);
3091 defsubr (&Schar_to_string);
3092 defsubr (&Sbuffer_substring);
3093 defsubr (&Sbuffer_substring_no_properties);
3094 defsubr (&Sbuffer_string);
3095
3096 defsubr (&Spoint_marker);
3097 defsubr (&Smark_marker);
3098 defsubr (&Spoint);
3099 defsubr (&Sregion_beginning);
3100 defsubr (&Sregion_end);
3101
3102 defsubr (&Sline_beginning_position);
3103 defsubr (&Sline_end_position);
3104
3105 /* defsubr (&Smark); */
3106 /* defsubr (&Sset_mark); */
3107 defsubr (&Ssave_excursion);
3108 defsubr (&Ssave_current_buffer);
3109
3110 defsubr (&Sbufsize);
3111 defsubr (&Spoint_max);
3112 defsubr (&Spoint_min);
3113 defsubr (&Spoint_min_marker);
3114 defsubr (&Spoint_max_marker);
3115 defsubr (&Sgap_position);
3116 defsubr (&Sgap_size);
3117 defsubr (&Sposition_bytes);
3118
3119 defsubr (&Sbobp);
3120 defsubr (&Seobp);
3121 defsubr (&Sbolp);
3122 defsubr (&Seolp);
3123 defsubr (&Sfollowing_char);
3124 defsubr (&Sprevious_char);
3125 defsubr (&Schar_after);
3126 defsubr (&Schar_before);
3127 defsubr (&Sinsert);
3128 defsubr (&Sinsert_before_markers);
3129 defsubr (&Sinsert_and_inherit);
3130 defsubr (&Sinsert_and_inherit_before_markers);
3131 defsubr (&Sinsert_char);
3132
3133 defsubr (&Suser_login_name);
3134 defsubr (&Suser_real_login_name);
3135 defsubr (&Suser_uid);
3136 defsubr (&Suser_real_uid);
3137 defsubr (&Suser_full_name);
3138 defsubr (&Semacs_pid);
3139 defsubr (&Scurrent_time);
3140 defsubr (&Sformat_time_string);
3141 defsubr (&Sdecode_time);
3142 defsubr (&Sencode_time);
3143 defsubr (&Scurrent_time_string);
3144 defsubr (&Scurrent_time_zone);
3145 defsubr (&Sset_time_zone_rule);
3146 defsubr (&Ssystem_name);
3147 defsubr (&Smessage);
3148 defsubr (&Smessage_box);
3149 defsubr (&Smessage_or_box);
3150 defsubr (&Scurrent_message);
3151 defsubr (&Sformat);
3152
3153 defsubr (&Sinsert_buffer_substring);
3154 defsubr (&Scompare_buffer_substrings);
3155 defsubr (&Ssubst_char_in_region);
3156 defsubr (&Stranslate_region);
3157 defsubr (&Sdelete_region);
3158 defsubr (&Swiden);
3159 defsubr (&Snarrow_to_region);
3160 defsubr (&Ssave_restriction);
3161 defsubr (&Stranspose_regions);
3162 }