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