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