* url-util.el (url-insert-entities-in-string):
[bpt/emacs.git] / lisp / emulation / viper-util.el
1 ;;; viper-util.el --- Utilities used by viper.el
2
3 ;; Copyright (C) 1994, 1995, 1996, 1997, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 ;; Author: Michael Kifer <kifer@cs.stonybrook.edu>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (provide 'viper-util)
28
29
30 ;; Compiler pacifier
31 (defvar viper-overriding-map)
32 (defvar pm-color-alist)
33 (defvar viper-minibuffer-current-face)
34 (defvar viper-minibuffer-insert-face)
35 (defvar viper-minibuffer-vi-face)
36 (defvar viper-minibuffer-emacs-face)
37 (defvar viper-replace-overlay-face)
38 (defvar viper-fast-keyseq-timeout)
39 (defvar ex-unix-type-shell)
40 (defvar ex-unix-type-shell-options)
41 (defvar viper-ex-tmp-buf-name)
42 (defvar viper-syntax-preference)
43 (defvar viper-saved-mark)
44
45 (require 'ring)
46
47 (eval-and-compile
48 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
49
50 ;; end pacifier
51
52 (require 'viper-init)
53
54
55 \f
56 (defalias 'viper-overlay-p
57 (if (featurep 'xemacs) 'extentp 'overlayp))
58 (defalias 'viper-make-overlay
59 (if (featurep 'xemacs) 'make-extent 'make-overlay))
60 (defalias 'viper-overlay-live-p
61 (if (featurep 'xemacs) 'extent-live-p 'overlayp))
62 (defalias 'viper-move-overlay
63 (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay))
64 (defalias 'viper-overlay-start
65 (if (featurep 'xemacs) 'extent-start-position 'overlay-start))
66 (defalias 'viper-overlay-end
67 (if (featurep 'xemacs) 'extent-end-position 'overlay-end))
68 (defalias 'viper-overlay-get
69 (if (featurep 'xemacs) 'extent-property 'overlay-get))
70 (defalias 'viper-overlay-put
71 (if (featurep 'xemacs) 'set-extent-property 'overlay-put))
72 (defalias 'viper-read-event
73 (if (featurep 'xemacs) 'next-command-event 'read-event))
74 (defalias 'viper-characterp
75 (if (featurep 'xemacs) 'characterp 'integerp))
76 (defalias 'viper-int-to-char
77 (if (featurep 'xemacs) 'int-to-char 'identity))
78 (defalias 'viper-get-face
79 (if (featurep 'xemacs) 'get-face 'internal-get-face))
80 (defalias 'viper-color-defined-p
81 (if (featurep 'xemacs) 'valid-color-name-p 'x-color-defined-p))
82 (defalias 'viper-iconify
83 (if (featurep 'xemacs) 'iconify-frame 'iconify-or-deiconify-frame))
84
85
86 ;; CHAR is supposed to be a char or an integer (positive or negative)
87 ;; LIST is a list of chars, nil, and negative numbers
88 ;; Check if CHAR is a member by trying to convert in characters, if necessary.
89 ;; Introduced for compatibility with XEmacs, where integers are not the same as
90 ;; chars.
91 (defun viper-memq-char (char list)
92 (cond ((and (integerp char) (>= char 0))
93 (memq (viper-int-to-char char) list))
94 ((memq char list))))
95
96 ;; Check if char-or-int and char are the same as characters
97 (defun viper-char-equal (char-or-int char)
98 (cond ((and (integerp char-or-int) (>= char-or-int 0))
99 (= (viper-int-to-char char-or-int) char))
100 ((eq char-or-int char))))
101
102 ;; Like =, but accommodates null and also is t for eq-objects
103 (defun viper= (char char1)
104 (cond ((eq char char1) t)
105 ((and (viper-characterp char) (viper-characterp char1))
106 (= char char1))
107 (t nil)))
108
109 (defsubst viper-color-display-p ()
110 (if (featurep 'xemacs) (eq (device-class (selected-device)) 'color)
111 (x-display-color-p)))
112
113 (defun viper-get-cursor-color (&optional frame)
114 (if (featurep 'xemacs)
115 (color-instance-name
116 (frame-property (or frame (selected-frame)) 'cursor-color))
117 (cdr (assoc 'cursor-color (frame-parameters)))))
118
119 (defmacro viper-frame-value (variable)
120 "Return the value of VARIABLE local to the current frame, if there is one.
121 Otherwise return the normal value."
122 `(if (featurep 'xemacs)
123 ,variable
124 ;; Frame-local variables are obsolete from Emacs 22.2 onwards,
125 ;; so we do it by hand instead.
126 ;; Buffer-local values take precedence over frame-local ones.
127 (if (local-variable-p ',variable)
128 ,variable
129 ;; Distinguish between no frame parameter and a frame parameter
130 ;; with a value of nil.
131 (let ((fp (assoc ',variable (frame-parameters))))
132 (if fp (cdr fp)
133 ,variable)))))
134
135 ;; OS/2
136 (cond ((eq (viper-device-type) 'pm)
137 (fset 'viper-color-defined-p
138 (lambda (color) (assoc color pm-color-alist)))))
139
140
141 ;; cursor colors
142 (defun viper-change-cursor-color (new-color &optional frame)
143 (if (and (viper-window-display-p) (viper-color-display-p)
144 (stringp new-color) (viper-color-defined-p new-color)
145 (not (string= new-color (viper-get-cursor-color))))
146 (if (featurep 'xemacs)
147 (set-frame-property
148 (or frame (selected-frame))
149 'cursor-color (make-color-instance new-color))
150 (modify-frame-parameters
151 (or frame (selected-frame))
152 (list (cons 'cursor-color new-color))))))
153
154 ;; Note that the colors this function uses might not be those
155 ;; associated with FRAME, if there are frame-local values.
156 ;; This was equally true before the advent of viper-frame-value.
157 ;; Now it could be changed by passing frame to v-f-v.
158 (defun viper-set-cursor-color-according-to-state (&optional frame)
159 (cond ((eq viper-current-state 'replace-state)
160 (viper-change-cursor-color
161 (viper-frame-value viper-replace-overlay-cursor-color)
162 frame))
163 ((and (eq viper-current-state 'emacs-state)
164 (viper-frame-value viper-emacs-state-cursor-color))
165 (viper-change-cursor-color
166 (viper-frame-value viper-emacs-state-cursor-color)
167 frame))
168 ((eq viper-current-state 'insert-state)
169 (viper-change-cursor-color
170 (viper-frame-value viper-insert-state-cursor-color)
171 frame))
172 (t
173 (viper-change-cursor-color
174 (viper-frame-value viper-vi-state-cursor-color)
175 frame))))
176
177 ;; By default, saves current frame cursor color in the
178 ;; viper-saved-cursor-color-in-replace-mode property of viper-replace-overlay
179 (defun viper-save-cursor-color (before-which-mode)
180 (if (and (viper-window-display-p) (viper-color-display-p))
181 (let ((color (viper-get-cursor-color)))
182 (if (and (stringp color) (viper-color-defined-p color)
183 (not (string= color
184 (viper-frame-value
185 viper-replace-overlay-cursor-color))))
186 (modify-frame-parameters
187 (selected-frame)
188 (list
189 (cons
190 (cond ((eq before-which-mode 'before-replace-mode)
191 'viper-saved-cursor-color-in-replace-mode)
192 ((eq before-which-mode 'before-emacs-mode)
193 'viper-saved-cursor-color-in-emacs-mode)
194 (t
195 'viper-saved-cursor-color-in-insert-mode))
196 color)))))))
197
198
199 (defun viper-get-saved-cursor-color-in-replace-mode ()
200 (or
201 (funcall
202 (if (featurep 'emacs) 'frame-parameter 'frame-property)
203 (selected-frame)
204 'viper-saved-cursor-color-in-replace-mode)
205 (or (and (eq viper-current-state 'emacs-mode)
206 (viper-frame-value viper-emacs-state-cursor-color))
207 (viper-frame-value viper-vi-state-cursor-color))))
208
209 (defun viper-get-saved-cursor-color-in-insert-mode ()
210 (or
211 (funcall
212 (if (featurep 'emacs) 'frame-parameter 'frame-property)
213 (selected-frame)
214 'viper-saved-cursor-color-in-insert-mode)
215 (or (and (eq viper-current-state 'emacs-mode)
216 (viper-frame-value viper-emacs-state-cursor-color))
217 (viper-frame-value viper-vi-state-cursor-color))))
218
219 (defun viper-get-saved-cursor-color-in-emacs-mode ()
220 (or
221 (funcall
222 (if (featurep 'emacs) 'frame-parameter 'frame-property)
223 (selected-frame)
224 'viper-saved-cursor-color-in-emacs-mode)
225 (viper-frame-value viper-vi-state-cursor-color)))
226
227 ;; restore cursor color from replace overlay
228 (defun viper-restore-cursor-color(after-which-mode)
229 (if (viper-overlay-p viper-replace-overlay)
230 (viper-change-cursor-color
231 (cond ((eq after-which-mode 'after-replace-mode)
232 (viper-get-saved-cursor-color-in-replace-mode))
233 ((eq after-which-mode 'after-emacs-mode)
234 (viper-get-saved-cursor-color-in-emacs-mode))
235 (t (viper-get-saved-cursor-color-in-insert-mode)))
236 )))
237
238 \f
239 ;; Check the current version against the major and minor version numbers
240 ;; using op: cur-vers op major.minor If emacs-major-version or
241 ;; emacs-minor-version are not defined, we assume that the current version
242 ;; is hopelessly outdated. We assume that emacs-major-version and
243 ;; emacs-minor-version are defined. Otherwise, for Emacs/XEmacs 19, if the
244 ;; current minor version is < 10 (xemacs) or < 23 (emacs) the return value
245 ;; will be nil (when op is =, >, or >=) and t (when op is <, <=), which may be
246 ;; incorrect. However, this gives correct result in our cases, since we are
247 ;; testing for sufficiently high Emacs versions.
248 (defun viper-check-version (op major minor &optional type-of-emacs)
249 (if (and (boundp 'emacs-major-version) (boundp 'emacs-minor-version))
250 (and (cond ((eq type-of-emacs 'xemacs) (featurep 'xemacs))
251 ((eq type-of-emacs 'emacs) (featurep 'emacs))
252 (t t))
253 (cond ((eq op '=) (and (= emacs-minor-version minor)
254 (= emacs-major-version major)))
255 ((memq op '(> >= < <=))
256 (and (or (funcall op emacs-major-version major)
257 (= emacs-major-version major))
258 (if (= emacs-major-version major)
259 (funcall op emacs-minor-version minor)
260 t)))
261 (t
262 (error "%S: Invalid op in viper-check-version" op))))
263 (cond ((memq op '(= > >=)) nil)
264 ((memq op '(< <=)) t))))
265
266
267 (defun viper-get-visible-buffer-window (wind)
268 (if (featurep 'xemacs)
269 (get-buffer-window wind t)
270 (get-buffer-window wind 'visible)))
271
272
273 ;; Return line position.
274 ;; If pos is 'start then returns position of line start.
275 ;; If pos is 'end, returns line end. If pos is 'mid, returns line center.
276 ;; Pos = 'indent returns beginning of indentation.
277 ;; Otherwise, returns point. Current point is not moved in any case."
278 (defun viper-line-pos (pos)
279 (let ((cur-pos (point))
280 (result))
281 (cond
282 ((equal pos 'start)
283 (beginning-of-line))
284 ((equal pos 'end)
285 (end-of-line))
286 ((equal pos 'mid)
287 (goto-char (+ (viper-line-pos 'start) (viper-line-pos 'end) 2)))
288 ((equal pos 'indent)
289 (back-to-indentation))
290 (t nil))
291 (setq result (point))
292 (goto-char cur-pos)
293 result))
294
295 ;; Emacs used to count each multibyte character as several positions in the buffer,
296 ;; so we had to use Emacs' chars-in-region to count characters. Since 20.3,
297 ;; Emacs counts multibyte characters as 1 position. XEmacs has always been
298 ;; counting each char as just one pos. So, now we can simply subtract beg from
299 ;; end to determine the number of characters in a region.
300 (defun viper-chars-in-region (beg end &optional preserve-sign)
301 ;;(let ((count (abs (if (fboundp 'chars-in-region)
302 ;; (chars-in-region beg end)
303 ;; (- end beg)))))
304 (let ((count (abs (- end beg))))
305 (if (and (< end beg) preserve-sign)
306 (- count)
307 count)))
308
309 ;; Test if POS is between BEG and END
310 (defsubst viper-pos-within-region (pos beg end)
311 (and (>= pos (min beg end)) (>= (max beg end) pos)))
312
313
314 ;; Like move-marker but creates a virgin marker if arg isn't already a marker.
315 ;; The first argument must eval to a variable name.
316 ;; Arguments: (var-name position &optional buffer).
317 ;;
318 ;; This is useful for moving markers that are supposed to be local.
319 ;; For this, VAR-NAME should be made buffer-local with nil as a default.
320 ;; Then, each time this var is used in `viper-move-marker-locally' in a new
321 ;; buffer, a new marker will be created.
322 (defun viper-move-marker-locally (var pos &optional buffer)
323 (if (markerp (eval var))
324 ()
325 (set var (make-marker)))
326 (move-marker (eval var) pos buffer))
327
328
329 ;; Print CONDITIONS as a message.
330 (defun viper-message-conditions (conditions)
331 (let ((case (car conditions)) (msg (cdr conditions)))
332 (if (null msg)
333 (message "%s" case)
334 (message "%s: %s" case (mapconcat 'prin1-to-string msg " ")))
335 (beep 1)))
336
337
338 \f
339 ;;; List/alist utilities
340
341 ;; Convert LIST to an alist
342 (defun viper-list-to-alist (lst)
343 (let ((alist))
344 (while lst
345 (setq alist (cons (list (car lst)) alist))
346 (setq lst (cdr lst)))
347 alist))
348
349 ;; Convert ALIST to a list.
350 (defun viper-alist-to-list (alst)
351 (let ((lst))
352 (while alst
353 (setq lst (cons (car (car alst)) lst))
354 (setq alst (cdr alst)))
355 lst))
356
357 ;; Filter ALIST using REGEXP. Return alist whose elements match the regexp.
358 (defun viper-filter-alist (regexp alst)
359 (interactive "s x")
360 (let ((outalst) (inalst alst))
361 (while (car inalst)
362 (if (string-match regexp (car (car inalst)))
363 (setq outalst (cons (car inalst) outalst)))
364 (setq inalst (cdr inalst)))
365 outalst))
366
367 ;; Filter LIST using REGEXP. Return list whose elements match the regexp.
368 (defun viper-filter-list (regexp lst)
369 (interactive "s x")
370 (let ((outlst) (inlst lst))
371 (while (car inlst)
372 (if (string-match regexp (car inlst))
373 (setq outlst (cons (car inlst) outlst)))
374 (setq inlst (cdr inlst)))
375 outlst))
376
377
378 ;; Append LIS2 to LIS1, both alists, by side-effect and returns LIS1
379 ;; LIS2 is modified by filtering it: deleting its members of the form
380 ;; \(car elt\) such that (car elt') is in LIS1.
381 (defun viper-append-filter-alist (lis1 lis2)
382 (let ((temp lis1)
383 elt)
384 ;;filter-append the second list
385 (while temp
386 ;; delete all occurrences
387 (while (setq elt (assoc (car (car temp)) lis2))
388 (setq lis2 (delq elt lis2)))
389 (setq temp (cdr temp)))
390
391 (append lis1 lis2)))
392
393
394 \f
395 (declare-function viper-forward-Word "viper-cmd" (arg))
396
397 ;;; Support for :e, :r, :w file globbing
398
399 ;; Glob the file spec.
400 ;; This function is designed to work under Unix.
401 (defun viper-glob-unix-files (filespec)
402 (let ((gshell
403 (cond (ex-unix-type-shell shell-file-name)
404 (t "sh"))) ; probably Unix anyway
405 (gshell-options
406 ;; using cond in anticipation of further additions
407 (cond (ex-unix-type-shell-options)
408 ))
409 (command (cond (viper-ms-style-os-p (format "\"ls -1 -d %s\"" filespec))
410 (t (format "ls -1 -d %s" filespec))))
411 status)
412 (with-current-buffer (get-buffer-create viper-ex-tmp-buf-name)
413 (erase-buffer)
414 (setq status
415 (if gshell-options
416 (call-process gshell nil t nil
417 gshell-options
418 "-c"
419 command)
420 (call-process gshell nil t nil
421 "-c"
422 command)))
423 (goto-char (point-min))
424 ;; Issue an error, if no match.
425 (unless (eq 0 status)
426 (save-excursion
427 (skip-chars-forward " \t\n\j")
428 (if (looking-at "ls:")
429 (viper-forward-Word 1))
430 (error "%s: %s"
431 (if (stringp gshell)
432 gshell
433 "shell")
434 (buffer-substring (point) (viper-line-pos 'end)))
435 ))
436 (goto-char (point-min))
437 (viper-get-filenames-from-buffer 'one-per-line))
438 ))
439
440
441 ;; Interpret the stuff in the buffer as a list of file names
442 ;; return a list of file names listed in the buffer beginning at point
443 ;; If optional arg is supplied, assume each filename is listed on a separate
444 ;; line
445 (defun viper-get-filenames-from-buffer (&optional one-per-line)
446 (let ((skip-chars (if one-per-line "\t\n" " \t\n"))
447 result fname delim)
448 (skip-chars-forward skip-chars)
449 (while (not (eobp))
450 (if (cond ((looking-at "\"")
451 (setq delim ?\")
452 (re-search-forward "[^\"]+" nil t)) ; noerror
453 ((looking-at "'")
454 (setq delim ?')
455 (re-search-forward "[^']+" nil t)) ; noerror
456 (t
457 (re-search-forward
458 (concat "[^" skip-chars "]+") nil t))) ;noerror
459 (setq fname
460 (buffer-substring (match-beginning 0) (match-end 0))))
461 (if delim
462 (forward-char 1))
463 (skip-chars-forward " \t\n")
464 (setq result (cons fname result)))
465 result))
466
467 ;; convert MS-DOS wildcards to regexp
468 (defun viper-wildcard-to-regexp (wcard)
469 (with-current-buffer (get-buffer-create viper-ex-tmp-buf-name)
470 (erase-buffer)
471 (insert wcard)
472 (goto-char (point-min))
473 (while (not (eobp))
474 (skip-chars-forward "^*?.\\\\")
475 (cond ((eq (char-after (point)) ?*) (insert ".")(forward-char 1))
476 ((eq (char-after (point)) ?.) (insert "\\")(forward-char 1))
477 ((eq (char-after (point)) ?\\) (insert "\\")(forward-char 1))
478 ((eq (char-after (point)) ??) (delete-char 1)(insert ".")))
479 )
480 (buffer-string)
481 ))
482
483
484 ;; glob windows files
485 ;; LIST is expected to be in reverse order
486 (defun viper-glob-mswindows-files (filespec)
487 (let ((case-fold-search t)
488 tmp tmp2)
489 (with-current-buffer (get-buffer-create viper-ex-tmp-buf-name)
490 (erase-buffer)
491 (insert filespec)
492 (goto-char (point-min))
493 (setq tmp (viper-get-filenames-from-buffer))
494 (while tmp
495 (setq tmp2 (cons (directory-files
496 ;; the directory part
497 (or (file-name-directory (car tmp))
498 "")
499 t ; return full names
500 ;; the regexp part: globs the file names
501 (concat "^"
502 (viper-wildcard-to-regexp
503 (file-name-nondirectory (car tmp)))
504 "$"))
505 tmp2))
506 (setq tmp (cdr tmp)))
507 (reverse (apply 'append tmp2)))))
508
509 \f
510 ;;; Insertion ring
511
512 ;; Rotate RING's index. DIRection can be positive or negative.
513 (defun viper-ring-rotate1 (ring dir)
514 (if (and (ring-p ring) (> (ring-length ring) 0))
515 (progn
516 (setcar ring (cond ((> dir 0)
517 (ring-plus1 (car ring) (ring-length ring)))
518 ((< dir 0)
519 (ring-minus1 (car ring) (ring-length ring)))
520 ;; don't rotate if dir = 0
521 (t (car ring))))
522 (viper-current-ring-item ring)
523 )))
524
525 (defun viper-special-ring-rotate1 (ring dir)
526 (if (memq viper-intermediate-command
527 '(repeating-display-destructive-command
528 repeating-insertion-from-ring))
529 (viper-ring-rotate1 ring dir)
530 ;; don't rotate otherwise
531 (viper-ring-rotate1 ring 0)))
532
533 ;; current ring item; if N is given, then so many items back from the
534 ;; current
535 (defun viper-current-ring-item (ring &optional n)
536 (setq n (or n 0))
537 (if (and (ring-p ring) (> (ring-length ring) 0))
538 (aref (cdr (cdr ring)) (mod (- (car ring) 1 n) (ring-length ring)))))
539
540 ;; Push item onto ring. The second argument is a ring-variable, not value.
541 (defun viper-push-onto-ring (item ring-var)
542 (or (ring-p (eval ring-var))
543 (set ring-var (make-ring (eval (intern (format "%S-size" ring-var))))))
544 (or (null item) ; don't push nil
545 (and (stringp item) (string= item "")) ; or empty strings
546 (equal item (viper-current-ring-item (eval ring-var))) ; or old stuff
547 ;; Since viper-set-destructive-command checks if we are inside
548 ;; viper-repeat, we don't check whether this-command-keys is a `.'. The
549 ;; cmd viper-repeat makes a call to the current function only if `.' is
550 ;; executing a command from the command history. It doesn't call the
551 ;; push-onto-ring function if `.' is simply repeating the last
552 ;; destructive command. We only check for ESC (which happens when we do
553 ;; insert with a prefix argument, or if this-command-keys doesn't give
554 ;; anything meaningful (in that case we don't know what to show to the
555 ;; user).
556 (and (eq ring-var 'viper-command-ring)
557 (string-match "\\([0-9]*\e\\|^[ \t]*$\\|escape\\)"
558 (viper-array-to-string (this-command-keys))))
559 (viper-ring-insert (eval ring-var) item))
560 )
561
562
563 ;; removing elts from ring seems to break it
564 (defun viper-cleanup-ring (ring)
565 (or (< (ring-length ring) 2)
566 (null (viper-current-ring-item ring))
567 ;; last and previous equal
568 (if (equal (viper-current-ring-item ring)
569 (viper-current-ring-item ring 1))
570 (viper-ring-pop ring))))
571
572 ;; ring-remove seems to be buggy, so we concocted this for our purposes.
573 (defun viper-ring-pop (ring)
574 (let* ((ln (ring-length ring))
575 (vec (cdr (cdr ring)))
576 (veclen (length vec))
577 (hd (car ring))
578 (idx (max 0 (ring-minus1 hd ln)))
579 (top-elt (aref vec idx)))
580
581 ;; shift elements
582 (while (< (1+ idx) veclen)
583 (aset vec idx (aref vec (1+ idx)))
584 (setq idx (1+ idx)))
585 (aset vec idx nil)
586
587 (setq hd (max 0 (ring-minus1 hd ln)))
588 (if (= hd (1- ln)) (setq hd 0))
589 (setcar ring hd) ; move head
590 (setcar (cdr ring) (max 0 (1- ln))) ; adjust length
591 top-elt
592 ))
593
594 (defun viper-ring-insert (ring item)
595 (let* ((ln (ring-length ring))
596 (vec (cdr (cdr ring)))
597 (veclen (length vec))
598 (hd (car ring))
599 (vecpos-after-hd (if (= hd 0) ln hd))
600 (idx ln))
601
602 (if (= ln veclen)
603 (progn
604 (aset vec hd item) ; hd is always 1+ the actual head index in vec
605 (setcar ring (ring-plus1 hd ln)))
606 (setcar (cdr ring) (1+ ln))
607 (setcar ring (ring-plus1 vecpos-after-hd (1+ ln)))
608 (while (and (>= idx vecpos-after-hd) (> ln 0))
609 (aset vec idx (aref vec (1- idx)))
610 (setq idx (1- idx)))
611 (aset vec vecpos-after-hd item))
612 item))
613
614 \f
615 ;;; String utilities
616
617 ;; If STRING is longer than MAX-LEN, truncate it and print ...... instead
618 ;; PRE-STRING is a string to prepend to the abbrev string.
619 ;; POST-STRING is a string to append to the abbrev string.
620 ;; ABBREV_SIGN is a string to be inserted before POST-STRING
621 ;; if the orig string was truncated.
622 (defun viper-abbreviate-string (string max-len
623 pre-string post-string abbrev-sign)
624 (let (truncated-str)
625 (setq truncated-str
626 (if (stringp string)
627 (substring string 0 (min max-len (length string)))))
628 (cond ((null truncated-str) "")
629 ((> (length string) max-len)
630 (format "%s%s%s%s"
631 pre-string truncated-str abbrev-sign post-string))
632 (t (format "%s%s%s" pre-string truncated-str post-string)))))
633
634 ;; tells if we are over a whitespace-only line
635 (defsubst viper-over-whitespace-line ()
636 (save-excursion
637 (beginning-of-line)
638 (looking-at "^[ \t]*$")))
639
640 \f
641 ;;; Saving settings in custom file
642
643 ;; Save the current setting of VAR in CUSTOM-FILE.
644 ;; If given, MESSAGE is a message to be displayed after that.
645 ;; This message is erased after 2 secs, if erase-msg is non-nil.
646 ;; Arguments: var message custom-file &optional erase-message
647 (defun viper-save-setting (var message custom-file &optional erase-msg)
648 (let* ((var-name (symbol-name var))
649 (var-val (if (boundp var) (eval var)))
650 (regexp (format "^[^;]*%s[ \t\n]*[a-zA-Z---_']*[ \t\n)]" var-name))
651 (buf (find-file-noselect (substitute-in-file-name custom-file)))
652 )
653 (message "%s" (or message ""))
654 (with-current-buffer buf
655 (goto-char (point-min))
656 (if (re-search-forward regexp nil t)
657 (let ((reg-end (1- (match-end 0))))
658 (search-backward var-name)
659 (delete-region (match-beginning 0) reg-end)
660 (goto-char (match-beginning 0))
661 (insert (format "%s '%S" var-name var-val)))
662 (goto-char (point-max))
663 (if (not (bolp)) (insert "\n"))
664 (insert (format "(setq %s '%S)\n" var-name var-val)))
665 (save-buffer))
666 (kill-buffer buf)
667 (if erase-msg
668 (progn
669 (sit-for 2)
670 (message "")))
671 ))
672
673 ;; Save STRING in CUSTOM-FILE. If PATTERN is non-nil, remove strings that
674 ;; match this pattern.
675 (defun viper-save-string-in-file (string custom-file &optional pattern)
676 (let ((buf (find-file-noselect (substitute-in-file-name custom-file))))
677 (with-current-buffer buf
678 (let (buffer-read-only)
679 (goto-char (point-min))
680 (if pattern (delete-matching-lines pattern))
681 (goto-char (point-max))
682 (if string (insert string))
683 (save-buffer)))
684 (kill-buffer buf)
685 ))
686
687
688 ;; This is a simple-minded check for whether a file is under version control.
689 ;; If file,v exists but file doesn't, this file is considered to be not checked
690 ;; in and not checked out for the purpose of patching (since patch won't be
691 ;; able to read such a file anyway).
692 ;; FILE is a string representing file name
693 ;;(defun viper-file-under-version-control (file)
694 ;; (let* ((filedir (file-name-directory file))
695 ;; (file-nondir (file-name-nondirectory file))
696 ;; (trial (concat file-nondir ",v"))
697 ;; (full-trial (concat filedir trial))
698 ;; (full-rcs-trial (concat filedir "RCS/" trial)))
699 ;; (and (stringp file)
700 ;; (file-exists-p file)
701 ;; (or
702 ;; (and
703 ;; (file-exists-p full-trial)
704 ;; ;; in FAT FS, `file,v' and `file' may turn out to be the same!
705 ;; ;; don't be fooled by this!
706 ;; (not (equal (file-attributes file)
707 ;; (file-attributes full-trial))))
708 ;; ;; check if a version is in RCS/ directory
709 ;; (file-exists-p full-rcs-trial)))
710 ;; ))
711
712
713 (defsubst viper-file-checked-in-p (file)
714 (and (featurep 'vc-hooks)
715 ;; CVS files are considered not checked in
716 ;; FIXME: Should this deal with more than CVS?
717 (not (memq (vc-backend file) '(nil CVS)))
718 (if (fboundp 'vc-state)
719 (and
720 (not (memq (vc-state file) '(edited needs-merge)))
721 (not (stringp (vc-state file))))
722 ;; XEmacs has no vc-state
723 (if (featurep 'xemacs) (not (vc-locking-user file))))))
724
725 ;; checkout if visited file is checked in
726 (defun viper-maybe-checkout (buf)
727 (let ((file (expand-file-name (buffer-file-name buf)))
728 (checkout-function (key-binding "\C-x\C-q")))
729 (if (and (viper-file-checked-in-p file)
730 (or (beep 1) t)
731 (y-or-n-p
732 (format
733 "File %s is checked in. Check it out? "
734 (viper-abbreviate-file-name file))))
735 (with-current-buffer buf
736 (command-execute checkout-function)))))
737
738
739
740 \f
741 ;;; Overlays
742 (defun viper-put-on-search-overlay (beg end)
743 (if (viper-overlay-p viper-search-overlay)
744 (viper-move-overlay viper-search-overlay beg end)
745 (setq viper-search-overlay (viper-make-overlay beg end (current-buffer)))
746 (viper-overlay-put
747 viper-search-overlay 'priority viper-search-overlay-priority))
748 (viper-overlay-put viper-search-overlay 'face viper-search-face))
749
750 ;; Search
751
752 (defun viper-flash-search-pattern ()
753 (if (not (viper-has-face-support-p))
754 nil
755 (viper-put-on-search-overlay (match-beginning 0) (match-end 0))
756 (sit-for 2)
757 (viper-overlay-put viper-search-overlay 'face nil)))
758
759 (defun viper-hide-search-overlay ()
760 (if (not (viper-overlay-p viper-search-overlay))
761 (progn
762 (setq viper-search-overlay
763 (viper-make-overlay (point-min) (point-min) (current-buffer)))
764 (viper-overlay-put
765 viper-search-overlay 'priority viper-search-overlay-priority)))
766 (viper-overlay-put viper-search-overlay 'face nil))
767
768 ;; Replace state
769
770 (defsubst viper-move-replace-overlay (beg end)
771 (viper-move-overlay viper-replace-overlay beg end))
772
773 (defun viper-set-replace-overlay (beg end)
774 (if (viper-overlay-live-p viper-replace-overlay)
775 (viper-move-replace-overlay beg end)
776 (setq viper-replace-overlay (viper-make-overlay beg end (current-buffer)))
777 ;; never detach
778 (viper-overlay-put
779 viper-replace-overlay (if (featurep 'emacs) 'evaporate 'detachable) nil)
780 (viper-overlay-put
781 viper-replace-overlay 'priority viper-replace-overlay-priority)
782 ;; If Emacs will start supporting overlay maps, as it currently supports
783 ;; text-property maps, we could do away with viper-replace-minor-mode and
784 ;; just have keymap attached to replace overlay.
785 ;;(viper-overlay-put
786 ;; viper-replace-overlay
787 ;; (if (featurep 'xemacs) 'keymap 'local-map)
788 ;; viper-replace-map)
789 )
790 (if (viper-has-face-support-p)
791 (viper-overlay-put
792 viper-replace-overlay 'face viper-replace-overlay-face))
793 (viper-save-cursor-color 'before-replace-mode)
794 (viper-change-cursor-color
795 (viper-frame-value viper-replace-overlay-cursor-color)))
796
797
798 (defun viper-set-replace-overlay-glyphs (before-glyph after-glyph)
799 (or (viper-overlay-live-p viper-replace-overlay)
800 (viper-set-replace-overlay (point-min) (point-min)))
801 (if (or (not (viper-has-face-support-p))
802 viper-use-replace-region-delimiters)
803 (let ((before-name (if (featurep 'xemacs) 'begin-glyph 'before-string))
804 (after-name (if (featurep 'xemacs) 'end-glyph 'after-string)))
805 (viper-overlay-put viper-replace-overlay before-name before-glyph)
806 (viper-overlay-put viper-replace-overlay after-name after-glyph))))
807
808 (defun viper-hide-replace-overlay ()
809 (viper-set-replace-overlay-glyphs nil nil)
810 (viper-restore-cursor-color 'after-replace-mode)
811 (viper-restore-cursor-color 'after-insert-mode)
812 (if (viper-has-face-support-p)
813 (viper-overlay-put viper-replace-overlay 'face nil)))
814
815
816 (defsubst viper-replace-start ()
817 (viper-overlay-start viper-replace-overlay))
818 (defsubst viper-replace-end ()
819 (viper-overlay-end viper-replace-overlay))
820
821
822 ;; Minibuffer
823
824 (defun viper-set-minibuffer-overlay ()
825 (viper-check-minibuffer-overlay)
826 (when (viper-has-face-support-p)
827 (viper-overlay-put
828 viper-minibuffer-overlay 'face viper-minibuffer-current-face)
829 (viper-overlay-put
830 viper-minibuffer-overlay 'priority viper-minibuffer-overlay-priority)
831 ;; never detach
832 (viper-overlay-put
833 viper-minibuffer-overlay
834 (if (featurep 'emacs) 'evaporate 'detachable)
835 nil)
836 ;; make viper-minibuffer-overlay open-ended
837 ;; In emacs, it is made open ended at creation time
838 (when (featurep 'xemacs)
839 (viper-overlay-put viper-minibuffer-overlay 'start-open nil)
840 (viper-overlay-put viper-minibuffer-overlay 'end-open nil))))
841
842 (defun viper-check-minibuffer-overlay ()
843 (if (viper-overlay-live-p viper-minibuffer-overlay)
844 (viper-move-overlay
845 viper-minibuffer-overlay
846 (if (fboundp 'minibuffer-prompt-end) (minibuffer-prompt-end) 1)
847 (1+ (buffer-size)))
848 (setq viper-minibuffer-overlay
849 (if (featurep 'xemacs)
850 (viper-make-overlay 1 (1+ (buffer-size)) (current-buffer))
851 ;; make overlay open-ended
852 (viper-make-overlay
853 (if (fboundp 'minibuffer-prompt-end) (minibuffer-prompt-end) 1)
854 (1+ (buffer-size))
855 (current-buffer) nil 'rear-advance)))))
856
857
858 (defsubst viper-is-in-minibuffer ()
859 (save-match-data
860 (string-match "\*Minibuf-" (buffer-name))))
861
862
863 \f
864 ;;; XEmacs compatibility
865
866 (defun viper-abbreviate-file-name (file)
867 (if (featurep 'xemacs)
868 (abbreviate-file-name file t) ; XEmacs requires addl argument
869 (abbreviate-file-name file)))
870
871 ;; Sit for VAL milliseconds. XEmacs doesn't support the millisecond arg
872 ;; in sit-for, so this function smoothes out the differences.
873 (defsubst viper-sit-for-short (val &optional nodisp)
874 (sit-for (/ val 1000.0) nodisp))
875
876 ;; EVENT may be a single event of a sequence of events
877 (defsubst viper-ESC-event-p (event)
878 (let ((ESC-keys '(?\e (control \[) escape))
879 (key (viper-event-key event)))
880 (member key ESC-keys)))
881
882 ;; checks if object is a marker, has a buffer, and points to within that buffer
883 (defun viper-valid-marker (marker)
884 (if (and (markerp marker) (marker-buffer marker))
885 (let ((buf (marker-buffer marker))
886 (pos (marker-position marker)))
887 (with-current-buffer buf
888 (and (<= pos (point-max)) (<= (point-min) pos))))))
889
890 (defsubst viper-mark-marker ()
891 (if (featurep 'xemacs) (mark-marker t)
892 (mark-marker)))
893
894 ;; like (set-mark-command nil) but doesn't push twice, if (car mark-ring)
895 ;; is the same as (mark t).
896 (defsubst viper-set-mark-if-necessary ()
897 (setq mark-ring (delete (viper-mark-marker) mark-ring))
898 (set-mark-command nil)
899 (setq viper-saved-mark (point)))
900
901 ;; In transient mark mode (zmacs mode), it is annoying when regions become
902 ;; highlighted due to Viper's pushing marks. So, we deactivate marks, unless
903 ;; the user explicitly wants highlighting, e.g., by hitting '' or ``
904 (defun viper-deactivate-mark ()
905 (if (featurep 'xemacs)
906 (zmacs-deactivate-region)
907 (deactivate-mark)))
908
909 (defsubst viper-leave-region-active ()
910 (if (featurep 'xemacs) (setq zmacs-region-stays t)))
911
912 ;; Check if arg is a valid character for register
913 ;; TYPE is a list that can contain `letter', `Letter', and `digit'.
914 ;; Letter means lowercase letters, Letter means uppercase letters, and
915 ;; digit means digits from 1 to 9.
916 ;; If TYPE is nil, then down/uppercase letters and digits are allowed.
917 (defun viper-valid-register (reg &optional type)
918 (or type (setq type '(letter Letter digit)))
919 (or (if (memq 'letter type)
920 (and (<= ?a reg) (<= reg ?z)))
921 (if (memq 'digit type)
922 (and (<= ?1 reg) (<= reg ?9)))
923 (if (memq 'Letter type)
924 (and (<= ?A reg) (<= reg ?Z)))
925 ))
926
927
928
929 ;; it is suggested that an event must be copied before it is assigned to
930 ;; last-command-event in XEmacs
931 (defun viper-copy-event (event)
932 (if (featurep 'xemacs) (copy-event event)
933 event))
934
935 ;; Uses different timeouts for ESC-sequences and others
936 (defun viper-fast-keysequence-p ()
937 (not (viper-sit-for-short
938 (if (viper-ESC-event-p last-input-event)
939 (viper-ESC-keyseq-timeout)
940 viper-fast-keyseq-timeout)
941 t)))
942
943 ;; like read-event, but in XEmacs also try to convert to char, if possible
944 (defun viper-read-event-convert-to-char ()
945 (let (event)
946 (if (featurep 'xemacs)
947 (progn
948 (setq event (next-command-event))
949 (or (event-to-character event)
950 event))
951 (read-event))))
952
953 ;; Viperized read-key-sequence
954 (defun viper-read-key-sequence (prompt &optional continue-echo)
955 (let (inhibit-quit event keyseq)
956 (setq keyseq (read-key-sequence prompt continue-echo))
957 (setq event (if (featurep 'xemacs)
958 (elt keyseq 0) ; XEmacs returns vector of events
959 (elt (listify-key-sequence keyseq) 0)))
960 (if (viper-ESC-event-p event)
961 (let (unread-command-events)
962 (if (viper-fast-keysequence-p)
963 (let ((viper-vi-global-user-minor-mode nil)
964 (viper-vi-local-user-minor-mode nil)
965 (viper-vi-intercept-minor-mode nil)
966 (viper-insert-intercept-minor-mode nil)
967 (viper-replace-minor-mode nil) ; actually unnecessary
968 (viper-insert-global-user-minor-mode nil)
969 (viper-insert-local-user-minor-mode nil))
970 ;; Note: set unread-command-events only after testing for fast
971 ;; keysequence. Otherwise, viper-fast-keysequence-p will be
972 ;; always t -- whether there is anything after ESC or not
973 (viper-set-unread-command-events keyseq)
974 (setq keyseq (read-key-sequence nil)))
975 (viper-set-unread-command-events keyseq)
976 (setq keyseq (read-key-sequence nil)))))
977 keyseq))
978
979
980 ;; This function lets function-key-map convert key sequences into logical
981 ;; keys. This does a better job than viper-read-event when it comes to kbd
982 ;; macros, since it enables certain macros to be shared between X and TTY modes
983 ;; by correctly mapping key sequences for Left/Right/... (on an ascii
984 ;; terminal) into logical keys left, right, etc.
985 (defun viper-read-key ()
986 (let ((overriding-local-map viper-overriding-map)
987 (inhibit-quit t)
988 help-char key)
989 (use-global-map viper-overriding-map)
990 (unwind-protect
991 (setq key (elt (viper-read-key-sequence nil) 0))
992 (use-global-map global-map))
993 key))
994
995
996 ;; Emacs has a bug in eventp, which causes (eventp nil) to return (nil)
997 ;; instead of nil, if '(nil) was previously inadvertently assigned to
998 ;; unread-command-events
999 (defun viper-event-key (event)
1000 (or (and event (eventp event))
1001 (error "viper-event-key: Wrong type argument, eventp, %S" event))
1002 (when (if (featurep 'xemacs)
1003 (or (key-press-event-p event) (mouse-event-p event)) ; xemacs
1004 t ; emacs
1005 )
1006 (let ((mod (event-modifiers event))
1007 basis)
1008 (setq basis
1009 (if (featurep 'xemacs)
1010 ;; XEmacs
1011 (cond ((key-press-event-p event)
1012 (event-key event))
1013 ((button-event-p event)
1014 (concat "mouse-" (prin1-to-string (event-button event))))
1015 (t
1016 (error "viper-event-key: Unknown event, %S" event)))
1017 ;; Emacs doesn't handle capital letters correctly, since
1018 ;; \S-a isn't considered the same as A (it behaves as
1019 ;; plain `a' instead). So we take care of this here
1020 (cond ((and (viper-characterp event) (<= ?A event) (<= event ?Z))
1021 (setq mod nil
1022 event event))
1023 ;; Emacs has the oddity whereby characters 128+char
1024 ;; represent M-char *if* this appears inside a string.
1025 ;; So, we convert them manually to (meta char).
1026 ((and (viper-characterp event)
1027 (< ?\C-? event) (<= event 255))
1028 (setq mod '(meta)
1029 event (- event ?\C-? 1)))
1030 ((and (null mod) (eq event 'return))
1031 (setq event ?\C-m))
1032 ((and (null mod) (eq event 'space))
1033 (setq event ?\ ))
1034 ((and (null mod) (eq event 'delete))
1035 (setq event ?\C-?))
1036 ((and (null mod) (eq event 'backspace))
1037 (setq event ?\C-h))
1038 (t (event-basic-type event)))
1039 ) ; (featurep 'xemacs)
1040 )
1041 (if (viper-characterp basis)
1042 (setq basis
1043 (if (viper= basis ?\C-?)
1044 (list 'control '\?) ; taking care of an emacs bug
1045 (intern (char-to-string basis)))))
1046 (if mod
1047 (append mod (list basis))
1048 basis))))
1049
1050 (defun viper-key-to-emacs-key (key)
1051 (let (key-name char-p modifiers mod-char-list base-key base-key-name)
1052 (cond ((featurep 'xemacs) key)
1053
1054 ((symbolp key)
1055 (setq key-name (symbol-name key))
1056 (cond ((= (length key-name) 1) ; character event
1057 (string-to-char key-name))
1058 ;; Emacs doesn't recognize `return' and `escape' as events on
1059 ;; dumb terminals, so we translate them into characters
1060 ((and (featurep 'emacs) (not (viper-window-display-p))
1061 (string= key-name "return"))
1062 ?\C-m)
1063 ((and (featurep 'emacs) (not (viper-window-display-p))
1064 (string= key-name "escape"))
1065 ?\e)
1066 ;; pass symbol-event as is
1067 (t key)))
1068
1069 ((listp key)
1070 (setq modifiers (viper-subseq key 0 (1- (length key)))
1071 base-key (viper-seq-last-elt key)
1072 base-key-name (symbol-name base-key)
1073 char-p (= (length base-key-name) 1))
1074 (setq mod-char-list
1075 (mapcar
1076 '(lambda (elt) (upcase (substring (symbol-name elt) 0 1)))
1077 modifiers))
1078 (if char-p
1079 (setq key-name
1080 (car (read-from-string
1081 (concat
1082 "?\\"
1083 (mapconcat 'identity mod-char-list "-\\")
1084 "-"
1085 base-key-name))))
1086 (setq key-name
1087 (intern
1088 (concat
1089 (mapconcat 'identity mod-char-list "-")
1090 "-"
1091 base-key-name))))))
1092 ))
1093
1094
1095 ;; LIS is assumed to be a list of events of characters
1096 (defun viper-eventify-list-xemacs (lis)
1097 (if (featurep 'xemacs)
1098 (mapcar
1099 (lambda (elt)
1100 (cond ((viper-characterp elt) (character-to-event elt))
1101 ((eventp elt) elt)
1102 (t (error
1103 "viper-eventify-list-xemacs: can't convert to event, %S"
1104 elt))))
1105 lis)))
1106
1107
1108 ;; Smoothes out the difference between Emacs' unread-command-events
1109 ;; and XEmacs unread-command-event. Arg is a character, an event, a list of
1110 ;; events or a sequence of keys.
1111 ;;
1112 ;; Due to the way unread-command-events in Emacs (not XEmacs), a non-event
1113 ;; symbol in unread-command-events list may cause Emacs to turn this symbol
1114 ;; into an event. Below, we delete nil from event lists, since nil is the most
1115 ;; common symbol that might appear in this wrong context.
1116 (defun viper-set-unread-command-events (arg)
1117 (if (featurep 'emacs)
1118 (setq
1119 unread-command-events
1120 (let ((new-events
1121 (cond ((eventp arg) (list arg))
1122 ((listp arg) arg)
1123 ((sequencep arg)
1124 (listify-key-sequence arg))
1125 (t (error
1126 "viper-set-unread-command-events: Invalid argument, %S"
1127 arg)))))
1128 (if (not (eventp nil))
1129 (setq new-events (delq nil new-events)))
1130 (append new-events unread-command-events)))
1131 ;; XEmacs
1132 (setq
1133 unread-command-events
1134 (append
1135 (cond ((viper-characterp arg) (list (character-to-event arg)))
1136 ((eventp arg) (list arg))
1137 ((stringp arg) (mapcar 'character-to-event arg))
1138 ((vectorp arg) (append arg nil)) ; turn into list
1139 ((listp arg) (viper-eventify-list-xemacs arg))
1140 (t (error
1141 "viper-set-unread-command-events: Invalid argument, %S" arg)))
1142 unread-command-events))))
1143
1144
1145 ;; Check if vec is a vector of key-press events representing characters
1146 ;; XEmacs only
1147 (defun viper-event-vector-p (vec)
1148 (and (vectorp vec)
1149 (eval (cons 'and (mapcar '(lambda (elt) (if (eventp elt) t)) vec)))))
1150
1151
1152 ;; check if vec is a vector of character symbols
1153 (defun viper-char-symbol-sequence-p (vec)
1154 (and
1155 (sequencep vec)
1156 (eval
1157 (cons 'and
1158 (mapcar (lambda (elt)
1159 (and (symbolp elt) (= (length (symbol-name elt)) 1)))
1160 vec)))))
1161
1162
1163 (defun viper-char-array-p (array)
1164 (eval (cons 'and (mapcar 'viper-characterp array))))
1165
1166
1167 ;; Args can be a sequence of events, a string, or a Viper macro. Will try to
1168 ;; convert events to keys and, if all keys are regular printable
1169 ;; characters, will return a string. Otherwise, will return a string
1170 ;; representing a vector of converted events. If the input was a Viper macro,
1171 ;; will return a string that represents this macro as a vector.
1172 (defun viper-array-to-string (event-seq)
1173 (let (temp temp2)
1174 (cond ((stringp event-seq) event-seq)
1175 ((viper-event-vector-p event-seq)
1176 (setq temp (mapcar 'viper-event-key event-seq))
1177 (cond ((viper-char-symbol-sequence-p temp)
1178 (mapconcat 'symbol-name temp ""))
1179 ((and (viper-char-array-p
1180 (setq temp2 (mapcar 'viper-key-to-character temp))))
1181 (mapconcat 'char-to-string temp2 ""))
1182 (t (prin1-to-string (vconcat temp)))))
1183 ((viper-char-symbol-sequence-p event-seq)
1184 (mapconcat 'symbol-name event-seq ""))
1185 ((and (vectorp event-seq)
1186 (viper-char-array-p
1187 (setq temp (mapcar 'viper-key-to-character event-seq))))
1188 (mapconcat 'char-to-string temp ""))
1189 (t (prin1-to-string event-seq)))))
1190
1191 (defun viper-key-press-events-to-chars (events)
1192 (mapconcat (if (featurep 'xemacs)
1193 (lambda (elt) (char-to-string (event-to-character elt))) ; xemacs
1194 'char-to-string ; emacs
1195 )
1196 events
1197 ""))
1198
1199
1200 (defun viper-read-char-exclusive ()
1201 (let (char
1202 (echo-keystrokes 1))
1203 (while (null char)
1204 (condition-case nil
1205 (setq char (read-char))
1206 (error
1207 ;; skip event if not char
1208 (viper-read-event))))
1209 char))
1210
1211 ;; key is supposed to be in viper's representation, e.g., (control l), a
1212 ;; character, etc.
1213 (defun viper-key-to-character (key)
1214 (cond ((eq key 'space) ?\ )
1215 ((eq key 'delete) ?\C-?)
1216 ((eq key 'return) ?\C-m)
1217 ((eq key 'backspace) ?\C-h)
1218 ((and (symbolp key)
1219 (= 1 (length (symbol-name key))))
1220 (string-to-char (symbol-name key)))
1221 ((and (listp key)
1222 (eq (car key) 'control)
1223 (symbol-name (nth 1 key))
1224 (= 1 (length (symbol-name (nth 1 key)))))
1225 (read (format "?\\C-%s" (symbol-name (nth 1 key)))))
1226 (t key)))
1227
1228
1229 (defun viper-setup-master-buffer (&rest other-files-or-buffers)
1230 "Set up the current buffer as a master buffer.
1231 Arguments become related buffers. This function should normally be used in
1232 the `Local variables' section of a file."
1233 (setq viper-related-files-and-buffers-ring
1234 (make-ring (1+ (length other-files-or-buffers))))
1235 (mapc '(lambda (elt)
1236 (viper-ring-insert viper-related-files-and-buffers-ring elt))
1237 other-files-or-buffers)
1238 (viper-ring-insert viper-related-files-and-buffers-ring (buffer-name))
1239 )
1240
1241 ;;; Movement utilities
1242
1243 ;; Characters that should not be considered as part of the word, in reformed-vi
1244 ;; syntax mode.
1245 ;; Note: \\ (quoted \) must appear before `-' because this string is listified
1246 ;; into characters at some point and then put back to string. The result is
1247 ;; used in skip-chars-forward, which treats - specially. Here we achieve the
1248 ;; effect of quoting - and preventing it from being special.
1249 (defconst viper-non-word-characters-reformed-vi
1250 "!@#$%^&*()\\-+=|\\~`{}[];:'\",<.>/?")
1251 ;; These are characters that are not to be considered as parts of a word in
1252 ;; Viper.
1253 ;; Set each time state changes and at loading time
1254 (viper-deflocalvar viper-non-word-characters nil)
1255
1256 ;; must be buffer-local
1257 (viper-deflocalvar viper-ALPHA-char-class "w"
1258 "String of syntax classes characterizing Viper's alphanumeric symbols.
1259 In addition, the symbol `_' may be considered alphanumeric if
1260 `viper-syntax-preference' is `strict-vi' or `reformed-vi'.")
1261
1262 (defconst viper-strict-ALPHA-chars "a-zA-Z0-9_"
1263 "Regexp matching the set of alphanumeric characters acceptable to strict
1264 Vi.")
1265 (defconst viper-strict-SEP-chars " \t\n"
1266 "Regexp matching the set of alphanumeric characters acceptable to strict
1267 Vi.")
1268 (defconst viper-strict-SEP-chars-sans-newline " \t"
1269 "Regexp matching the set of alphanumeric characters acceptable to strict
1270 Vi.")
1271
1272 (defconst viper-SEP-char-class " -"
1273 "String of syntax classes for Vi separators.
1274 Usually contains ` ', linefeed, TAB or formfeed.")
1275
1276
1277 ;; Set Viper syntax classes and related variables according to
1278 ;; `viper-syntax-preference'.
1279 (defun viper-update-syntax-classes (&optional set-default)
1280 (let ((preference (cond ((eq viper-syntax-preference 'emacs)
1281 "w") ; Viper words have only Emacs word chars
1282 ((eq viper-syntax-preference 'extended)
1283 "w_") ; Viper words have Emacs word & symbol chars
1284 (t "w"))) ; Viper words are Emacs words plus `_'
1285 (non-word-chars (cond ((eq viper-syntax-preference 'reformed-vi)
1286 (viper-string-to-list
1287 viper-non-word-characters-reformed-vi))
1288 (t nil))))
1289 (if set-default
1290 (setq-default viper-ALPHA-char-class preference
1291 viper-non-word-characters non-word-chars)
1292 (setq viper-ALPHA-char-class preference
1293 viper-non-word-characters non-word-chars))
1294 ))
1295
1296 ;; SYMBOL is used because customize requires it, but it is ignored, unless it
1297 ;; is `nil'. If nil, use setq.
1298 (defun viper-set-syntax-preference (&optional symbol value)
1299 "Set Viper syntax preference.
1300 If called interactively or if SYMBOL is nil, sets syntax preference in current
1301 buffer. If called non-interactively, preferably via the customization widget,
1302 sets the default value."
1303 (interactive)
1304 (or value
1305 (setq value
1306 (completing-read
1307 "Viper syntax preference: "
1308 '(("strict-vi") ("reformed-vi") ("extended") ("emacs"))
1309 nil 'require-match)))
1310 (if (stringp value) (setq value (intern value)))
1311 (or (memq value '(strict-vi reformed-vi extended emacs))
1312 (error "Invalid Viper syntax preference, %S" value))
1313 (if symbol
1314 (setq-default viper-syntax-preference value)
1315 (setq viper-syntax-preference value))
1316 (viper-update-syntax-classes))
1317
1318 (defcustom viper-syntax-preference 'reformed-vi
1319 "*Syntax type characterizing Viper's alphanumeric symbols.
1320 Affects movement and change commands that deal with Vi-style words.
1321 Works best when set in the hooks to various major modes.
1322
1323 `strict-vi' means Viper words are (hopefully) exactly as in Vi.
1324
1325 `reformed-vi' means Viper words are like Emacs words \(as determined using
1326 Emacs syntax tables, which are different for different major modes\) with two
1327 exceptions: the symbol `_' is always part of a word and typical Vi non-word
1328 symbols, such as `,',:,\",),{, etc., are excluded.
1329 This behaves very close to `strict-vi', but also works well with non-ASCII
1330 characters from various alphabets.
1331
1332 `extended' means Viper word constituents are symbols that are marked as being
1333 parts of words OR symbols in Emacs syntax tables.
1334 This is most appropriate for major modes intended for editing programs.
1335
1336 `emacs' means Viper words are the same as Emacs words as specified by Emacs
1337 syntax tables.
1338 This option is appropriate if you like Emacs-style words."
1339 :type '(radio (const strict-vi) (const reformed-vi)
1340 (const extended) (const emacs))
1341 :set 'viper-set-syntax-preference
1342 :group 'viper)
1343 (make-variable-buffer-local 'viper-syntax-preference)
1344
1345
1346 ;; addl-chars are characters to be temporarily considered as alphanumerical
1347 (defun viper-looking-at-alpha (&optional addl-chars)
1348 (or (stringp addl-chars) (setq addl-chars ""))
1349 (if (eq viper-syntax-preference 'reformed-vi)
1350 (setq addl-chars (concat addl-chars "_")))
1351 (let ((char (char-after (point))))
1352 (if char
1353 (if (eq viper-syntax-preference 'strict-vi)
1354 (looking-at (concat "[" viper-strict-ALPHA-chars addl-chars "]"))
1355 (or
1356 ;; or one of the additional chars being asked to include
1357 (viper-memq-char char (viper-string-to-list addl-chars))
1358 (and
1359 ;; not one of the excluded word chars (note:
1360 ;; viper-non-word-characters is a list)
1361 (not (viper-memq-char char viper-non-word-characters))
1362 ;; char of the Viper-word syntax class
1363 (viper-memq-char (char-syntax char)
1364 (viper-string-to-list viper-ALPHA-char-class))))))
1365 ))
1366
1367 (defun viper-looking-at-separator ()
1368 (let ((char (char-after (point))))
1369 (if char
1370 (if (eq viper-syntax-preference 'strict-vi)
1371 (viper-memq-char char (viper-string-to-list viper-strict-SEP-chars))
1372 (or (eq char ?\n) ; RET is always a separator in Vi
1373 (viper-memq-char (char-syntax char)
1374 (viper-string-to-list viper-SEP-char-class)))))
1375 ))
1376
1377 (defsubst viper-looking-at-alphasep (&optional addl-chars)
1378 (or (viper-looking-at-separator) (viper-looking-at-alpha addl-chars)))
1379
1380 (defun viper-skip-alpha-forward (&optional addl-chars)
1381 (or (stringp addl-chars) (setq addl-chars ""))
1382 (viper-skip-syntax
1383 'forward
1384 (cond ((eq viper-syntax-preference 'strict-vi)
1385 "")
1386 (t viper-ALPHA-char-class))
1387 (cond ((eq viper-syntax-preference 'strict-vi)
1388 (concat viper-strict-ALPHA-chars addl-chars))
1389 (t addl-chars))))
1390
1391 (defun viper-skip-alpha-backward (&optional addl-chars)
1392 (or (stringp addl-chars) (setq addl-chars ""))
1393 (viper-skip-syntax
1394 'backward
1395 (cond ((eq viper-syntax-preference 'strict-vi)
1396 "")
1397 (t viper-ALPHA-char-class))
1398 (cond ((eq viper-syntax-preference 'strict-vi)
1399 (concat viper-strict-ALPHA-chars addl-chars))
1400 (t addl-chars))))
1401
1402 ;; weird syntax tables may confuse strict-vi style
1403 (defsubst viper-skip-all-separators-forward (&optional within-line)
1404 (if (eq viper-syntax-preference 'strict-vi)
1405 (if within-line
1406 (skip-chars-forward viper-strict-SEP-chars-sans-newline)
1407 (skip-chars-forward viper-strict-SEP-chars))
1408 (viper-skip-syntax 'forward
1409 viper-SEP-char-class
1410 (or within-line "\n")
1411 (if within-line (viper-line-pos 'end)))))
1412
1413 (defsubst viper-skip-all-separators-backward (&optional within-line)
1414 (if (eq viper-syntax-preference 'strict-vi)
1415 (if within-line
1416 (skip-chars-backward viper-strict-SEP-chars-sans-newline)
1417 (skip-chars-backward viper-strict-SEP-chars))
1418 (viper-skip-syntax 'backward
1419 viper-SEP-char-class
1420 (or within-line "\n")
1421 (if within-line (viper-line-pos 'start)))))
1422 (defun viper-skip-nonseparators (direction)
1423 (viper-skip-syntax
1424 direction
1425 (concat "^" viper-SEP-char-class)
1426 nil
1427 (viper-line-pos (if (eq direction 'forward) 'end 'start))))
1428
1429
1430 ;; skip over non-word constituents and non-separators
1431 (defun viper-skip-nonalphasep-forward ()
1432 (if (eq viper-syntax-preference 'strict-vi)
1433 (skip-chars-forward
1434 (concat "^" viper-strict-SEP-chars viper-strict-ALPHA-chars))
1435 (viper-skip-syntax
1436 'forward
1437 (concat "^" viper-ALPHA-char-class viper-SEP-char-class)
1438 ;; Emacs may consider some of these as words, but we don't want them
1439 viper-non-word-characters
1440 (viper-line-pos 'end))))
1441
1442 (defun viper-skip-nonalphasep-backward ()
1443 (if (eq viper-syntax-preference 'strict-vi)
1444 (skip-chars-backward
1445 (concat "^" viper-strict-SEP-chars viper-strict-ALPHA-chars))
1446 (viper-skip-syntax
1447 'backward
1448 (concat "^" viper-ALPHA-char-class viper-SEP-char-class)
1449 ;; Emacs may consider some of these as words, but we don't want them
1450 viper-non-word-characters
1451 (viper-line-pos 'start))))
1452
1453 ;; Skip SYNTAX like skip-syntax-* and ADDL-CHARS like skip-chars-*
1454 ;; Return the number of chars traveled.
1455 ;; Both SYNTAX or ADDL-CHARS can be strings or lists of characters.
1456 ;; When SYNTAX is "w", then viper-non-word-characters are not considered to be
1457 ;; words, even if Emacs syntax table says they are.
1458 (defun viper-skip-syntax (direction syntax addl-chars &optional limit)
1459 (let ((total 0)
1460 (local 1)
1461 (skip-chars-func
1462 (if (eq direction 'forward)
1463 'skip-chars-forward 'skip-chars-backward))
1464 (skip-syntax-func
1465 (if (eq direction 'forward)
1466 'viper-forward-char-carefully 'viper-backward-char-carefully))
1467 char-looked-at syntax-of-char-looked-at negated-syntax)
1468 (setq addl-chars
1469 (cond ((listp addl-chars) (viper-charlist-to-string addl-chars))
1470 ((stringp addl-chars) addl-chars)
1471 (t "")))
1472 (setq syntax
1473 (cond ((listp syntax) syntax)
1474 ((stringp syntax) (viper-string-to-list syntax))
1475 (t nil)))
1476 (if (memq ?^ syntax) (setq negated-syntax t))
1477
1478 (while (and (not (= local 0))
1479 (cond ((eq direction 'forward)
1480 (not (eobp)))
1481 (t (not (bobp)))))
1482 (setq char-looked-at (viper-char-at-pos direction)
1483 ;; if outside the range, set to nil
1484 syntax-of-char-looked-at (if char-looked-at
1485 (char-syntax char-looked-at)))
1486 (setq local
1487 (+ (if (and
1488 (cond ((and limit (eq direction 'forward))
1489 (< (point) limit))
1490 (limit ; backward & limit
1491 (> (point) limit))
1492 (t t)) ; no limit
1493 ;; char under/before cursor has appropriate syntax
1494 (if negated-syntax
1495 (not (memq syntax-of-char-looked-at syntax))
1496 (memq syntax-of-char-looked-at syntax))
1497 ;; if char-syntax class is "word", make sure it is not one
1498 ;; of the excluded characters
1499 (if (and (eq syntax-of-char-looked-at ?w)
1500 (not negated-syntax))
1501 (not (viper-memq-char
1502 char-looked-at viper-non-word-characters))
1503 t))
1504 (funcall skip-syntax-func 1)
1505 0)
1506 (funcall skip-chars-func addl-chars limit)))
1507 (setq total (+ total local)))
1508 total
1509 ))
1510
1511 ;; tells when point is at the beginning of field
1512 (defun viper-beginning-of-field ()
1513 (or (bobp)
1514 (not (eq (get-char-property (point) 'field)
1515 (get-char-property (1- (point)) 'field)))))
1516
1517
1518 ;; this is copied from cl-extra.el
1519 ;; Return the subsequence of SEQ from START to END.
1520 ;; If END is omitted, it defaults to the length of the sequence.
1521 ;; If START or END is negative, it counts from the end.
1522 (defun viper-subseq (seq start &optional end)
1523 (if (stringp seq) (substring seq start end)
1524 (let (len)
1525 (and end (< end 0) (setq end (+ end (setq len (length seq)))))
1526 (if (< start 0) (setq start (+ start (or len (setq len (length seq))))))
1527 (cond ((listp seq)
1528 (if (> start 0) (setq seq (nthcdr start seq)))
1529 (if end
1530 (let ((res nil))
1531 (while (>= (setq end (1- end)) start)
1532 (push (pop seq) res))
1533 (nreverse res))
1534 (copy-sequence seq)))
1535 (t
1536 (or end (setq end (or len (length seq))))
1537 (let ((res (make-vector (max (- end start) 0) nil))
1538 (i 0))
1539 (while (< start end)
1540 (aset res i (aref seq start))
1541 (setq i (1+ i) start (1+ start)))
1542 res))))))
1543
1544
1545
1546 ;; Local Variables:
1547 ;; eval: (put 'viper-deflocalvar 'lisp-indent-hook 'defun)
1548 ;; End:
1549
1550 ;; arch-tag: 7f023fd5-dd9e-4378-a397-9c179553b0e3
1551 ;;; viper-util.el ends here