1;;; viper-cmd.el --- Vi command support for Viper
2
3;; Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4;;   2005, 2006, 2007 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 2, 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(provide 'viper-cmd)
30(require 'advice)
31
32;; Compiler pacifier
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-always)
38(defvar viper-mode-string)
39(defvar viper-custom-file-name)
40(defvar viper--key-maps)
41(defvar viper--intercept-key-maps)
42(defvar iso-accents-mode)
43(defvar quail-mode)
44(defvar quail-current-str)
45(defvar zmacs-region-stays)
46(defvar mark-even-if-inactive)
47(defvar init-message)
48(defvar initial)
49(defvar undo-beg-posn)
50(defvar undo-end-posn)
51
52;; loading happens only in non-interactive compilation
53;; in order to spare non-viperized emacs from being viperized
54(if noninteractive
55    (eval-when-compile
56      (let ((load-path (cons (expand-file-name ".") load-path)))
57	(or (featurep 'viper-util)
58	    (load "viper-util.el" nil nil 'nosuffix))
59	(or (featurep 'viper-keym)
60	    (load "viper-keym.el" nil nil 'nosuffix))
61	(or (featurep 'viper-mous)
62	    (load "viper-mous.el" nil nil 'nosuffix))
63	(or (featurep 'viper-macs)
64	    (load "viper-macs.el" nil nil 'nosuffix))
65	(or (featurep 'viper-ex)
66	    (load "viper-ex.el" nil nil 'nosuffix))
67	)))
68;; end pacifier
69
70
71(require 'viper-util)
72(require 'viper-keym)
73(require 'viper-mous)
74(require 'viper-macs)
75(require 'viper-ex)
76
77
78
79;; Generic predicates
80
81;; These test functions are shamelessly lifted from vip 4.4.2 by Aamod Sane
82
83;; generate test functions
84;; given symbol foo, foo-p is the test function, foos is the set of
85;; Viper command keys
86;; (macroexpand '(viper-test-com-defun foo))
87;; (defun foo-p (com) (consp (memq com foos)))
88
89(defmacro viper-test-com-defun (name)
90  (let* ((snm (symbol-name name))
91	 (nm-p (intern (concat snm "-p")))
92	 (nms (intern (concat snm "s"))))
93    `(defun ,nm-p (com)
94       (consp (viper-memq-char com ,nms)
95	      ))))
96
97;; Variables for defining VI commands
98
99;; Modifying commands that can be prefixes to movement commands
100(defvar viper-prefix-commands '(?c ?d ?y ?! ?= ?# ?< ?> ?\"))
101;; define viper-prefix-command-p
102(viper-test-com-defun viper-prefix-command)
103
104;; Commands that are pairs eg. dd. r and R here are a hack
105(defconst viper-charpair-commands '(?c ?d ?y ?! ?= ?< ?> ?r ?R))
106;; define viper-charpair-command-p
107(viper-test-com-defun viper-charpair-command)
108
109(defconst viper-movement-commands '(?b ?B ?e ?E ?f ?F ?G ?h ?H ?j ?k ?l
110				     ?H ?M ?L ?n ?t ?T ?w ?W ?$ ?%
111				     ?^ ?( ?) ?- ?+ ?| ?{ ?} ?[ ?] ?' ?`
112				     ?\; ?, ?0 ?? ?/ ?\  ?\C-m
113				     space return
114				     delete backspace
115				     )
116				     "Movement commands")
117;; define viper-movement-command-p
118(viper-test-com-defun viper-movement-command)
119
120;; Vi digit commands
121(defconst viper-digit-commands '(?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
122
123;; define viper-digit-command-p
124(viper-test-com-defun viper-digit-command)
125
126;; Commands that can be repeated by . (dotted)
127(defconst viper-dotable-commands '(?c ?d ?C ?s ?S ?D ?> ?<))
128;; define viper-dotable-command-p
129(viper-test-com-defun viper-dotable-command)
130
131;; Commands that can follow a #
132(defconst viper-hash-commands '(?c ?C ?g ?q ?s))
133;; define viper-hash-command-p
134(viper-test-com-defun viper-hash-command)
135
136;; Commands that may have registers as prefix
137(defconst viper-regsuffix-commands '(?d ?y ?Y ?D ?p ?P ?x ?X))
138;; define viper-regsuffix-command-p
139(viper-test-com-defun viper-regsuffix-command)
140
141(defconst viper-vi-commands (append viper-movement-commands
142				  viper-digit-commands
143				  viper-dotable-commands
144				  viper-charpair-commands
145				  viper-hash-commands
146				  viper-prefix-commands
147				  viper-regsuffix-commands)
148  "The list of all commands in Vi-state.")
149;; define viper-vi-command-p
150(viper-test-com-defun viper-vi-command)
151
152;; Where viper saves mark. This mark is resurrected by m^
153(defvar viper-saved-mark nil)
154
155;; Contains user settings for vars affected by viper-set-expert-level function.
156;; Not a user option.
157(defvar viper-saved-user-settings nil)
158
159
160
161;;; CODE
162
163;; sentinels
164
165;; Runs viper-after-change-functions inside after-change-functions
166(defun viper-after-change-sentinel (beg end len)
167  (run-hook-with-args 'viper-after-change-functions beg end len))
168
169;; Runs viper-before-change-functions inside before-change-functions
170(defun viper-before-change-sentinel (beg end)
171  (run-hook-with-args 'viper-before-change-functions beg end))
172
173(defsubst viper-post-command-sentinel ()
174  (condition-case conds
175      (run-hooks 'viper-post-command-hooks)
176    (error (viper-message-conditions conds)))
177  (if (eq viper-current-state 'vi-state)
178      (viper-restore-cursor-color 'after-insert-mode)))
179
180(defsubst viper-pre-command-sentinel ()
181  (run-hooks 'viper-pre-command-hooks))
182
183;; Needed so that Viper will be able to figure the last inserted
184;; chunk of text with reasonable accuracy.
185(defsubst viper-insert-state-post-command-sentinel ()
186  (if (and (memq viper-current-state '(insert-state replace-state))
187	   viper-insert-point
188	   (>= (point) viper-insert-point))
189      (setq viper-last-posn-while-in-insert-state (point-marker)))
190  (or (viper-overlay-p viper-replace-overlay)
191      (progn
192	(viper-set-replace-overlay (point-min) (point-min))
193	(viper-hide-replace-overlay)))
194  (if (eq viper-current-state 'insert-state)
195      (let ((has-saved-cursor-color-in-insert-mode
196	     (stringp (viper-get-saved-cursor-color-in-insert-mode))))
197	(or has-saved-cursor-color-in-insert-mode
198	    (string= (viper-get-cursor-color) viper-insert-state-cursor-color)
199	    ;; save current color, if not already saved
200	    (viper-save-cursor-color 'before-insert-mode))
201	;; set insert mode cursor color
202	(viper-change-cursor-color viper-insert-state-cursor-color)))
203  (if (and viper-emacs-state-cursor-color (eq viper-current-state 'emacs-state))
204      (let ((has-saved-cursor-color-in-emacs-mode
205	     (stringp (viper-get-saved-cursor-color-in-emacs-mode))))
206	(or has-saved-cursor-color-in-emacs-mode
207	    (string= (viper-get-cursor-color) viper-emacs-state-cursor-color)
208	    ;; save current color, if not already saved
209	    (viper-save-cursor-color 'before-emacs-mode))
210	;; set emacs mode cursor color
211	(viper-change-cursor-color viper-emacs-state-cursor-color)))
212
213  (if (and (memq this-command '(dabbrev-expand hippie-expand))
214	   (integerp viper-pre-command-point)
215	   (markerp viper-insert-point)
216	   (marker-position viper-insert-point)
217	   (> viper-insert-point viper-pre-command-point))
218      (viper-move-marker-locally viper-insert-point viper-pre-command-point))
219  )
220
221(defsubst viper-preserve-cursor-color ()
222  (or (memq this-command '(self-insert-command
223			   viper-del-backward-char-in-insert
224			   viper-del-backward-char-in-replace
225			   viper-delete-backward-char
226			   viper-join-lines
227			   viper-delete-char))
228      (memq (viper-event-key last-command-event)
229	    '(up down left right (meta f) (meta b)
230		 (control n) (control p) (control f) (control b)))))
231
232(defsubst viper-insert-state-pre-command-sentinel ()
233  (or (viper-preserve-cursor-color)
234      (viper-restore-cursor-color 'after-insert-mode))
235  (if (and (memq this-command '(dabbrev-expand hippie-expand))
236	   (markerp viper-insert-point)
237	   (marker-position viper-insert-point))
238      (setq viper-pre-command-point (marker-position viper-insert-point))))
239
240(defsubst viper-R-state-post-command-sentinel ()
241  ;; Restoring cursor color is needed despite
242  ;; viper-replace-state-pre-command-sentinel: When you jump to another buffer
243  ;; in another frame, the pre-command hook won't change cursor color to
244  ;; default in that other frame.  So, if the second frame cursor was red and
245  ;; we set the point outside the replacement region, then the cursor color
246  ;; will remain red.  Restoring the default, below, prevents this.
247  (if (and (<= (viper-replace-start) (point))
248	   (<=  (point) (viper-replace-end)))
249      (viper-change-cursor-color viper-replace-overlay-cursor-color)
250    (viper-restore-cursor-color 'after-replace-mode)
251    ))
252
253;; to speed up, don't change cursor color before self-insert
254;; and common move commands
255(defsubst viper-replace-state-pre-command-sentinel ()
256  (or (viper-preserve-cursor-color)
257      (viper-restore-cursor-color 'after-replace-mode)))
258
259
260;; Make sure we don't delete more than needed.
261;; This is executed at viper-last-posn-in-replace-region
262(defsubst viper-trim-replace-chars-to-delete-if-necessary ()
263  (setq viper-replace-chars-to-delete
264	(max 0
265	     (min viper-replace-chars-to-delete
266		  ;; Don't delete more than to the end of repl overlay
267		  (viper-chars-in-region
268		   (viper-replace-end) viper-last-posn-in-replace-region)
269		  ;; point is viper-last-posn-in-replace-region now
270		  ;; So, this limits deletion to the end of line
271		  (viper-chars-in-region (point) (viper-line-pos 'end))
272		  ))))
273
274
275(defun viper-replace-state-post-command-sentinel ()
276  ;; Restoring cursor color is needed despite
277  ;; viper-replace-state-pre-command-sentinel: When one jumps to another buffer
278  ;; in another frame, the pre-command hook won't change cursor color to
279  ;; default in that other frame.  So, if the second frame cursor was red and
280  ;; we set the point outside the replacement region, then the cursor color
281  ;; will remain red.  Restoring the default, below, fixes this problem.
282  ;;
283  ;; We optimize for some commands, like self-insert-command,
284  ;; viper-delete-backward-char, etc., since they either don't change
285  ;; cursor color or, if they terminate replace mode, the color will be changed
286  ;; in viper-finish-change
287  (or (viper-preserve-cursor-color)
288      (viper-restore-cursor-color 'after-replace-mode))
289  (cond
290   ((eq viper-current-state 'replace-state)
291    ;; delete characters to compensate for inserted chars.
292    (let ((replace-boundary (viper-replace-end)))
293      (save-excursion
294	(goto-char viper-last-posn-in-replace-region)
295	(viper-trim-replace-chars-to-delete-if-necessary)
296	(delete-char viper-replace-chars-to-delete)
297	(setq viper-replace-chars-to-delete 0)
298	;; terminate replace mode if reached replace limit
299	(if (= viper-last-posn-in-replace-region (viper-replace-end))
300	    (viper-finish-change)))
301
302      (if (viper-pos-within-region
303	   (point) (viper-replace-start) replace-boundary)
304	  (progn
305	    ;; the state may have changed in viper-finish-change above
306	    (if (eq viper-current-state 'replace-state)
307		(viper-change-cursor-color viper-replace-overlay-cursor-color))
308	    (setq viper-last-posn-in-replace-region (point-marker))))
309      ))
310   ;; terminate replace mode if changed Viper states.
311   (t (viper-finish-change))))
312
313
314;; changing mode
315
316;; Change state to NEW-STATE---either emacs-state, vi-state, or insert-state.
317(defun viper-change-state (new-state)
318  ;; Keep viper-post/pre-command-hooks fresh.
319  ;; We remove then add viper-post/pre-command-sentinel since it is very
320  ;; desirable that viper-pre-command-sentinel is the last hook and
321  ;; viper-post-command-sentinel is the first hook.
322
323  (viper-cond-compile-for-xemacs-or-emacs
324   ;; xemacs
325   (progn
326     (make-local-hook 'viper-after-change-functions)
327     (make-local-hook 'viper-before-change-functions)
328     (make-local-hook 'viper-post-command-hooks)
329     (make-local-hook 'viper-pre-command-hooks))
330   nil ; emacs
331   )
332
333  (remove-hook 'post-command-hook 'viper-post-command-sentinel)
334  (add-hook 'post-command-hook 'viper-post-command-sentinel)
335  (remove-hook 'pre-command-hook 'viper-pre-command-sentinel)
336  (add-hook 'pre-command-hook 'viper-pre-command-sentinel t)
337  ;; These hooks will be added back if switching to insert/replace mode
338  (remove-hook 'viper-post-command-hooks
339	       'viper-insert-state-post-command-sentinel 'local)
340  (remove-hook 'viper-pre-command-hooks
341	       'viper-insert-state-pre-command-sentinel 'local)
342  (setq viper-intermediate-command nil)
343  (cond ((eq new-state 'vi-state)
344	 (cond ((member viper-current-state '(insert-state replace-state))
345
346		;; move viper-last-posn-while-in-insert-state
347		;; This is a normal hook that is executed in insert/replace
348		;; states after each command.  In Vi/Emacs state, it does
349		;; nothing.  We need to execute it here to make sure that
350		;; the last posn was recorded when we hit ESC.
351		;; It may be left unrecorded if the last thing done in
352		;; insert/repl state was dabbrev-expansion or abbrev
353		;; expansion caused by hitting ESC
354		(viper-insert-state-post-command-sentinel)
355
356		(condition-case conds
357		    (progn
358		      (viper-save-last-insertion
359		       viper-insert-point
360		       viper-last-posn-while-in-insert-state)
361		      (if viper-began-as-replace
362			  (setq viper-began-as-replace nil)
363			;; repeat insert commands if numerical arg > 1
364			(save-excursion
365			  (viper-repeat-insert-command))))
366		  (error
367		   (viper-message-conditions conds)))
368
369		(if (> (length viper-last-insertion) 0)
370		    (viper-push-onto-ring viper-last-insertion
371					  'viper-insertion-ring))
372
373		(if viper-ESC-moves-cursor-back
374		    (or (bolp) (viper-beginning-of-field) (backward-char 1))))
375	       ))
376
377	;; insert or replace
378	((memq new-state '(insert-state replace-state))
379	 (if (memq viper-current-state '(emacs-state vi-state))
380	     (viper-move-marker-locally 'viper-insert-point (point)))
381	 (viper-move-marker-locally
382	  'viper-last-posn-while-in-insert-state (point))
383	 (add-hook 'viper-post-command-hooks
384		   'viper-insert-state-post-command-sentinel t 'local)
385	 (add-hook 'viper-pre-command-hooks
386		   'viper-insert-state-pre-command-sentinel t 'local))
387	) ; outermost cond
388
389  ;; Nothing needs to be done to switch to emacs mode! Just set some
390  ;; variables, which is already done in viper-change-state-to-emacs!
391
392  ;; ISO accents
393  ;; always turn off iso-accents-mode in vi-state, or else we won't be able to
394  ;; use the keys `,',^ , as they will do accents instead of Vi actions.
395  (cond ((eq new-state 'vi-state) (viper-set-iso-accents-mode nil));accents off
396	(viper-automatic-iso-accents (viper-set-iso-accents-mode t));accents on
397	(t (viper-set-iso-accents-mode nil)))
398  ;; Always turn off quail mode in vi state
399  (cond ((eq new-state 'vi-state) (viper-set-input-method nil)) ;intl input off
400	(viper-special-input-method (viper-set-input-method t)) ;intl input on
401	(t (viper-set-input-method nil)))
402
403  (setq viper-current-state new-state)
404
405  (viper-update-syntax-classes)
406  (viper-normalize-minor-mode-map-alist)
407  (viper-adjust-keys-for new-state)
408  (viper-set-mode-vars-for new-state)
409  (viper-refresh-mode-line)
410  )
411
412
413(defun viper-adjust-keys-for (state)
414  "Make necessary adjustments to keymaps before entering STATE."
415  (cond ((memq state '(insert-state replace-state))
416	 (if viper-auto-indent
417	     (progn
418	       (define-key viper-insert-basic-map "\C-m" 'viper-autoindent)
419	       (if viper-want-emacs-keys-in-insert
420		   ;; expert
421		   (define-key viper-insert-basic-map "\C-j" nil)
422		 ;; novice
423		 (define-key viper-insert-basic-map "\C-j" 'viper-autoindent)))
424	   (define-key viper-insert-basic-map "\C-m" nil)
425	   (define-key viper-insert-basic-map "\C-j" nil))
426
427	 (setq viper-insert-diehard-minor-mode
428	       (not viper-want-emacs-keys-in-insert))
429
430	 (if viper-want-ctl-h-help
431	     (progn
432	       (define-key viper-insert-basic-map "\C-h" 'help-command)
433	       (define-key viper-replace-map "\C-h" 'help-command))
434	   (define-key viper-insert-basic-map
435	     "\C-h" 'viper-del-backward-char-in-insert)
436	   (define-key viper-replace-map
437	     "\C-h" 'viper-del-backward-char-in-replace))
438	 ;; In XEmacs, C-h overrides backspace, so we make sure it doesn't.
439	 (define-key viper-insert-basic-map
440	   [backspace] 'viper-del-backward-char-in-insert)
441	 (define-key viper-replace-map
442	   [backspace] 'viper-del-backward-char-in-replace)
443	 ) ; end insert/replace case
444	(t ; Vi state
445	 (setq viper-vi-diehard-minor-mode (not viper-want-emacs-keys-in-vi))
446	 (if viper-want-ctl-h-help
447	     (define-key viper-vi-basic-map "\C-h" 'help-command)
448	   (define-key viper-vi-basic-map "\C-h" 'viper-backward-char))
449	 ;; In XEmacs, C-h overrides backspace, so we make sure it doesn't.
450	 (define-key viper-vi-basic-map [backspace] 'viper-backward-char))
451	))
452
453
454;; Normalizes minor-mode-map-alist by putting Viper keymaps first.
455;; This ensures that Viper bindings are in effect, regardless of which minor
456;; modes were turned on by the user or by other packages.
457(defun viper-normalize-minor-mode-map-alist ()
458  (setq viper--intercept-key-maps
459	(list
460	 (cons 'viper-vi-intercept-minor-mode viper-vi-intercept-map)
461	 (cons 'viper-insert-intercept-minor-mode viper-insert-intercept-map)
462	 (cons 'viper-emacs-intercept-minor-mode viper-emacs-intercept-map)
463	 ))
464  (setq viper--key-maps
465	(list (cons 'viper-vi-minibuffer-minor-mode viper-minibuffer-map)
466	      (cons 'viper-vi-local-user-minor-mode viper-vi-local-user-map)
467	      (cons 'viper-vi-kbd-minor-mode viper-vi-kbd-map)
468	      (cons 'viper-vi-global-user-minor-mode viper-vi-global-user-map)
469	      (cons 'viper-vi-state-modifier-minor-mode
470		    (if (keymapp
471			 (cdr (assoc major-mode viper-vi-state-modifier-alist)))
472			(cdr (assoc major-mode viper-vi-state-modifier-alist))
473		      viper-empty-keymap))
474	      (cons 'viper-vi-diehard-minor-mode  viper-vi-diehard-map)
475	      (cons 'viper-vi-basic-minor-mode     viper-vi-basic-map)
476	       (cons 'viper-replace-minor-mode  viper-replace-map)
477	       ;; viper-insert-minibuffer-minor-mode must come after
478	       ;; viper-replace-minor-mode
479	       (cons 'viper-insert-minibuffer-minor-mode
480		     viper-minibuffer-map)
481	       (cons 'viper-insert-local-user-minor-mode
482		     viper-insert-local-user-map)
483	       (cons 'viper-insert-kbd-minor-mode viper-insert-kbd-map)
484	       (cons 'viper-insert-global-user-minor-mode
485		     viper-insert-global-user-map)
486	       (cons 'viper-insert-state-modifier-minor-mode
487		     (if (keymapp
488			  (cdr (assoc major-mode
489				      viper-insert-state-modifier-alist)))
490			 (cdr (assoc major-mode
491				     viper-insert-state-modifier-alist))
492		       viper-empty-keymap))
493	       (cons 'viper-insert-diehard-minor-mode viper-insert-diehard-map)
494	       (cons 'viper-insert-basic-minor-mode viper-insert-basic-map)
495	       (cons 'viper-emacs-local-user-minor-mode
496		     viper-emacs-local-user-map)
497	       (cons 'viper-emacs-kbd-minor-mode viper-emacs-kbd-map)
498	       (cons 'viper-emacs-global-user-minor-mode
499		     viper-emacs-global-user-map)
500	       (cons 'viper-emacs-state-modifier-minor-mode
501		     (if (keymapp
502			  (cdr
503			   (assoc major-mode viper-emacs-state-modifier-alist)))
504			 (cdr
505			  (assoc major-mode viper-emacs-state-modifier-alist))
506		       viper-empty-keymap))
507	       ))
508
509  ;; This var is not local in Emacs, so we make it local.  It must be local
510  ;; because although the stack of minor modes can be the same for all buffers,
511  ;; the associated *keymaps* can be different.  In Viper,
512  ;; viper-vi-local-user-map, viper-insert-local-user-map, and others can have
513  ;; different keymaps for different buffers.  Also, the keymaps associated
514  ;; with viper-vi/insert-state-modifier-minor-mode can be different.
515  ;; ***This is needed only in case emulation-mode-map-alists is not defined.
516  ;; In emacs with emulation-mode-map-alists, nothing needs to be done
517  (unless
518      (and (fboundp 'add-to-ordered-list) (boundp 'emulation-mode-map-alists))
519    (set (make-local-variable 'minor-mode-map-alist)
520         (viper-append-filter-alist
521          (append viper--intercept-key-maps viper--key-maps)
522          minor-mode-map-alist)))
523  )
524
525
526
527;; Viper mode-changing commands and utilities
528
529;; Modifies mode-line-buffer-identification.
530(defun viper-refresh-mode-line ()
531  (set (make-local-variable 'viper-mode-string)
532	(cond ((eq viper-current-state 'emacs-state) viper-emacs-state-id)
533	      ((eq viper-current-state 'vi-state) viper-vi-state-id)
534	      ((eq viper-current-state 'replace-state) viper-replace-state-id)
535	      ((eq viper-current-state 'insert-state) viper-insert-state-id)))
536
537  ;; Sets Viper mode string in global-mode-string
538  (force-mode-line-update))
539
540
541;; Switch from Insert state to Vi state.
542(defun viper-exit-insert-state ()
543  (interactive)
544  (viper-change-state-to-vi))
545
546(defun viper-set-mode-vars-for (state)
547  "Sets Viper minor mode variables to put Viper's state STATE in effect."
548
549  ;; Emacs state
550  (setq viper-vi-minibuffer-minor-mode	     nil
551        viper-insert-minibuffer-minor-mode   nil
552	viper-vi-intercept-minor-mode	     nil
553	viper-insert-intercept-minor-mode    nil
554
555	viper-vi-local-user-minor-mode       nil
556	viper-vi-kbd-minor-mode        	     nil
557	viper-vi-global-user-minor-mode      nil
558	viper-vi-state-modifier-minor-mode   nil
559	viper-vi-diehard-minor-mode          nil
560        viper-vi-basic-minor-mode            nil
561
562	viper-replace-minor-mode 	       nil
563
564	viper-insert-local-user-minor-mode     nil
565	viper-insert-kbd-minor-mode            nil
566	viper-insert-global-user-minor-mode    nil
567	viper-insert-state-modifier-minor-mode nil
568	viper-insert-diehard-minor-mode        nil
569	viper-insert-basic-minor-mode          nil
570	viper-emacs-intercept-minor-mode       t
571	viper-emacs-local-user-minor-mode      t
572	viper-emacs-kbd-minor-mode             (not (viper-is-in-minibuffer))
573	viper-emacs-global-user-minor-mode     t
574	viper-emacs-state-modifier-minor-mode  t
575	)
576
577  ;; Vi state
578  (if (eq state 'vi-state) ; adjust for vi-state
579      (setq
580       viper-vi-intercept-minor-mode	   t
581       viper-vi-minibuffer-minor-mode	   (viper-is-in-minibuffer)
582       viper-vi-local-user-minor-mode	   t
583       viper-vi-kbd-minor-mode        	   (not (viper-is-in-minibuffer))
584       viper-vi-global-user-minor-mode	   t
585       viper-vi-state-modifier-minor-mode    t
586       ;; don't let the diehard keymap block command completion
587       ;; and other things in the minibuffer
588       viper-vi-diehard-minor-mode    	   (not
589					    (or viper-want-emacs-keys-in-vi
590						(viper-is-in-minibuffer)))
591       viper-vi-basic-minor-mode      	      t
592       viper-emacs-intercept-minor-mode       nil
593       viper-emacs-local-user-minor-mode      nil
594       viper-emacs-kbd-minor-mode     	      nil
595       viper-emacs-global-user-minor-mode     nil
596       viper-emacs-state-modifier-minor-mode  nil
597       ))
598
599  ;; Insert and Replace states
600  (if (member state '(insert-state replace-state))
601      (setq
602       viper-insert-intercept-minor-mode      t
603       viper-replace-minor-mode	     	      (eq state 'replace-state)
604       viper-insert-minibuffer-minor-mode     (viper-is-in-minibuffer)
605       viper-insert-local-user-minor-mode     t
606       viper-insert-kbd-minor-mode     	      (not (viper-is-in-minibuffer))
607       viper-insert-global-user-minor-mode     t
608       viper-insert-state-modifier-minor-mode  t
609       ;; don't let the diehard keymap block command completion
610       ;; and other things in the minibuffer
611       viper-insert-diehard-minor-mode 	      (not
612					       (or
613					        viper-want-emacs-keys-in-insert
614					        (viper-is-in-minibuffer)))
615       viper-insert-basic-minor-mode   	      t
616       viper-emacs-intercept-minor-mode       nil
617       viper-emacs-local-user-minor-mode      nil
618       viper-emacs-kbd-minor-mode     	      nil
619       viper-emacs-global-user-minor-mode     nil
620       viper-emacs-state-modifier-minor-mode  nil
621       ))
622
623  ;; minibuffer faces
624  (if (viper-has-face-support-p)
625      (setq viper-minibuffer-current-face
626	    (cond ((eq state 'emacs-state) viper-minibuffer-emacs-face)
627		  ((eq state 'vi-state) viper-minibuffer-vi-face)
628		  ((memq state '(insert-state replace-state))
629		   viper-minibuffer-insert-face))))
630
631  (if (viper-is-in-minibuffer)
632      (viper-set-minibuffer-overlay))
633  )
634
635;; This also takes care of the annoying incomplete lines in files.
636;; Also, this fixes `undo' to work vi-style for complex commands.
637(defun viper-change-state-to-vi ()
638  "Change Viper state to Vi."
639  (interactive)
640  (if (and viper-first-time (not (viper-is-in-minibuffer)))
641      (viper-mode)
642    (if overwrite-mode (overwrite-mode -1))
643    (or (viper-overlay-p viper-replace-overlay)
644      (viper-set-replace-overlay (point-min) (point-min)))
645    (viper-hide-replace-overlay)
646    (if abbrev-mode (expand-abbrev))
647    (if (and auto-fill-function (> (current-column) fill-column))
648	(funcall auto-fill-function))
649    ;; don't leave whitespace lines around
650    (if (and (memq last-command
651		   '(viper-autoindent
652		     viper-open-line viper-Open-line
653		     viper-replace-state-exit-cmd))
654	     (viper-over-whitespace-line))
655	(indent-to-left-margin))
656    (viper-add-newline-at-eob-if-necessary)
657    (viper-adjust-undo)
658
659    (if (eq viper-current-state 'emacs-state)
660	(viper-restore-cursor-color 'after-emacs-mode)
661      (viper-restore-cursor-color 'after-insert-mode))
662
663    (viper-change-state 'vi-state)
664
665    ;; Protect against user errors in hooks
666    (condition-case conds
667	(run-hooks 'viper-vi-state-hook)
668      (error
669       (viper-message-conditions conds)))))
670
671(defun viper-change-state-to-insert ()
672  "Change Viper state to Insert."
673  (interactive)
674  (viper-change-state 'insert-state)
675
676  (or (viper-overlay-p viper-replace-overlay)
677      (viper-set-replace-overlay (point-min) (point-min)))
678  (viper-hide-replace-overlay)
679
680  (let ((has-saved-cursor-color-in-insert-mode
681	 (stringp (viper-get-saved-cursor-color-in-insert-mode))))
682    (or has-saved-cursor-color-in-insert-mode
683	(string= (viper-get-cursor-color) viper-insert-state-cursor-color)
684	(viper-save-cursor-color 'before-insert-mode))
685    (viper-change-cursor-color viper-insert-state-cursor-color))
686
687  ;; Protect against user errors in hooks
688  (condition-case conds
689      (run-hooks 'viper-insert-state-hook)
690    (error
691     (viper-message-conditions conds))))
692
693(defsubst viper-downgrade-to-insert ()
694  ;; Protect against user errors in hooks
695  (condition-case conds
696      (run-hooks 'viper-insert-state-hook)
697    (error
698     (viper-message-conditions conds)))
699  (setq viper-current-state 'insert-state
700	viper-replace-minor-mode nil))
701
702
703
704;; Change to replace state.  When the end of replacement region is reached,
705;; replace state changes to insert state.
706(defun viper-change-state-to-replace (&optional non-R-cmd)
707  (viper-change-state 'replace-state)
708  ;; Run insert-state-hook
709  (condition-case conds
710      (run-hooks 'viper-insert-state-hook 'viper-replace-state-hook)
711    (error
712     (viper-message-conditions conds)))
713
714  (if non-R-cmd
715      (viper-start-replace)
716    ;; 'R' is implemented using Emacs's overwrite-mode
717    (viper-start-R-mode))
718  )
719
720
721(defun viper-change-state-to-emacs ()
722  "Change Viper state to Emacs."
723  (interactive)
724  (or (viper-overlay-p viper-replace-overlay)
725      (viper-set-replace-overlay (point-min) (point-min)))
726  (viper-hide-replace-overlay)
727
728  (if viper-emacs-state-cursor-color
729      (let ((has-saved-cursor-color-in-emacs-mode
730	     (stringp (viper-get-saved-cursor-color-in-emacs-mode))))
731	(or has-saved-cursor-color-in-emacs-mode
732	    (string= (viper-get-cursor-color) viper-emacs-state-cursor-color)
733	    (viper-save-cursor-color 'before-emacs-mode))
734	(viper-change-cursor-color viper-emacs-state-cursor-color)))
735
736  (viper-change-state 'emacs-state)
737
738  ;; Protect against user errors in hooks
739  (condition-case conds
740      (run-hooks 'viper-emacs-state-hook)
741    (error
742     (viper-message-conditions conds))))
743
744;; escape to emacs mode termporarily
745(defun viper-escape-to-emacs (arg &optional events)
746  "Escape to Emacs state from Vi state for one Emacs command.
747ARG is used as the prefix value for the executed command.  If
748EVENTS is a list of events, which become the beginning of the command."
749  (interactive "P")
750  (if (viper= last-command-char ?\\)
751      (message "Switched to EMACS state for the next command..."))
752  (viper-escape-to-state arg events 'emacs-state))
753
754;; escape to Vi mode termporarily
755(defun viper-escape-to-vi (arg)
756  "Escape from Emacs state to Vi state for one Vi 1-character command.
757If the Vi command that the user types has a prefix argument, e.g., `d2w', then
758Vi's prefix argument will be used.  Otherwise, the prefix argument passed to
759`viper-escape-to-vi' is used."
760  (interactive "P")
761  (message "Switched to VI state for the next command...")
762  (viper-escape-to-state arg nil 'vi-state))
763
764;; Escape to STATE mode for one Emacs command.
765(defun viper-escape-to-state (arg events state)
766  ;;(let (com key prefix-arg)
767  (let (com key)
768    ;; this temporarily turns off Viper's minor mode keymaps
769    (viper-set-mode-vars-for state)
770    (viper-normalize-minor-mode-map-alist)
771    (if events (viper-set-unread-command-events events))
772
773    ;; protect against keyboard quit and other errors
774    (condition-case nil
775	(let (viper-vi-kbd-minor-mode
776	      viper-insert-kbd-minor-mode
777	      viper-emacs-kbd-minor-mode)
778	  (unwind-protect
779	      (progn
780		(setq com
781		      (key-binding (setq key (viper-read-key-sequence nil))))
782		;; In case of binding indirection--chase definitions.
783		;; Have to do it here because we execute this command under
784		;; different keymaps, so command-execute may not do the
785		;; right thing there
786		(while (vectorp com) (setq com (key-binding com))))
787	    nil)
788	  ;; Execute command com in the original Viper state, not in state
789	  ;; `state'.  Otherwise, if we switch buffers while executing the
790	  ;; escaped to command, Viper's mode vars will remain those of
791	  ;; `state'.  When we return to the orig buffer, the bindings will be
792	  ;; screwed up.
793	  (viper-set-mode-vars-for viper-current-state)
794
795	  ;; this-command, last-command-char, last-command-event
796	  (setq this-command com)
797	  (viper-cond-compile-for-xemacs-or-emacs
798	   ;; XEmacs represents key sequences as vectors
799	   (setq last-command-event
800		 (viper-copy-event (viper-seq-last-elt key))
801		 last-command-char (event-to-character last-command-event))
802	   ;; Emacs represents them as sequences (str or vec)
803	   (setq last-command-event
804		 (viper-copy-event (viper-seq-last-elt key))
805		 last-command-char last-command-event)
806	   )
807
808	  (if (commandp com)
809	      ;; pretend that current state is the state we excaped to
810	      (let ((viper-current-state state))
811		(setq prefix-arg (or prefix-arg arg))
812		(command-execute com)))
813	  )
814      (quit (ding))
815      (error (beep 1))))
816  ;; set state in the new buffer
817  (viper-set-mode-vars-for viper-current-state))
818
819;; This is used in order to allow reading characters according to the input
820;; method. The character is read in emacs and inserted into the buffer.
821;; If an input method is in effect, this might
822;; cause several characters to be combined into one.
823;; Also takes care of the iso-accents mode
824(defun viper-special-read-and-insert-char ()
825  (viper-set-mode-vars-for 'emacs-state)
826  (viper-normalize-minor-mode-map-alist)
827  (if viper-special-input-method
828      (viper-set-input-method t))
829  (if viper-automatic-iso-accents
830      (viper-set-iso-accents-mode t))
831  (condition-case nil
832      (let (viper-vi-kbd-minor-mode
833	    viper-insert-kbd-minor-mode
834	    viper-emacs-kbd-minor-mode
835	    ch)
836	(cond ((and viper-special-input-method
837		    viper-emacs-p
838		    (fboundp 'quail-input-method))
839	       ;; (let ...) is used to restore unread-command-events to the
840	       ;; original state. We don't want anything left in there after
841	       ;; key translation. (Such left-overs are possible if the user
842	       ;; types a regular key.)
843	       (let (unread-command-events)
844		 ;; The next cmd  and viper-set-unread-command-events
845		 ;; are intended to prevent the input method
846		 ;; from swallowing ^M, ^Q and other special characters
847		 (setq ch (read-char-exclusive))
848		 ;; replace ^M with the newline
849		 (if (eq ch ?\C-m) (setq ch ?\n))
850		 ;; Make sure ^V and ^Q work as quotation chars
851		 (if (memq ch '(?\C-v ?\C-q))
852		     (setq ch (read-char-exclusive)))
853		 (viper-set-unread-command-events ch)
854		 (quail-input-method nil)
855
856		 (if (and ch (string= quail-current-str ""))
857		     (insert ch)
858		   (insert quail-current-str))
859		 (setq ch (or ch
860			      (aref quail-current-str
861				    (1- (length quail-current-str)))))
862		 ))
863	      ((and viper-special-input-method
864		    viper-xemacs-p
865		    (fboundp 'quail-start-translation))
866	       ;; same as above but for XEmacs, which doesn't have
867	       ;; quail-input-method
868	       (let (unread-command-events)
869		 (setq ch (read-char-exclusive))
870		 ;; replace ^M with the newline
871		 (if (eq ch ?\C-m) (setq ch ?\n))
872		 ;; Make sure ^V and ^Q work as quotation chars
873		 (if (memq ch '(?\C-v ?\C-q))
874		     (setq ch (read-char-exclusive)))
875		 (viper-set-unread-command-events ch)
876		 (quail-start-translation nil)
877
878		 (if (and ch (string= quail-current-str ""))
879		     (insert ch)
880		   (insert quail-current-str))
881		 (setq ch (or ch
882			      (aref quail-current-str
883				    (1- (length quail-current-str)))))
884		 ))
885	      ((and (boundp 'iso-accents-mode) iso-accents-mode)
886	       (setq ch (aref (read-key-sequence nil) 0))
887	       ;; replace ^M with the newline
888	       (if (eq ch ?\C-m) (setq ch ?\n))
889	       ;; Make sure ^V and ^Q work as quotation chars
890	       (if (memq ch '(?\C-v ?\C-q))
891		   (setq ch (aref (read-key-sequence nil) 0)))
892	       (insert ch))
893	      (t
894	       ;;(setq ch (read-char-exclusive))
895	       (setq ch (aref (read-key-sequence nil) 0))
896	       (if viper-xemacs-p
897		   (setq ch (event-to-character ch)))
898	       ;; replace ^M with the newline
899	       (if (eq ch ?\C-m) (setq ch ?\n))
900	       ;; Make sure ^V and ^Q work as quotation chars
901	       (if (memq ch '(?\C-v ?\C-q))
902		   (progn
903		     ;;(setq ch (read-char-exclusive))
904		     (setq ch (aref (read-key-sequence nil) 0))
905		     (if viper-xemacs-p
906			 (setq ch (event-to-character ch))))
907		 )
908	       (insert ch))
909	      )
910	(setq last-command-event
911	      (viper-copy-event (if viper-xemacs-p
912				    (character-to-event ch) ch)))
913	) ; let
914    (error nil)
915    ) ; condition-case
916
917  (viper-set-input-method nil)
918  (viper-set-iso-accents-mode nil)
919  (viper-set-mode-vars-for viper-current-state)
920  )
921
922
923(defun viper-exec-form-in-vi  (form)
924  "Execute FORM in Vi state, regardless of the Ccurrent Vi state."
925  (let ((buff (current-buffer))
926	result)
927    (viper-set-mode-vars-for 'vi-state)
928
929    (condition-case nil
930	(let (viper-vi-kbd-minor-mode) ; execute without kbd macros
931	  (setq result (eval form)))
932      (error
933       (signal 'quit nil)))
934
935    (if (not (equal buff (current-buffer))) ; cmd switched buffer
936	(save-excursion
937	  (set-buffer buff)
938	  (viper-set-mode-vars-for viper-current-state)))
939    (viper-set-mode-vars-for viper-current-state)
940    result))
941
942(defun viper-exec-form-in-emacs  (form)
943  "Execute FORM in Emacs, temporarily disabling Viper's minor modes.
944Similar to viper-escape-to-emacs, but accepts forms rather than keystrokes."
945  (let ((buff (current-buffer))
946	result)
947    (viper-set-mode-vars-for 'emacs-state)
948    (setq result (eval form))
949    (if (not (equal buff (current-buffer))) ; cmd switched buffer
950	(save-excursion
951	  (set-buffer buff)
952	  (viper-set-mode-vars-for viper-current-state)))
953    (viper-set-mode-vars-for viper-current-state)
954    result))
955
956;; This executes the last kbd event in emacs mode. Is used when we want to
957;; interpret certain keys directly in emacs (as, for example, in comint mode).
958(defun viper-exec-key-in-emacs (arg)
959  (interactive "P")
960  (viper-escape-to-emacs arg last-command-event))
961
962
963;; This is needed because minor modes sometimes override essential Viper
964;; bindings.  By letting Viper know which files these modes are in, it will
965;; arrange to reorganize minor-mode-map-alist so that things will work right.
966(defun viper-harness-minor-mode (load-file)
967  "Familiarize Viper with a minor mode defined in LOAD_FILE.
968Minor modes that have their own keymaps may overshadow Viper keymaps.
969This function is designed to make Viper aware of the packages that define
970such minor modes.
971Usage:
972    (viper-harness-minor-mode load-file)
973
974LOAD-FILE is a name of the file where the specific minor mode is defined.
975Suffixes such as .el or .elc should be stripped."
976
977  (interactive "sEnter name of the load file: ")
978
979  (eval-after-load load-file '(viper-normalize-minor-mode-map-alist))
980
981  ;; Change the default for minor-mode-map-alist each time a harnessed minor
982  ;; mode adds its own keymap to the a-list.
983  (unless
984      (and (fboundp 'add-to-ordered-list) (boundp 'emulation-mode-map-alists))
985    (eval-after-load
986	load-file '(setq-default minor-mode-map-alist minor-mode-map-alist)))
987  )
988
989
990(defun viper-ESC (arg)
991  "Emulate ESC key in Emacs.
992Prevents multiple escape keystrokes if viper-no-multiple-ESC is true.
993If viper-no-multiple-ESC is 'twice double ESC would ding in vi-state.
994Other ESC sequences are emulated via the current Emacs's major mode
995keymap.  This is more convenient on TTYs, since this won't block
996function keys such as up,down, etc.  ESC will also will also work as
997a Meta key in this case.  When viper-no-multiple-ESC is nil, ESC functions
998as a Meta key and any number of multiple escapes is allowed."
999  (interactive "P")
1000  (let (char)
1001    (cond ((and (not viper-no-multiple-ESC) (eq viper-current-state 'vi-state))
1002	   (setq char (viper-read-char-exclusive))
1003	   (viper-escape-to-emacs arg (list ?\e char) ))
1004	  ((and (eq viper-no-multiple-ESC 'twice)
1005		(eq viper-current-state 'vi-state))
1006	   (setq char (viper-read-char-exclusive))
1007	   (if (= char (string-to-char viper-ESC-key))
1008	       (ding)
1009	     (viper-escape-to-emacs arg (list ?\e char) )))
1010	  (t (ding)))
1011    ))
1012
1013(defun viper-alternate-Meta-key (arg)
1014  "Simulate Emacs Meta key."
1015  (interactive "P")
1016  (sit-for 1) (message "ESC-")
1017  (viper-escape-to-emacs arg '(?\e)))
1018
1019(defun viper-toggle-key-action ()
1020  "Action bound to `viper-toggle-key'."
1021  (interactive)
1022  (if (and (< viper-expert-level 2) (equal viper-toggle-key "\C-z"))
1023      (if (viper-window-display-p)
1024	  (viper-iconify)
1025	(suspend-emacs))
1026    (viper-change-state-to-emacs)))
1027
1028
1029;; Intercept ESC sequences on dumb terminals.
1030;; Based on the idea contributed by Marcelino Veiga Tuimil <mveiga@dit.upm.es>
1031
1032;; Check if last key was ESC and if so try to reread it as a function key.
1033;; But only if there are characters to read during a very short time.
1034;; Returns the last event, if any.
1035(defun viper-envelop-ESC-key ()
1036  (let ((event last-input-event)
1037	(keyseq [nil])
1038	(inhibit-quit t))
1039    (if (viper-ESC-event-p event)
1040	(progn
1041	  ;; Some versions of Emacs (eg., 22.50.8 have a bug, which makes even
1042	  ;; a single ESC into ;; a fast keyseq. To guard against this, we
1043	  ;; added a check if there are other events as well. Keep the next
1044	  ;; line for the next time the bug reappears, so that will remember to
1045	  ;; report it.
1046	  ;;(if (and (viper-fast-keysequence-p) unread-command-events)
1047	  (if (viper-fast-keysequence-p) ;; for Emacsen without the above bug
1048	      (progn
1049		(let (minor-mode-map-alist emulation-mode-map-alists)
1050		  (viper-set-unread-command-events event)
1051		  (setq keyseq (read-key-sequence nil 'continue-echo))
1052		  ) ; let
1053		;; If keyseq translates into something that still has ESC
1054		;; at the beginning, separate ESC from the rest of the seq.
1055		;; In XEmacs we check for events that are keypress meta-key
1056		;; and convert them into [escape key]
1057		;;
1058		;; This is needed for the following reason:
1059		;; If ESC is the first symbol, we interpret it as if the
1060		;; user typed ESC and then quickly some other symbols.
1061		;; If ESC is not the first one, then the key sequence
1062		;; entered was apparently translated into a function key or
1063		;; something (e.g., one may have
1064		;; (define-key function-key-map "\e[192z" [f11])
1065		;; which would translate the escape-sequence generated by
1066		;; f11 in an xterm window into the symbolic key f11.
1067		;;
1068		;; If `first-key' is not an ESC event, we make it into the
1069		;; last-command-event in order to pretend that this key was
1070		;; pressed.  This is needed to allow arrow keys to be bound to
1071		;; macros.  Otherwise, viper-exec-mapped-kbd-macro will think
1072		;; that the last event was ESC and so it'll execute whatever is
1073		;; bound to ESC. (Viper macros can't be bound to
1074		;; ESC-sequences).
1075		(let* ((first-key (elt keyseq 0))
1076		       (key-mod (event-modifiers first-key)))
1077		  (cond ((and (viper-ESC-event-p first-key)
1078			      (not viper-translate-all-ESC-keysequences))
1079			 ;; put keys following ESC on the unread list
1080			 ;; and return ESC as the key-sequence
1081			 (viper-set-unread-command-events (viper-subseq keyseq 1))
1082			 (setq last-input-event event
1083			       keyseq (if viper-emacs-p
1084					  "\e"
1085					(vector (character-to-event ?\e)))))
1086			((and viper-xemacs-p
1087			      (key-press-event-p first-key)
1088			      (equal '(meta) key-mod))
1089			 (viper-set-unread-command-events
1090			  (vconcat (vector
1091				    (character-to-event (event-key first-key)))
1092				   (viper-subseq keyseq 1)))
1093			 (setq last-input-event event
1094			       keyseq (vector (character-to-event ?\e))))
1095			((eventp first-key)
1096			 (setq last-command-event
1097			       (viper-copy-event first-key)))
1098			))
1099		) ; end progn
1100
1101	    ;; this is escape event with nothing after it
1102	    ;; put in unread-command-event and then re-read
1103	    (viper-set-unread-command-events event)
1104	    (setq keyseq (read-key-sequence nil))
1105	    ))
1106      ;; not an escape event
1107      (setq keyseq (vector event)))
1108    keyseq))
1109
1110
1111
1112;; Listen to ESC key.
1113;; If a sequence of keys starting with ESC is issued with very short delays,
1114;; interpret these keys in Emacs mode, so ESC won't be interpreted as a Vi key.
1115(defun viper-intercept-ESC-key ()
1116  "Function that implements ESC key in Viper emulation of Vi."
1117  (interactive)
1118  (let ((cmd (or (key-binding (viper-envelop-ESC-key))
1119		 '(lambda () (interactive) (error "")))))
1120
1121    ;; call the actual function to execute ESC (if no other symbols followed)
1122    ;; or the key bound to the ESC sequence (if the sequence was issued
1123    ;; with very short delay between characters).
1124    (if (eq cmd 'viper-intercept-ESC-key)
1125	(setq cmd
1126	      (cond ((eq viper-current-state 'vi-state)
1127		     'viper-ESC)
1128		    ((eq viper-current-state 'insert-state)
1129		     'viper-exit-insert-state)
1130		    ((eq viper-current-state 'replace-state)
1131		     'viper-replace-state-exit-cmd)
1132		    (t 'viper-change-state-to-vi)
1133		    )))
1134    (call-interactively cmd)))
1135
1136
1137
1138
1139;; prefix argument for Vi mode
1140
1141;; In Vi mode, prefix argument is a dotted pair (NUM . COM) where NUM
1142;; represents the numeric value of the prefix argument and COM represents
1143;; command prefix such as "c", "d", "m" and "y".
1144
1145;; Get value part of prefix-argument ARG.
1146(defsubst viper-p-val (arg)
1147  (cond ((null arg) 1)
1148	((consp arg)
1149	 (if (or (null (car arg)) (equal (car arg) '(nil)))
1150	     1 (car arg)))
1151	(t arg)))
1152
1153;; Get raw value part of prefix-argument ARG.
1154(defsubst viper-P-val (arg)
1155  (cond ((consp arg) (car arg))
1156	(t arg)))
1157
1158;; Get com part of prefix-argument ARG.
1159(defsubst viper-getcom (arg)
1160  (cond ((null arg) nil)
1161	((consp arg) (cdr arg))
1162	(t nil)))
1163
1164;; Get com part of prefix-argument ARG and modify it.
1165(defun viper-getCom (arg)
1166  (let ((com (viper-getcom arg)))
1167    (cond ((viper= com ?c) ?c)
1168	  ;; Previously, ?c was being converted to ?C, but this prevented
1169	  ;; multiline replace regions.
1170	  ;;((viper= com ?c) ?C)
1171	  ((viper= com ?d) ?D)
1172	  ((viper= com ?y) ?Y)
1173	  (t com))))
1174
1175
1176;; Compute numeric prefix arg value.
1177;; Invoked by EVENT-CHAR.  COM is the command part obtained so far.
1178(defun viper-prefix-arg-value (event-char com)
1179  (let ((viper-intermediate-command 'viper-digit-argument)
1180	value func)
1181    ;; read while number
1182    (while (and (viper-characterp event-char)
1183		(>= event-char ?0) (<= event-char ?9))
1184      (setq value (+ (* (if (integerp value) value 0) 10) (- event-char ?0)))
1185      (setq event-char (viper-read-event-convert-to-char)))
1186
1187    (setq prefix-arg value)
1188    (if com (setq prefix-arg (cons prefix-arg com)))
1189    (while (eq event-char ?U)
1190      (viper-describe-arg prefix-arg)
1191      (setq event-char (viper-read-event-convert-to-char)))
1192
1193    (if (or com (and (not (eq viper-current-state 'vi-state))
1194		     ;; make sure it is a Vi command
1195		     (viper-characterp event-char)
1196		     (viper-vi-command-p event-char)
1197		     ))
1198	;; If appears to be one of the vi commands,
1199	;; then execute it with funcall and clear prefix-arg in order to not
1200	;; confuse subsequent commands
1201	(progn
1202	  ;; last-command-char is the char we want emacs to think was typed
1203	  ;; last.  If com is not nil, the viper-digit-argument command was
1204	  ;; called from within viper-prefix-arg command, such as `d', `w',
1205	  ;; etc., i.e., the user typed, say, d2.  In this case, `com' would be
1206	  ;; `d', `w', etc.  If viper-digit-argument was invoked by
1207	  ;; viper-escape-to-vi (which is indicated by the fact that the
1208	  ;; current state is not vi-state), then `event-char' represents the
1209	  ;; vi command to be executed (e.g., `d', `w', etc).  Again,
1210	  ;; last-command-char must make emacs believe that this is the command
1211	  ;; we typed.
1212	  (cond ((eq event-char 'return) (setq event-char ?\C-m))
1213		((eq event-char 'delete) (setq event-char ?\C-?))
1214		((eq event-char 'backspace) (setq event-char ?\C-h))
1215		((eq event-char 'space) (setq event-char ?\ )))
1216	  (setq last-command-char (or com event-char))
1217	  (setq func (viper-exec-form-in-vi
1218		      `(key-binding (char-to-string ,event-char))))
1219	  (funcall func prefix-arg)
1220	  (setq prefix-arg nil))
1221      ;; some other command -- let emacs do it in its own way
1222      (viper-set-unread-command-events event-char))
1223    ))
1224
1225
1226;; Vi operator as prefix argument."
1227(defun viper-prefix-arg-com (char value com)
1228  (let ((cont t)
1229	cmd-info
1230	cmd-to-exec-at-end)
1231    (while (and cont
1232		(viper-memq-char char
1233				 (list ?c ?d ?y ?! ?< ?> ?= ?# ?r ?R ?\"
1234				       viper-buffer-search-char)))
1235      (if com
1236	  ;; this means that we already have a command character, so we
1237	  ;; construct a com list and exit while.  however, if char is "
1238	  ;; it is an error.
1239	  (progn
1240	    ;; new com is (CHAR . OLDCOM)
1241	    (if (viper-memq-char char '(?# ?\")) (error ""))
1242	    (setq com (cons char com))
1243	    (setq cont nil))
1244	;; If com is nil we set com as char, and read more.  Again, if char is
1245	;; ", we read the name of register and store it in viper-use-register.
1246	;; if char is !, =, or #, a complete com is formed so we exit the while
1247	;; loop.
1248	(cond ((viper-memq-char char '(?! ?=))
1249	       (setq com char)
1250	       (setq char (read-char))
1251	       (setq cont nil))
1252	      ((viper= char ?#)
1253	       ;; read a char and encode it as com
1254	       (setq com (+ 128 (read-char)))
1255	       (setq char (read-char)))
1256	      ((viper= char ?\")
1257	       (let ((reg (read-char)))
1258		 (if (viper-valid-register reg)
1259		     (setq viper-use-register reg)
1260		   (error ""))
1261		 (setq char (read-char))))
1262	      (t
1263	       (setq com char)
1264	       (setq char (read-char))))))
1265
1266    (if (atom com)
1267	;; `com' is a single char, so we construct the command argument
1268	;; and if `char' is `?', we describe the arg; otherwise
1269	;; we prepare the command that will be executed at the end.
1270	(progn
1271	  (setq cmd-info (cons value com))
1272	  (while (viper= char ?U)
1273	    (viper-describe-arg cmd-info)
1274	    (setq char (read-char)))
1275	  ;; `char' is a movement cmd, a digit arg cmd, or a register cmd---so
1276	  ;; we execute it at the very end
1277	  (or (viper-movement-command-p char)
1278	      (viper-digit-command-p char)
1279	      (viper-regsuffix-command-p char)
1280	      (viper= char ?!) ; bang command
1281	      (viper= char ?g) ; the gg command (like G0)
1282	      (error ""))
1283	  (setq cmd-to-exec-at-end
1284		(viper-exec-form-in-vi
1285		 `(key-binding (char-to-string ,char)))))
1286
1287      ;; as com is non-nil, this means that we have a command to execute
1288      (if (viper-memq-char (car com) '(?r ?R))
1289	  ;; execute apropriate region command.
1290	  (let ((char (car com)) (com (cdr com)))
1291	    (setq prefix-arg (cons value com))
1292	    (if (viper= char ?r)
1293		(viper-region prefix-arg)
1294	      (viper-Region prefix-arg))
1295	    ;; reset prefix-arg
1296	    (setq prefix-arg nil))
1297	;; otherwise, reset prefix arg and call appropriate command
1298	(setq value (if (null value) 1 value))
1299	(setq prefix-arg nil)
1300	(cond
1301	 ;; If we change ?C to ?c here, then cc will enter replacement mode
1302	 ;; rather than deleting lines.  However, it will affect 1 less line
1303	 ;; than normal.  We decided to not use replacement mode here and
1304	 ;; follow Vi, since replacement mode on n full lines can be achieved
1305	 ;; with nC.
1306	 ((equal com '(?c . ?c)) (viper-line (cons value ?C)))
1307	 ((equal com '(?d . ?d)) (viper-line (cons value ?D)))
1308	 ((equal com '(?d . ?y)) (viper-yank-defun))
1309	 ((equal com '(?y . ?y)) (viper-line (cons value ?Y)))
1310	 ((equal com '(?< . ?<)) (viper-line (cons value ?<)))
1311	 ((equal com '(?> . ?>)) (viper-line (cons value ?>)))
1312	 ((equal com '(?! . ?!)) (viper-line (cons value ?!)))
1313	 ((equal com '(?= . ?=)) (viper-line (cons value ?=)))
1314	 ;; gg  acts as G0
1315	 ((equal (car com) ?g)   (viper-goto-line 0))
1316	 (t (error "")))))
1317
1318    (if cmd-to-exec-at-end
1319	(progn
1320	  (setq last-command-char char)
1321	  (setq last-command-event
1322		(viper-copy-event
1323		 (if viper-xemacs-p (character-to-event char) char)))
1324	  (condition-case nil
1325	      (funcall cmd-to-exec-at-end cmd-info)
1326	    (error
1327	     (error "")))))
1328    ))
1329
1330(defun viper-describe-arg (arg)
1331  (let (val com)
1332    (setq val (viper-P-val arg)
1333	  com (viper-getcom arg))
1334    (if (null val)
1335	(if (null com)
1336	    (message "Value is nil, and command is nil")
1337	  (message "Value is nil, and command is `%c'" com))
1338      (if (null com)
1339	  (message "Value is `%d', and command is nil" val)
1340	(message "Value is `%d', and command is `%c'" val com)))))
1341
1342(defun viper-digit-argument (arg)
1343  "Begin numeric argument for the next command."
1344  (interactive "P")
1345  (viper-leave-region-active)
1346  (viper-prefix-arg-value
1347   last-command-char (if (consp arg) (cdr arg) nil)))
1348
1349(defun viper-command-argument (arg)
1350  "Accept a motion command as an argument."
1351  (interactive "P")
1352  (let ((viper-intermediate-command 'viper-command-argument))
1353    (condition-case nil
1354	(viper-prefix-arg-com
1355	 last-command-char
1356	 (cond ((null arg) nil)
1357	       ((consp arg) (car arg))
1358	       ((integerp arg) arg)
1359	       (t (error viper-InvalidCommandArgument)))
1360	 (cond ((null arg) nil)
1361	       ((consp arg) (cdr arg))
1362	       ((integerp arg) nil)
1363	       (t (error viper-InvalidCommandArgument))))
1364      (quit (setq viper-use-register nil)
1365	    (signal 'quit nil)))
1366    (viper-deactivate-mark)))
1367
1368
1369;; repeat last destructive command
1370
1371;; Append region to text in register REG.
1372;; START and END are buffer positions indicating what to append.
1373(defsubst viper-append-to-register (reg start end)
1374  (set-register reg (concat (if (stringp (get-register reg))
1375				(get-register reg) "")
1376			    (buffer-substring start end))))
1377
1378;; Saves last inserted text for possible use by viper-repeat command.
1379(defun viper-save-last-insertion (beg end)
1380  (condition-case nil
1381      (setq viper-last-insertion (buffer-substring beg end))
1382    (error
1383     ;; beg or end marker are somehow screwed up
1384     (setq viper-last-insertion nil)))
1385  (setq viper-last-insertion (buffer-substring beg end))
1386  (or (< (length viper-d-com) 5)
1387      (setcar (nthcdr 4 viper-d-com) viper-last-insertion))
1388  (or (null viper-command-ring)
1389      (ring-empty-p viper-command-ring)
1390      (progn
1391	(setcar (nthcdr 4 (viper-current-ring-item viper-command-ring))
1392		viper-last-insertion)
1393	;; del most recent elt, if identical to the second most-recent
1394	(viper-cleanup-ring viper-command-ring)))
1395  )
1396
1397(defsubst viper-yank-last-insertion ()
1398  "Inserts the text saved by the previous viper-save-last-insertion command."
1399  (condition-case nil
1400      (insert viper-last-insertion)
1401    (error nil)))
1402
1403
1404;; define functions to be executed
1405
1406;; invoked by the `C' command
1407(defun viper-exec-change (m-com com)
1408  (or (and (markerp viper-com-point) (marker-position viper-com-point))
1409      (set-marker viper-com-point (point) (current-buffer)))
1410  ;; handle C cmd at the eol and at eob.
1411  (if (or (and (eolp) (= viper-com-point (point)))
1412	  (= viper-com-point (point-max)))
1413      (progn
1414	(insert " ")(backward-char 1)))
1415  (if (= viper-com-point (point))
1416      (viper-forward-char-carefully))
1417  (set-mark viper-com-point)
1418  (if (eq m-com 'viper-next-line-at-bol)
1419      (viper-enlarge-region (mark t) (point)))
1420  (if (< (point) (mark t))
1421      (exchange-point-and-mark))
1422  (if (eq (preceding-char) ?\n)
1423      (viper-backward-char-carefully)) ; give back the newline
1424  (if (eq viper-intermediate-command 'viper-repeat)
1425      (viper-change-subr (mark t) (point))
1426    (viper-change (mark t) (point))
1427    ))
1428
1429;; this is invoked by viper-substitute-line
1430(defun viper-exec-Change (m-com com)
1431  (save-excursion
1432    (set-mark viper-com-point)
1433    (viper-enlarge-region (mark t) (point))
1434    (if viper-use-register
1435	(progn
1436	  (cond ((viper-valid-register viper-use-register '(letter digit))
1437		 (copy-to-register
1438		  viper-use-register (mark t) (point) nil))
1439		((viper-valid-register viper-use-register '(Letter))
1440		 (viper-append-to-register
1441		  (downcase viper-use-register) (mark t) (point)))
1442		(t (setq viper-use-register nil)
1443		   (error viper-InvalidRegister viper-use-register)))
1444	  (setq viper-use-register nil)))
1445    (delete-region (mark t) (point)))
1446  (open-line 1)
1447  (if (eq viper-intermediate-command 'viper-repeat)
1448      (viper-yank-last-insertion)
1449    (viper-change-state-to-insert)
1450    ))
1451
1452(defun viper-exec-delete (m-com com)
1453  (or (and (markerp viper-com-point) (marker-position viper-com-point))
1454      (set-marker viper-com-point (point) (current-buffer)))
1455  (let (chars-deleted)
1456    (if viper-use-register
1457	(progn
1458	  (cond ((viper-valid-register viper-use-register '(letter digit))
1459		 (copy-to-register
1460		  viper-use-register viper-com-point (point) nil))
1461		((viper-valid-register viper-use-register '(Letter))
1462		 (viper-append-to-register
1463		  (downcase viper-use-register) viper-com-point (point)))
1464		(t (setq viper-use-register nil)
1465		 (error viper-InvalidRegister viper-use-register)))
1466	  (setq viper-use-register nil)))
1467    (setq last-command
1468	  (if (eq last-command 'd-command) 'kill-region nil))
1469    (setq chars-deleted (abs (- (point) viper-com-point)))
1470    (if (> chars-deleted viper-change-notification-threshold)
1471	(unless (viper-is-in-minibuffer)
1472	  (message "Deleted %d characters" chars-deleted)))
1473    (kill-region viper-com-point (point))
1474    (setq this-command 'd-command)
1475    (if viper-ex-style-motion
1476	(if (and (eolp) (not (bolp))) (backward-char 1)))))
1477
1478(defun viper-exec-Delete (m-com com)
1479  (save-excursion
1480    (set-mark viper-com-point)
1481    (viper-enlarge-region (mark t) (point))
1482    (let (lines-deleted)
1483      (if viper-use-register
1484	  (progn
1485	    (cond ((viper-valid-register viper-use-register '(letter digit))
1486		   (copy-to-register
1487		    viper-use-register (mark t) (point) nil))
1488		  ((viper-valid-register viper-use-register '(Letter))
1489		   (viper-append-to-register
1490		    (downcase viper-use-register) (mark t) (point)))
1491		  (t (setq viper-use-register nil)
1492		     (error viper-InvalidRegister viper-use-register)))
1493	    (setq viper-use-register nil)))
1494      (setq last-command
1495	    (if (eq last-command 'D-command) 'kill-region nil))
1496      (setq lines-deleted (count-lines (point) viper-com-point))
1497      (if (> lines-deleted viper-change-notification-threshold)
1498	  (unless (viper-is-in-minibuffer)
1499	    (message "Deleted %d lines" lines-deleted)))
1500      (kill-region (mark t) (point))
1501      (if (eq m-com 'viper-line) (setq this-command 'D-command)))
1502    (back-to-indentation)))
1503
1504;; save region
1505(defun viper-exec-yank (m-com com)
1506  (or (and (markerp viper-com-point) (marker-position viper-com-point))
1507      (set-marker viper-com-point (point) (current-buffer)))
1508  (let (chars-saved)
1509    (if viper-use-register
1510	(progn
1511	  (cond ((viper-valid-register viper-use-register '(letter digit))
1512		 (copy-to-register
1513		  viper-use-register viper-com-point (point) nil))
1514		((viper-valid-register viper-use-register '(Letter))
1515		 (viper-append-to-register
1516		  (downcase viper-use-register) viper-com-point (point)))
1517		(t (setq viper-use-register nil)
1518		   (error viper-InvalidRegister viper-use-register)))
1519	  (setq viper-use-register nil)))
1520    (setq last-command nil)
1521    (copy-region-as-kill viper-com-point (point))
1522    (setq chars-saved (abs (- (point) viper-com-point)))
1523    (if (> chars-saved viper-change-notification-threshold)
1524	(unless (viper-is-in-minibuffer)
1525	  (message "Saved %d characters" chars-saved)))
1526    (goto-char viper-com-point)))
1527
1528;; save lines
1529(defun viper-exec-Yank (m-com com)
1530  (save-excursion
1531    (set-mark viper-com-point)
1532    (viper-enlarge-region (mark t) (point))
1533    (let (lines-saved)
1534      (if viper-use-register
1535	  (progn
1536	    (cond ((viper-valid-register viper-use-register '(letter digit))
1537		   (copy-to-register
1538		    viper-use-register (mark t) (point) nil))
1539		  ((viper-valid-register viper-use-register '(Letter))
1540		   (viper-append-to-register
1541		    (downcase viper-use-register) (mark t) (point)))
1542		  (t (setq viper-use-register nil)
1543		     (error viper-InvalidRegister  viper-use-register)))
1544	    (setq viper-use-register nil)))
1545      (setq last-command nil)
1546      (copy-region-as-kill (mark t) (point))
1547      (setq lines-saved (count-lines (mark t) (point)))
1548      (if (> lines-saved viper-change-notification-threshold)
1549	  (unless (viper-is-in-minibuffer)
1550	    (message "Saved %d lines" lines-saved)))))
1551  (viper-deactivate-mark)
1552  (goto-char viper-com-point))
1553
1554(defun viper-exec-bang (m-com com)
1555  (save-excursion
1556    (set-mark viper-com-point)
1557    (viper-enlarge-region (mark t) (point))
1558    (exchange-point-and-mark)
1559    (shell-command-on-region
1560     (mark t) (point)
1561     (if (viper= com ?!)
1562	 (setq viper-last-shell-com
1563	       (viper-read-string-with-history
1564		"!"
1565		nil
1566		'viper-shell-history
1567		(car viper-shell-history)
1568		))
1569       viper-last-shell-com)
1570     t)))
1571
1572(defun viper-exec-equals (m-com com)
1573  (save-excursion
1574    (set-mark viper-com-point)
1575    (viper-enlarge-region (mark t) (point))
1576    (if (> (mark t) (point)) (exchange-point-and-mark))
1577    (indent-region (mark t) (point) nil)))
1578
1579(defun viper-exec-shift (m-com com)
1580  (save-excursion
1581    (set-mark viper-com-point)
1582    (viper-enlarge-region (mark t) (point))
1583    (if (> (mark t) (point)) (exchange-point-and-mark))
1584    (indent-rigidly (mark t) (point)
1585		    (if (viper= com ?>)
1586			viper-shift-width
1587		      (- viper-shift-width))))
1588  ;; return point to where it was before shift
1589  (goto-char viper-com-point))
1590
1591;; this is needed because some commands fake com by setting it to ?r, which
1592;; denotes repeated insert command.
1593(defsubst viper-exec-dummy (m-com com)
1594  nil)
1595
1596(defun viper-exec-buffer-search (m-com com)
1597  (setq viper-s-string
1598	(regexp-quote (buffer-substring (point) viper-com-point)))
1599  (setq viper-s-forward t)
1600  (setq viper-search-history (cons viper-s-string viper-search-history))
1601  (setq viper-intermediate-command 'viper-exec-buffer-search)
1602  (viper-search viper-s-string viper-s-forward 1))
1603
1604(defvar viper-exec-array (make-vector 128 nil))
1605
1606;; Using a dispatch array allows adding functions like buffer search
1607;; without affecting other functions.  Buffer search can now be bound
1608;; to any character.
1609
1610(aset viper-exec-array ?c 'viper-exec-change)
1611(aset viper-exec-array ?C 'viper-exec-Change)
1612(aset viper-exec-array ?d 'viper-exec-delete)
1613(aset viper-exec-array ?D 'viper-exec-Delete)
1614(aset viper-exec-array ?y 'viper-exec-yank)
1615(aset viper-exec-array ?Y 'viper-exec-Yank)
1616(aset viper-exec-array ?r 'viper-exec-dummy)
1617(aset viper-exec-array ?! 'viper-exec-bang)
1618(aset viper-exec-array ?< 'viper-exec-shift)
1619(aset viper-exec-array ?> 'viper-exec-shift)
1620(aset viper-exec-array ?= 'viper-exec-equals)
1621
1622
1623
1624;; This function is called by various movement commands to execute a
1625;; destructive command on the region specified by the movement command.  For
1626;; instance, if the user types cw, then the command viper-forward-word will
1627;; call viper-execute-com to execute viper-exec-change, which eventually will
1628;; call viper-change to invoke the replace mode on the region.
1629;;
1630;; The var viper-d-com is set to (M-COM VAL COM REG INSETED-TEXT COMMAND-KEYS)
1631;; via a call to viper-set-destructive-command, for later use by viper-repeat.
1632(defun viper-execute-com (m-com val com)
1633  (let ((reg viper-use-register))
1634    ;; this is the special command `#'
1635    (if (> com 128)
1636	(viper-special-prefix-com (- com 128))
1637      (let ((fn (aref viper-exec-array com)))
1638	(if (null fn)
1639	    (error "%c: %s" com viper-InvalidViCommand)
1640	  (funcall fn m-com com))))
1641    (if (viper-dotable-command-p com)
1642	(viper-set-destructive-command
1643	 (list m-com val com reg nil nil)))
1644    ))
1645
1646
1647(defun viper-repeat (arg)
1648  "Re-execute last destructive command.
1649Use the info in viper-d-com, which has the form
1650\(com val ch reg inserted-text command-keys\),
1651where `com' is the command to be re-executed, `val' is the
1652argument to `com', `ch' is a flag for repeat, and `reg' is optional;
1653if it exists, it is the name of the register for `com'.
1654If the prefix argument, ARG, is non-nil, it is used instead of `val'."
1655  (interactive "P")
1656  (let ((save-point (point)) ; save point before repeating prev cmd
1657	;; Pass along that we are repeating a destructive command
1658	;; This tells viper-set-destructive-command not to update
1659	;; viper-command-ring
1660	(viper-intermediate-command 'viper-repeat))
1661    (if (eq last-command 'viper-undo)
1662	;; if the last command was viper-undo, then undo-more
1663	(viper-undo-more)
1664      ;; otherwise execute the command stored in viper-d-com.  if arg is
1665      ;; non-nil its prefix value is used as new prefix value for the command.
1666      (let ((m-com (car viper-d-com))
1667	    (val (viper-P-val arg))
1668	    (com (nth 2 viper-d-com))
1669	    (reg (nth 3 viper-d-com)))
1670        (if (null val) (setq val (nth 1 viper-d-com)))
1671        (if (null m-com) (error "No previous command to repeat"))
1672        (setq viper-use-register reg)
1673	(if (nth 4 viper-d-com) ; text inserted by command
1674	    (setq viper-last-insertion (nth 4 viper-d-com)
1675		  viper-d-char (nth 4 viper-d-com)))
1676        (funcall m-com (cons val com))
1677        (cond ((and (< save-point (point)) viper-keep-point-on-repeat)
1678	       (goto-char save-point)) ; go back to before repeat.
1679	      ((and (< save-point (point)) viper-ex-style-editing)
1680	       (or (bolp) (backward-char 1))))
1681	(if (and (eolp) (not (bolp)))
1682	    (backward-char 1))
1683     ))
1684  (viper-adjust-undo) ; take care of undo
1685  ;; If the prev cmd was rotating the command ring, this means that `.' has
1686  ;; just executed a command from that ring.  So, push it on the ring again.
1687  ;; If we are just executing previous command , then don't push viper-d-com
1688  ;; because viper-d-com is not fully constructed in this case (its keys and
1689  ;; the inserted text may be nil).  Besides, in this case, the command
1690  ;; executed by `.' is already on the ring.
1691  (if (eq last-command 'viper-display-current-destructive-command)
1692      (viper-push-onto-ring viper-d-com 'viper-command-ring))
1693  (viper-deactivate-mark)
1694  ))
1695
1696(defun viper-repeat-from-history ()
1697  "Repeat a destructive command from history.
1698Doesn't change viper-command-ring in any way, so `.' will work as before
1699executing this command.
1700This command is supposed to be bound to a two-character Vi macro where
1701the second character is a digit 0 to 9.  The digit indicates which
1702history command to execute. `0' is equivalent to `.', `1'
1703invokes the command before that, etc."
1704  (interactive)
1705  (let* ((viper-intermediate-command 'repeating-display-destructive-command)
1706	 (idx (cond (viper-this-kbd-macro
1707		      (string-to-number
1708		       (symbol-name (elt viper-this-kbd-macro 1))))
1709		    (t 0)))
1710	 (num idx)
1711	 (viper-d-com viper-d-com))
1712
1713    (or (and (numberp num) (<= 0 num) (<= num 9))
1714	(progn
1715	  (setq idx 0
1716		num 0)
1717	  (message
1718	   "`viper-repeat-from-history' must be invoked as a Vi macro bound to `'")))
1719    (while (< 0 num)
1720      (setq viper-d-com (viper-special-ring-rotate1 viper-command-ring -1))
1721      (setq num (1- num)))
1722    (viper-repeat nil)
1723    (while (> idx num)
1724      (viper-special-ring-rotate1 viper-command-ring 1)
1725      (setq num (1+ num)))
1726    ))
1727
1728
1729;; The hash-command.  It is invoked interactively by the key sequence #<char>.
1730;; The chars that can follow `#' are determined by viper-hash-command-p
1731(defun viper-special-prefix-com (char)
1732  (cond ((viper= char ?c)
1733	 (downcase-region (min viper-com-point (point))
1734			  (max viper-com-point (point))))
1735	((viper= char ?C)
1736	 (upcase-region (min viper-com-point (point))
1737			(max viper-com-point (point))))
1738	((viper= char ?g)
1739	 (push-mark viper-com-point t)
1740	 ;; execute the last emacs kbd macro on each line of the region
1741	 (viper-global-execute))
1742	((viper= char ?q)
1743	 (push-mark viper-com-point t)
1744	 (viper-quote-region))
1745	((viper= char ?s)
1746	 (funcall viper-spell-function viper-com-point (point)))
1747	(t (error "#%c: %s" char viper-InvalidViCommand))))
1748
1749
1750;; undoing
1751
1752;; hook used inside undo
1753(defvar viper-undo-functions nil)
1754
1755;; Runs viper-before-change-functions inside before-change-functions
1756(defun viper-undo-sentinel (beg end length)
1757  (run-hook-with-args 'viper-undo-functions beg end length))
1758
1759(add-hook 'after-change-functions 'viper-undo-sentinel)
1760
1761;; Hook used in viper-undo
1762(defun viper-after-change-undo-hook (beg end len)
1763  (if (and (boundp 'undo-in-progress) undo-in-progress)
1764      (setq undo-beg-posn beg
1765	    undo-end-posn (or end beg))
1766    ;; some other hooks may be changing various text properties in
1767    ;; the buffer in response to 'undo'; so remove this hook to avoid
1768    ;; its repeated invocation
1769    (remove-hook 'viper-undo-functions 'viper-after-change-undo-hook 'local)
1770  ))
1771
1772(defun viper-undo ()
1773  "Undo previous change."
1774  (interactive)
1775  (message "undo!")
1776  (let ((modified (buffer-modified-p))
1777        (before-undo-pt (point-marker))
1778	undo-beg-posn undo-end-posn)
1779
1780    ;; the viper-after-change-undo-hook removes itself after the 1st invocation
1781    (add-hook 'viper-undo-functions 'viper-after-change-undo-hook nil 'local)
1782
1783    (undo-start)
1784    (undo-more 2)
1785    ;;(setq undo-beg-posn (or undo-beg-posn (point))
1786    ;;    undo-end-posn (or undo-end-posn (point)))
1787    ;;(setq undo-beg-posn (or undo-beg-posn before-undo-pt)
1788    ;;      undo-end-posn (or undo-end-posn undo-beg-posn))
1789
1790    (if (and undo-beg-posn undo-end-posn)
1791	(progn
1792	  (goto-char undo-beg-posn)
1793	  (sit-for 0)
1794	  (if (and viper-keep-point-on-undo
1795		   (pos-visible-in-window-p before-undo-pt))
1796	      (progn
1797		(push-mark (point-marker) t)
1798		(viper-sit-for-short 300)
1799		(goto-char undo-end-posn)
1800		(viper-sit-for-short 300)
1801		(if (pos-visible-in-window-p undo-beg-posn)
1802		    (goto-char before-undo-pt)
1803		  (goto-char undo-beg-posn)))
1804	    (push-mark before-undo-pt t))
1805	  ))
1806
1807    (if (and (eolp) (not (bolp))) (backward-char 1))
1808    )
1809  (setq this-command 'viper-undo))
1810
1811;; Continue undoing previous changes.
1812(defun viper-undo-more ()
1813  (message "undo more!")
1814  (condition-case nil
1815      (undo-more 1)
1816    (error (beep)
1817	   (message "No further undo information in this buffer")))
1818  (if (and (eolp) (not (bolp))) (backward-char 1))
1819  (setq this-command 'viper-undo))
1820
1821;; The following two functions are used to set up undo properly.
1822;; In VI, unlike Emacs, if you open a line, say, and add a bunch of lines,
1823;; they are undone all at once.
1824(defun viper-adjust-undo ()
1825  (if viper-undo-needs-adjustment
1826      (let ((inhibit-quit t)
1827	    tmp tmp2)
1828	(setq viper-undo-needs-adjustment nil)
1829	(if (listp buffer-undo-list)
1830	    (if (setq tmp (memq viper-buffer-undo-list-mark buffer-undo-list))
1831		(progn
1832		  (setq tmp2 (cdr tmp)) ; the part after mark
1833
1834		  ;; cut tail from buffer-undo-list temporarily by direct
1835		  ;; manipulation with pointers in buffer-undo-list
1836		  (setcdr tmp nil)
1837
1838		  (setq buffer-undo-list (delq nil buffer-undo-list))
1839		  (setq buffer-undo-list
1840			(delq viper-buffer-undo-list-mark buffer-undo-list))
1841		  ;; restore tail of buffer-undo-list
1842		  (setq buffer-undo-list (nconc buffer-undo-list tmp2)))
1843	      (setq buffer-undo-list (delq nil buffer-undo-list)))))
1844    ))
1845
1846
1847(defun viper-set-complex-command-for-undo ()
1848  (if (listp buffer-undo-list)
1849      (if (not viper-undo-needs-adjustment)
1850	  (let ((inhibit-quit t))
1851	    (setq buffer-undo-list
1852		  (cons viper-buffer-undo-list-mark buffer-undo-list))
1853	    (setq viper-undo-needs-adjustment t)))))
1854
1855
1856;;; Viper's destructive Command ring utilities
1857
1858(defun viper-display-current-destructive-command ()
1859  (let ((text (nth 4 viper-d-com))
1860	(keys (nth 5 viper-d-com))
1861	(max-text-len 30))
1862
1863    (setq this-command 'viper-display-current-destructive-command)
1864
1865    (message " `.' runs  %s%s"
1866	     (concat "`" (viper-array-to-string keys) "'")
1867	     (viper-abbreviate-string
1868	      (viper-cond-compile-for-xemacs-or-emacs
1869	       (replace-in-string ; xemacs
1870		(cond ((characterp text) (char-to-string text))
1871		      ((stringp text) text)
1872		      (t ""))
1873		"\n" "^J")
1874	       text ; emacs
1875	       )
1876	      max-text-len
1877	      "  inserting  `" "'" "    ......."))
1878    ))
1879
1880
1881;; don't change viper-d-com if it was viper-repeat command invoked with `.'
1882;; or in some other way (non-interactively).
1883(defun viper-set-destructive-command (list)
1884  (or (eq viper-intermediate-command 'viper-repeat)
1885      (progn
1886	(setq viper-d-com list)
1887	(setcar (nthcdr 5 viper-d-com)
1888		(viper-array-to-string (if (arrayp viper-this-command-keys)
1889					   viper-this-command-keys
1890					 (this-command-keys))))
1891	(viper-push-onto-ring viper-d-com 'viper-command-ring)))
1892  (setq viper-this-command-keys nil))
1893
1894
1895(defun viper-prev-destructive-command (next)
1896  "Find previous destructive command in the history of destructive commands.
1897With prefix argument, find next destructive command."
1898  (interactive "P")
1899  (let (cmd viper-intermediate-command)
1900    (if (eq last-command 'viper-display-current-destructive-command)
1901	;; repeated search through command history
1902	(setq viper-intermediate-command
1903	      'repeating-display-destructive-command)
1904      ;; first search through command history--set temp ring
1905      (setq viper-temp-command-ring (copy-list viper-command-ring)))
1906    (setq cmd (if next
1907		  (viper-special-ring-rotate1 viper-temp-command-ring 1)
1908		(viper-special-ring-rotate1 viper-temp-command-ring -1)))
1909    (if (null cmd)
1910	()
1911      (setq viper-d-com cmd))
1912    (viper-display-current-destructive-command)))
1913
1914
1915(defun viper-next-destructive-command ()
1916  "Find next destructive command in the history of destructive commands."
1917  (interactive)
1918  (viper-prev-destructive-command 'next))
1919
1920
1921(defun viper-insert-prev-from-insertion-ring (arg)
1922  "Cycle through insertion ring in the direction of older insertions.
1923Undoes previous insertion and inserts new.
1924With prefix argument, cycles in the direction of newer elements.
1925In minibuffer, this command executes whatever the invocation key is bound
1926to in the global map, instead of cycling through the insertion ring."
1927  (interactive "P")
1928  (let (viper-intermediate-command)
1929    (if (eq last-command 'viper-insert-from-insertion-ring)
1930	(progn  ; repeated search through insertion history
1931	  (setq viper-intermediate-command 'repeating-insertion-from-ring)
1932	  (if (eq viper-current-state 'replace-state)
1933	      (undo 1)
1934	    (if viper-last-inserted-string-from-insertion-ring
1935		(backward-delete-char
1936		 (length viper-last-inserted-string-from-insertion-ring))))
1937	  )
1938      ;;first search through insertion history
1939      (setq viper-temp-insertion-ring (copy-list viper-insertion-ring)))
1940    (setq this-command 'viper-insert-from-insertion-ring)
1941    ;; so that things will be undone properly
1942    (setq buffer-undo-list (cons nil buffer-undo-list))
1943    (setq viper-last-inserted-string-from-insertion-ring
1944	  (viper-special-ring-rotate1 viper-temp-insertion-ring (if arg 1 -1)))
1945
1946    ;; this change of viper-intermediate-command must come after
1947    ;; viper-special-ring-rotate1, so that the ring will rotate, but before the
1948    ;; insertion.
1949    (setq viper-intermediate-command nil)
1950    (if viper-last-inserted-string-from-insertion-ring
1951	(insert viper-last-inserted-string-from-insertion-ring))
1952    ))
1953
1954(defun viper-insert-next-from-insertion-ring ()
1955  "Cycle through insertion ring in the direction of older insertions.
1956Undo previous insertion and inserts new."
1957  (interactive)
1958  (viper-insert-prev-from-insertion-ring 'next))
1959
1960
1961
1962;; some region utilities
1963
1964;; If at the last line of buffer, add \\n before eob, if newline is missing.
1965(defun viper-add-newline-at-eob-if-necessary ()
1966  (save-excursion
1967      (end-of-line)
1968      ;; make sure all lines end with newline, unless in the minibuffer or
1969      ;; when requested otherwise (require-final-newline is nil)
1970      (save-restriction
1971	(widen)
1972	(if (and (eobp)
1973		 (not (bolp))
1974		 require-final-newline
1975		 ;; add newline only if we actually edited buffer. otherwise it
1976		 ;; might unintentionally modify binary buffers
1977		 (buffer-modified-p)
1978		 (not (viper-is-in-minibuffer))
1979		 (not buffer-read-only))
1980	    ;; text property may be read-only
1981	    (condition-case nil
1982		(insert "\n")
1983	      (error nil))
1984	  ))
1985      ))
1986
1987(defun viper-yank-defun ()
1988  (mark-defun)
1989  (copy-region-as-kill (point) (mark t)))
1990
1991;; Enlarge region between BEG and END.
1992(defun viper-enlarge-region (beg end)
1993  (or beg (setq beg end)) ; if beg is nil, set to end
1994  (or end (setq end beg)) ; if end is nil, set to beg
1995
1996  (if (< beg end)
1997      (progn (goto-char beg) (set-mark end))
1998    (goto-char end)
1999    (set-mark beg))
2000  (beginning-of-line)
2001  (exchange-point-and-mark)
2002  (if (or (not (eobp)) (not (bolp))) (forward-line 1))
2003  (if (not (eobp)) (beginning-of-line))
2004  (if (> beg end) (exchange-point-and-mark)))
2005
2006
2007;; Quote region by each line with a user supplied string.
2008(defun viper-quote-region ()
2009  (let ((quote-str viper-quote-string)
2010	(donot-change-dafault t))
2011    (setq quote-str
2012	  (viper-read-string-with-history
2013	   "Quote string: "
2014	   nil
2015	   'viper-quote-region-history
2016	   (cond ((string-match "tex.*-mode" (symbol-name major-mode)) "%%")
2017		 ((string-match "java.*-mode" (symbol-name major-mode)) "//")
2018		 ((string-match "perl.*-mode" (symbol-name major-mode)) "#")
2019		 ((string-match "lisp.*-mode" (symbol-name major-mode)) ";;")
2020		 ((memq major-mode '(c-mode cc-mode c++-mode)) "//")
2021		 ((memq major-mode '(sh-mode shell-mode)) "#")
2022		 (t (setq donot-change-dafault nil)
2023		    quote-str))))
2024    (or donot-change-dafault
2025	(setq viper-quote-string quote-str))
2026    (viper-enlarge-region (point) (mark t))
2027    (if (> (point) (mark t)) (exchange-point-and-mark))
2028    (insert quote-str)
2029    (beginning-of-line)
2030    (forward-line 1)
2031    (while (and (< (point) (mark t)) (bolp))
2032      (insert quote-str)
2033      (beginning-of-line)
2034      (forward-line 1))))
2035
2036;;  Tells whether BEG is on the same line as END.
2037;;  If one of the args is nil, it'll return nil.
2038(defun viper-same-line (beg end)
2039   (let ((selective-display nil)
2040	 (incr 0)
2041	 temp)
2042     (if (and beg end (> beg end))
2043	 (setq temp beg
2044	       beg end
2045	       end temp))
2046     (if (and beg end)
2047	 (cond ((or (> beg (point-max)) (> end (point-max))) ; out of range
2048		nil)
2049	       (t
2050		;; This 'if' is needed because Emacs treats the next empty line
2051		;; as part of the previous line.
2052		(if (= (viper-line-pos 'start) end)
2053		    (setq incr 1))
2054		(<= (+ incr (count-lines beg end)) 1))))
2055     ))
2056
2057
2058;; Check if the string ends with a newline.
2059(defun viper-end-with-a-newline-p (string)
2060  (or (string= string "")
2061      (= (viper-seq-last-elt string) ?\n)))
2062
2063(defun viper-tmp-insert-at-eob (msg)
2064  (let ((savemax (point-max)))
2065      (goto-char savemax)
2066      (insert msg)
2067      (sit-for 2)
2068      (goto-char savemax) (delete-region (point) (point-max))
2069      ))
2070
2071
2072
2073;;; Minibuffer business
2074
2075(defsubst viper-set-minibuffer-style ()
2076  (add-hook 'minibuffer-setup-hook 'viper-minibuffer-setup-sentinel)
2077  (add-hook 'post-command-hook 'viper-minibuffer-post-command-hook))
2078
2079
2080(defun viper-minibuffer-setup-sentinel ()
2081  (let ((hook (if viper-vi-style-in-minibuffer
2082		  'viper-change-state-to-insert
2083		'viper-change-state-to-emacs)))
2084    ;; making buffer-local variables so that normal buffers won't affect the
2085    ;; minibuffer and vice versa. Otherwise, command arguments will affect
2086    ;; minibuffer ops and insertions from the minibuffer will change those in
2087    ;; the normal buffers
2088    (make-local-variable 'viper-d-com)
2089    (make-local-variable 'viper-last-insertion)
2090    (make-local-variable 'viper-command-ring)
2091    (setq viper-d-com nil
2092	  viper-last-insertion nil
2093	  viper-command-ring nil)
2094    (funcall hook)
2095    ))
2096
2097;; Thie is a temp hook that uses free variables init-message and initial.
2098;; A dirty feature, but it is the simplest way to have it do the right thing.
2099;; The INIT-MESSAGE and INITIAL vars come from the scope set by
2100;; viper-read-string-with-history
2101(defun viper-minibuffer-standard-hook ()
2102  (if (stringp init-message)
2103      (viper-tmp-insert-at-eob init-message))
2104  (if (stringp initial)
2105      (progn
2106	;; don't wait if we have unread events or in kbd macro
2107	(or unread-command-events
2108	    executing-kbd-macro
2109	    (sit-for 840))
2110	(if (fboundp 'minibuffer-prompt-end)
2111	    (delete-region (minibuffer-prompt-end) (point-max))
2112	  (erase-buffer))
2113	(insert initial))))
2114
2115(defsubst viper-minibuffer-real-start ()
2116  (if (fboundp 'minibuffer-prompt-end)
2117      (minibuffer-prompt-end)
2118    (point-min)))
2119
2120(defun viper-minibuffer-post-command-hook()
2121  (when (active-minibuffer-window)
2122    (when (< (point) (viper-minibuffer-real-start))
2123      (goto-char (viper-minibuffer-real-start)))))
2124
2125
2126;; Interpret last event in the local map first; if fails, use exit-minibuffer.
2127;; Run viper-minibuffer-exit-hook before exiting.
2128(defun viper-exit-minibuffer ()
2129  "Exit minibuffer Viper way."
2130  (interactive)
2131  (let (command)
2132    (setq command (local-key-binding (char-to-string last-command-char)))
2133    (run-hooks 'viper-minibuffer-exit-hook)
2134    (if command
2135	(command-execute command)
2136      (exit-minibuffer))))
2137
2138
2139(defcustom viper-smart-suffix-list
2140  '("" "tex" "c" "cc" "C" "java" "el" "html" "htm" "xml"
2141    "pl" "flr" "P" "p" "h" "H")
2142  "*List of suffixes that Viper tries to append to filenames ending with a `.'.
2143This is useful when the current directory contains files with the same
2144prefix and many different suffixes.  Usually, only one of the suffixes
2145represents an editable file.  However, file completion will stop at the `.'
2146The smart suffix feature lets you hit RET in such a case, and Viper will
2147select the appropriate suffix.
2148
2149Suffixes are tried in the order given and the first suffix for which a
2150corresponding file exists is selected.  If no file exists for any of the
2151suffixes, the user is asked to confirm.
2152
2153To turn this feature off, set this variable to nil."
2154  :type '(repeat string)
2155  :group 'viper-misc)
2156
2157
2158;; Try to add a suitable suffix to files whose name ends with a `.'
2159;; Useful when the user hits RET on a non-completed file name.
2160;; Used as a minibuffer exit hook in read-file-name
2161(defun viper-file-add-suffix ()
2162  (let ((count 0)
2163	(len (length viper-smart-suffix-list))
2164	(file (buffer-substring-no-properties
2165	       (viper-minibuffer-real-start) (point-max)))
2166	found key cmd suff)
2167    (goto-char (point-max))
2168    (if (and viper-smart-suffix-list (string-match "\\.$" file))
2169	(progn
2170	  (while (and (not found) (< count len))
2171	    (setq suff (nth count viper-smart-suffix-list)
2172		  count (1+ count))
2173	    (if (file-exists-p
2174		 (format "%s%s" (substitute-in-file-name file) suff))
2175		(progn
2176		  (setq found t)
2177		  (insert suff))))
2178
2179	  (if found
2180	      ()
2181	    (viper-tmp-insert-at-eob " [Please complete file name]")
2182	    (unwind-protect
2183		(while (not (memq cmd
2184				  '(exit-minibuffer viper-exit-minibuffer)))
2185		  (setq cmd
2186			(key-binding (setq key (read-key-sequence nil))))
2187		  (cond ((eq cmd 'self-insert-command)
2188			 (viper-cond-compile-for-xemacs-or-emacs
2189			  (insert (events-to-keys key)) ; xemacs
2190			  (insert key) ; emacs
2191			  ))
2192			((memq cmd '(exit-minibuffer viper-exit-minibuffer))
2193			 nil)
2194			(t (command-execute cmd)))
2195		  )))
2196	  ))))
2197
2198
2199(defun viper-minibuffer-trim-tail ()
2200  "Delete junk at the end of the first line of the minibuffer input.
2201Remove this function from `viper-minibuffer-exit-hook', if this causes
2202problems."
2203  (if (viper-is-in-minibuffer)
2204      (let ((inhibit-field-text-motion t))
2205	(goto-char (viper-minibuffer-real-start))
2206	(end-of-line)
2207	(delete-region (point) (point-max)))))
2208
2209
2210;;; Reading string with history
2211
2212(defun viper-read-string-with-history (prompt &optional initial
2213					      history-var default keymap
2214					      init-message)
2215  ;; Read string, prompting with PROMPT and inserting the INITIAL
2216  ;; value.  Uses HISTORY-VAR.  DEFAULT is the default value to accept if the
2217  ;; input is an empty string.
2218  ;; Default value is displayed until the user types something in the
2219  ;; minibuffer.
2220  ;; KEYMAP is used, if given, instead of minibuffer-local-map.
2221  ;; INIT-MESSAGE is the message temporarily displayed after entering the
2222  ;; minibuffer.
2223  (let ((minibuffer-setup-hook
2224	 ;; stolen from add-hook
2225	 (let ((old
2226		(if (boundp 'minibuffer-setup-hook)
2227		    minibuffer-setup-hook
2228		  nil)))
2229	   (cons
2230	    'viper-minibuffer-standard-hook
2231	    (if (or (not (listp old)) (eq (car old) 'lambda))
2232		(list old) old))))
2233	(val "")
2234	(padding "")
2235	temp-msg)
2236
2237    (setq keymap (or keymap minibuffer-local-map)
2238	  initial (or initial "")
2239	  temp-msg (if default
2240		       (format "(default %s) " default)
2241		     ""))
2242
2243    (setq viper-incomplete-ex-cmd nil)
2244    (setq val (read-from-minibuffer prompt
2245				    (concat temp-msg initial val padding)
2246				    keymap nil history-var))
2247    (setq minibuffer-setup-hook nil
2248	  padding (viper-array-to-string (this-command-keys))
2249	  temp-msg "")
2250    ;; the following tries to be smart about what to put in history
2251    (if (not (string= val (car (eval history-var))))
2252	(set history-var (cons val (eval history-var))))
2253    (if (or (string= (nth 0 (eval history-var)) (nth 1 (eval history-var)))
2254	    (string= (nth 0 (eval history-var)) ""))
2255	(set history-var (cdr (eval history-var))))
2256    ;; If the user enters nothing but the prev cmd wasn't viper-ex,
2257    ;; viper-command-argument, or `! shell-command', this probably means
2258    ;; that the user typed something then erased.  Return "" in this case, not
2259    ;; the default---the default is too confusing in this case.
2260    (cond ((and (string= val "")
2261		(not (string= prompt "!")) ; was a `! shell-command'
2262		(not (memq last-command
2263			   '(viper-ex
2264			     viper-command-argument
2265			     t)
2266			   )))
2267	   "")
2268	  ((string= val "") (or default ""))
2269	  (t val))
2270    ))
2271
2272
2273
2274;; insertion commands
2275
2276;; Called when state changes from Insert Vi command mode.
2277;; Repeats the insertion command if Insert state was entered with prefix
2278;; argument > 1.
2279(defun viper-repeat-insert-command ()
2280  (let ((i-com (car viper-d-com))
2281	(val   (nth 1 viper-d-com))
2282	(char  (nth 2 viper-d-com)))
2283    (if (and val (> val 1)) ; first check that val is non-nil
2284	(progn
2285	  (setq viper-d-com (list i-com (1- val) ?r nil nil nil))
2286	  (viper-repeat nil)
2287	  (setq viper-d-com (list i-com val char nil nil nil))
2288	  ))))
2289
2290(defun viper-insert (arg)
2291  "Insert before point."
2292  (interactive "P")
2293  (viper-set-complex-command-for-undo)
2294  (let ((val (viper-p-val arg))
2295	;;(com (viper-getcom arg))
2296	)
2297    (viper-set-destructive-command (list 'viper-insert val ?r nil nil nil))
2298    (if (eq viper-intermediate-command 'viper-repeat)
2299	(viper-loop val (viper-yank-last-insertion))
2300      (viper-change-state-to-insert))))
2301
2302(defun viper-append (arg)
2303  "Append after point."
2304  (interactive "P")
2305  (viper-set-complex-command-for-undo)
2306  (let ((val (viper-p-val arg))
2307	;;(com (viper-getcom arg))
2308	)
2309    (viper-set-destructive-command (list 'viper-append val ?r nil nil nil))
2310    (if (not (eolp)) (forward-char))
2311    (if (eq viper-intermediate-command 'viper-repeat)
2312	(viper-loop val (viper-yank-last-insertion))
2313      (viper-change-state-to-insert))))
2314
2315(defun viper-Append (arg)
2316  "Append at end of line."
2317  (interactive "P")
2318  (viper-set-complex-command-for-undo)
2319  (let ((val (viper-p-val arg))
2320	;;(com (viper-getcom arg))
2321	)
2322    (viper-set-destructive-command (list 'viper-Append val ?r nil nil nil))
2323    (end-of-line)
2324    (if (eq viper-intermediate-command 'viper-repeat)
2325	(viper-loop val (viper-yank-last-insertion))
2326      (viper-change-state-to-insert))))
2327
2328(defun viper-Insert (arg)
2329  "Insert before first non-white."
2330  (interactive "P")
2331  (viper-set-complex-command-for-undo)
2332  (let ((val (viper-p-val arg))
2333	;;(com (viper-getcom arg))
2334	)
2335    (viper-set-destructive-command (list 'viper-Insert val ?r nil nil nil))
2336    (back-to-indentation)
2337    (if (eq viper-intermediate-command 'viper-repeat)
2338	(viper-loop val (viper-yank-last-insertion))
2339      (viper-change-state-to-insert))))
2340
2341(defun viper-open-line (arg)
2342  "Open line below."
2343  (interactive "P")
2344  (viper-set-complex-command-for-undo)
2345  (let ((val (viper-p-val arg))
2346	;;(com (viper-getcom arg))
2347	)
2348    (viper-set-destructive-command (list 'viper-open-line val ?r nil nil nil))
2349    (let ((col (current-indentation)))
2350      (if (eq viper-intermediate-command 'viper-repeat)
2351	  (viper-loop val
2352		      (end-of-line)
2353		      (newline 1)
2354		      (viper-indent-line col)
2355		      (viper-yank-last-insertion))
2356	(end-of-line)
2357	(newline 1)
2358	(viper-indent-line col)
2359	(viper-change-state-to-insert)))))
2360
2361(defun viper-Open-line (arg)
2362  "Open line above."
2363  (interactive "P")
2364  (viper-set-complex-command-for-undo)
2365  (let ((val (viper-p-val arg))
2366	;;(com (viper-getcom arg))
2367	)
2368    (viper-set-destructive-command (list 'viper-Open-line val ?r nil nil nil))
2369    (let ((col (current-indentation)))
2370      (if (eq viper-intermediate-command 'viper-repeat)
2371	  (viper-loop val
2372		      (beginning-of-line)
2373		      (open-line 1)
2374		      (viper-indent-line col)
2375		      (viper-yank-last-insertion))
2376	(beginning-of-line)
2377	(open-line 1)
2378	(viper-indent-line col)
2379	(viper-change-state-to-insert)))))
2380
2381(defun viper-open-line-at-point (arg)
2382  "Open line at point."
2383  (interactive "P")
2384  (viper-set-complex-command-for-undo)
2385  (let ((val (viper-p-val arg))
2386	;;(com (viper-getcom arg))
2387	)
2388    (viper-set-destructive-command
2389     (list 'viper-open-line-at-point val ?r nil nil nil))
2390    (if (eq viper-intermediate-command 'viper-repeat)
2391	(viper-loop val
2392		    (open-line 1)
2393		    (viper-yank-last-insertion))
2394      (open-line 1)
2395      (viper-change-state-to-insert))))
2396
2397;; bound to s
2398(defun viper-substitute (arg)
2399  "Substitute characters."
2400  (interactive "P")
2401  (let ((val (viper-p-val arg))
2402	;;(com (viper-getcom arg))
2403	)
2404    (push-mark nil t)
2405    (forward-char val)
2406    (if (eq viper-intermediate-command 'viper-repeat)
2407	(viper-change-subr (mark t) (point))
2408      (viper-change (mark t) (point)))
2409    ;; com is set to ?r when we repeat this comand with dot
2410    (viper-set-destructive-command (list 'viper-substitute val ?r nil nil nil))
2411    ))
2412
2413;; Command bound to S
2414(defun viper-substitute-line (arg)
2415  "Substitute lines."
2416  (interactive "p")
2417  (viper-set-complex-command-for-undo)
2418  (viper-line (cons arg ?C)))
2419
2420;; Prepare for replace
2421(defun viper-start-replace ()
2422  (setq viper-began-as-replace t
2423	viper-sitting-in-replace t
2424	viper-replace-chars-to-delete 0)
2425  (add-hook
2426   'viper-after-change-functions 'viper-replace-mode-spy-after t 'local)
2427  (add-hook
2428   'viper-before-change-functions 'viper-replace-mode-spy-before t 'local)
2429  ;; this will get added repeatedly, but no harm
2430  (add-hook 'after-change-functions 'viper-after-change-sentinel t)
2431  (add-hook 'before-change-functions 'viper-before-change-sentinel t)
2432  (viper-move-marker-locally
2433   'viper-last-posn-in-replace-region (viper-replace-start))
2434  (add-hook
2435   'viper-post-command-hooks 'viper-replace-state-post-command-sentinel
2436   t 'local)
2437  (add-hook
2438   'viper-pre-command-hooks 'viper-replace-state-pre-command-sentinel t 'local)
2439  ;; guard against a smartie who switched from R-replace to normal replace
2440  (remove-hook
2441   'viper-post-command-hooks 'viper-R-state-post-command-sentinel 'local)
2442  (if overwrite-mode (overwrite-mode -1))
2443  )
2444
2445
2446(defun viper-replace-mode-spy-before (beg end)
2447  (setq viper-replace-region-chars-deleted (viper-chars-in-region beg end))
2448  )
2449
2450;; Invoked as an after-change-function to calculate how many chars have to be
2451;; deleted.  This function may be called several times within a single command,
2452;; if this command performs several separate buffer changes.  Therefore, if
2453;; adds up the number of chars inserted and subtracts the number of chars
2454;; deleted.
2455(defun viper-replace-mode-spy-after (beg end length)
2456  (if (memq viper-intermediate-command
2457	    '(dabbrev-expand hippie-expand repeating-insertion-from-ring))
2458      ;; Take special care of text insertion from insertion ring inside
2459      ;; replacement overlays.
2460      (progn
2461	(setq viper-replace-chars-to-delete 0)
2462	(viper-move-marker-locally
2463	 'viper-last-posn-in-replace-region (point)))
2464
2465    (let* ((real-end (min end (viper-replace-end)))
2466	   (column-shift (- (save-excursion (goto-char real-end)
2467					    (current-column))
2468			    (save-excursion (goto-char beg)
2469					    (current-column))))
2470	   (chars-deleted 0))
2471
2472      (if (> length 0)
2473	  (setq chars-deleted viper-replace-region-chars-deleted))
2474      (setq viper-replace-region-chars-deleted 0)
2475      (setq viper-replace-chars-to-delete
2476	    (+ viper-replace-chars-to-delete
2477	       (-
2478		;; if column shift is bigger, due to a TAB insertion, take
2479		;; column-shift instead of the number of inserted chars
2480		(max (viper-chars-in-region beg real-end)
2481		     ;; This test accounts for Chinese/Japanese/...  chars,
2482		     ;; which occupy 2 columns instead of one.  If we use
2483		     ;; column-shift here, we may delete two chars instead of
2484		     ;; one when the user types one Chinese character.
2485		     ;; Deleting two would be OK, if they were European chars,
2486		     ;; but it is not OK if they are Chinese chars.
2487		     ;; Since it is hard to
2488		     ;; figure out which characters are being deleted in any
2489		     ;; given region, we decided to treat Eastern and European
2490		     ;; characters equally, even though Eastern chars may
2491		     ;; occupy more columns.
2492		     (if (memq this-command '(self-insert-command
2493					      quoted-insert viper-insert-tab))
2494			 column-shift
2495		       0))
2496		;; the number of deleted chars
2497		chars-deleted)))
2498
2499      (viper-move-marker-locally
2500       'viper-last-posn-in-replace-region
2501       (max (if (> end (viper-replace-end)) (viper-replace-end) end)
2502	    (or (marker-position viper-last-posn-in-replace-region)
2503		(viper-replace-start))
2504	    ))
2505
2506      )))
2507
2508
2509;; Delete stuff between viper-last-posn-in-replace-region and the end of
2510;; viper-replace-overlay-marker, if viper-last-posn-in-replace-region is within
2511;; the overlay and current point is before the end of the overlay.
2512;; Don't delete anything if current point is past the end of the overlay.
2513(defun viper-finish-change ()
2514  (remove-hook
2515   'viper-after-change-functions 'viper-replace-mode-spy-after 'local)
2516  (remove-hook
2517   'viper-before-change-functions 'viper-replace-mode-spy-before 'local)
2518  (remove-hook
2519   'viper-post-command-hooks 'viper-replace-state-post-command-sentinel 'local)
2520  (remove-hook
2521   'viper-pre-command-hooks 'viper-replace-state-pre-command-sentinel 'local)
2522  (viper-restore-cursor-color 'after-replace-mode)
2523  (setq viper-sitting-in-replace nil) ; just in case we'll need to know it
2524  (save-excursion
2525    (if (and viper-replace-overlay
2526	     (viper-pos-within-region viper-last-posn-in-replace-region
2527				      (viper-replace-start)
2528				      (viper-replace-end))
2529	     (< (point) (viper-replace-end)))
2530	(delete-region
2531	 viper-last-posn-in-replace-region (viper-replace-end))))
2532
2533  (if (eq viper-current-state 'replace-state)
2534      (viper-downgrade-to-insert))
2535  ;; replace mode ended => nullify viper-last-posn-in-replace-region
2536  (viper-move-marker-locally 'viper-last-posn-in-replace-region nil)
2537  (viper-hide-replace-overlay)
2538  (viper-refresh-mode-line)
2539  (viper-put-string-on-kill-ring viper-last-replace-region)
2540  )
2541
2542;; Make STRING be the first element of the kill ring.
2543(defun viper-put-string-on-kill-ring (string)
2544  (setq kill-ring (cons string kill-ring))
2545  (if (> (length kill-ring) kill-ring-max)
2546      (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
2547  (setq kill-ring-yank-pointer kill-ring))
2548
2549(defun viper-finish-R-mode ()
2550  (remove-hook
2551   'viper-post-command-hooks 'viper-R-state-post-command-sentinel 'local)
2552  (remove-hook
2553   'viper-pre-command-hooks 'viper-replace-state-pre-command-sentinel 'local)
2554  (viper-downgrade-to-insert))
2555
2556(defun viper-start-R-mode ()
2557  ;; Leave arg as 1, not t: XEmacs insists that it must be a pos number
2558  (overwrite-mode 1)
2559  (add-hook
2560   'viper-post-command-hooks 'viper-R-state-post-command-sentinel t 'local)
2561  (add-hook
2562   'viper-pre-command-hooks 'viper-replace-state-pre-command-sentinel t 'local)
2563  ;; guard against a smartie who switched from R-replace to normal replace
2564  (remove-hook
2565   'viper-post-command-hooks 'viper-replace-state-post-command-sentinel 'local)
2566  )
2567
2568
2569
2570(defun viper-replace-state-exit-cmd ()
2571  "Binding for keys that cause Replace state to switch to Vi or to Insert.
2572These keys are ESC, RET, and LineFeed"
2573  (interactive)
2574  (if overwrite-mode   ; if in replace mode invoked via 'R'
2575      (viper-finish-R-mode)
2576    (viper-finish-change))
2577  (let (com)
2578    (if (eq this-command 'viper-intercept-ESC-key)
2579	(setq com 'viper-exit-insert-state)
2580      (viper-set-unread-command-events last-input-char)
2581      (setq com (key-binding (viper-read-key-sequence nil))))
2582
2583    (condition-case conds
2584	(command-execute com)
2585      (error
2586       (viper-message-conditions conds)))
2587    )
2588  (viper-hide-replace-overlay))
2589
2590
2591(defun viper-replace-state-carriage-return ()
2592  "Carriage return in Viper replace state."
2593  (interactive)
2594  ;; If Emacs start supporting overlay maps, as it currently supports
2595  ;; text-property maps, we could do away with viper-replace-minor-mode and
2596  ;; just have keymap attached to replace overlay.  Then the "if part" of this
2597  ;; statement can be deleted.
2598  (if (or (< (point) (viper-replace-start))
2599	  (> (point) (viper-replace-end)))
2600      (let (viper-replace-minor-mode com)
2601	(viper-set-unread-command-events last-input-char)
2602	(setq com (key-binding (read-key-sequence nil)))
2603	(condition-case conds
2604	    (command-execute com)
2605	  (error
2606	   (viper-message-conditions conds))))
2607    (if (not viper-allow-multiline-replace-regions)
2608	(viper-replace-state-exit-cmd)
2609      (if (viper-same-line (point) (viper-replace-end))
2610	  (viper-replace-state-exit-cmd)
2611	;; delete the rest of line
2612	(delete-region (point) (viper-line-pos 'end))
2613	(save-excursion
2614	  (end-of-line)
2615	  (if (eobp) (error "Last line in buffer")))
2616	;; skip to the next line
2617	(forward-line 1)
2618	(back-to-indentation)
2619	))))
2620
2621
2622;; This is the function bound to 'R'---unlimited replace.
2623;; Similar to Emacs's own overwrite-mode.
2624(defun viper-overwrite (arg)
2625  "Begin overwrite mode."
2626  (interactive "P")
2627  (let ((val (viper-p-val arg))
2628	;;(com (viper-getcom arg))
2629	(len))
2630    (viper-set-destructive-command (list 'viper-overwrite val ?r nil nil nil))
2631    (if (eq viper-intermediate-command 'viper-repeat)
2632	(progn
2633	  ;; Viper saves inserted text in viper-last-insertion
2634	  (setq len (length viper-last-insertion))
2635	  (delete-char (min len (- (point-max) (point) 1)))
2636	  (viper-loop val (viper-yank-last-insertion)))
2637      (setq last-command 'viper-overwrite)
2638      (viper-set-complex-command-for-undo)
2639      (viper-set-replace-overlay (point) (viper-line-pos 'end))
2640      (viper-change-state-to-replace)
2641      )))
2642
2643
2644;; line commands
2645
2646(defun viper-line (arg)
2647  (let ((val (car arg))
2648	(com (cdr arg)))
2649    (viper-move-marker-locally 'viper-com-point (point))
2650    (if (not (eobp))
2651	(viper-next-line-carefully (1- val)))
2652    ;; the following ensures that dd, cc, D, yy will do the right thing on the
2653    ;; last line of buffer when this line has no \n.
2654    (viper-add-newline-at-eob-if-necessary)
2655    (viper-execute-com 'viper-line val com))
2656  (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
2657  )
2658
2659(defun viper-yank-line (arg)
2660  "Yank ARG lines (in Vi's sense)."
2661  (interactive "P")
2662  (let ((val (viper-p-val arg)))
2663    (viper-line (cons val ?Y))))
2664
2665
2666;; region commands
2667
2668(defun viper-region (arg)
2669  "Execute command on a region."
2670  (interactive "P")
2671  (let ((val (viper-P-val arg))
2672	(com (viper-getcom arg)))
2673    (viper-move-marker-locally 'viper-com-point (point))
2674    (exchange-point-and-mark)
2675    (viper-execute-com 'viper-region val com)))
2676
2677(defun viper-Region (arg)
2678  "Execute command on a Region."
2679  (interactive "P")
2680  (let ((val (viper-P-val arg))
2681	(com (viper-getCom arg)))
2682    (viper-move-marker-locally 'viper-com-point (point))
2683    (exchange-point-and-mark)
2684    (viper-execute-com 'viper-Region val com)))
2685
2686(defun viper-replace-char (arg)
2687  "Replace the following ARG chars by the character read."
2688  (interactive "P")
2689  (if (and (eolp) (bolp)) (error "No character to replace here"))
2690  (let ((val (viper-p-val arg))
2691	(com (viper-getcom arg)))
2692    (viper-replace-char-subr com val)
2693    (if (and (eolp) (not (bolp))) (forward-char 1))
2694    (setq viper-this-command-keys
2695	  (format "%sr" (if (integerp arg) arg "")))
2696    (viper-set-destructive-command
2697     (list 'viper-replace-char val ?r nil viper-d-char nil))
2698  ))
2699
2700(defun viper-replace-char-subr (com arg)
2701  (let ((inhibit-quit t)
2702	char)
2703    (viper-set-complex-command-for-undo)
2704    (or (eq viper-intermediate-command 'viper-repeat)
2705	(viper-special-read-and-insert-char))
2706
2707    (delete-char 1 t)
2708    (setq char (if com viper-d-char (viper-char-at-pos 'backward)))
2709
2710    (if com (insert char))
2711
2712    (setq viper-d-char char)
2713
2714    (viper-loop (1- (if (> arg 0) arg (- arg)))
2715		(delete-char 1 t)
2716		(insert char))
2717
2718    (viper-adjust-undo)
2719    (backward-char arg)
2720    ))
2721
2722
2723;; basic cursor movement.  j, k, l, h commands.
2724
2725(defun viper-forward-char (arg)
2726  "Move point right ARG characters (left if ARG negative).
2727On reaching end of line, stop and signal error."
2728  (interactive "P")
2729  (viper-leave-region-active)
2730  (let ((val (viper-p-val arg))
2731	(com (viper-getcom arg)))
2732    (if com (viper-move-marker-locally 'viper-com-point (point)))
2733    (if viper-ex-style-motion
2734	(progn
2735	  ;; the boundary condition check gets weird here because
2736	  ;; forward-char may be the parameter of a delete, and 'dl' works
2737	  ;; just like 'x' for the last char on a line, so we have to allow
2738	  ;; the forward motion before the 'viper-execute-com', but, of
2739	  ;; course, 'dl' doesn't work on an empty line, so we have to
2740	  ;; catch that condition before 'viper-execute-com'
2741	  (if (and (eolp) (bolp)) (error "") (forward-char val))
2742	  (if com (viper-execute-com 'viper-forward-char val com))
2743	  (if (eolp) (progn (backward-char 1) (error ""))))
2744      (forward-char val)
2745      (if com (viper-execute-com 'viper-forward-char val com)))))
2746
2747
2748(defun viper-backward-char (arg)
2749  "Move point left ARG characters (right if ARG negative).
2750On reaching beginning of line, stop and signal error."
2751  (interactive "P")
2752  (viper-leave-region-active)
2753  (let ((val (viper-p-val arg))
2754	(com (viper-getcom arg)))
2755    (if com (viper-move-marker-locally 'viper-com-point (point)))
2756    (if viper-ex-style-motion
2757	(progn
2758	  (if (bolp) (error "") (backward-char val))
2759	  (if com (viper-execute-com 'viper-backward-char val com)))
2760      (backward-char val)
2761      (if com (viper-execute-com 'viper-backward-char val com)))))
2762
2763
2764;; Like forward-char, but doesn't move at end of buffer.
2765;; Returns distance traveled
2766;; (positive or 0, if arg positive; negative if arg negative).
2767(defun viper-forward-char-carefully (&optional arg)
2768  (setq arg (or arg 1))
2769  (let ((pt (point)))
2770    (condition-case nil
2771	(forward-char arg)
2772      (error nil))
2773    (if (< (point) pt) ; arg was negative
2774	(- (viper-chars-in-region pt (point)))
2775      (viper-chars-in-region pt (point)))))
2776
2777
2778;; Like backward-char, but doesn't move at beg of buffer.
2779;; Returns distance traveled
2780;; (negative or 0, if arg positive; positive if arg negative).
2781(defun viper-backward-char-carefully (&optional arg)
2782  (setq arg (or arg 1))
2783  (let ((pt (point)))
2784    (condition-case nil
2785	(backward-char arg)
2786      (error nil))
2787    (if (> (point) pt) ; arg was negative
2788	(viper-chars-in-region pt (point))
2789      (- (viper-chars-in-region pt (point))))))
2790
2791(defun viper-next-line-carefully (arg)
2792  (condition-case nil
2793      (next-line arg)
2794    (error nil)))
2795
2796
2797
2798;;; Word command
2799
2800;; Words are formed from alpha's and nonalphas - <sp>,\t\n are separators for
2801;; word movement.  When executed with a destructive command, \n is usually left
2802;; untouched for the last word.  Viper uses syntax table to determine what is a
2803;; word and what is a separator.  However, \n is always a separator.  Also, if
2804;; viper-syntax-preference is 'vi, then `_' is part of the word.
2805
2806;; skip only one \n
2807(defun viper-skip-separators (forward)
2808  (if forward
2809      (progn
2810	(viper-skip-all-separators-forward 'within-line)
2811	(if (looking-at "\n")
2812	    (progn
2813	      (forward-char)
2814	      (viper-skip-all-separators-forward  'within-line))))
2815    ;; check for eob and white space before it.  move off of eob
2816    (if (and (eobp) (save-excursion
2817		      (viper-backward-char-carefully)
2818		      (viper-looking-at-separator)))
2819	(viper-backward-char-carefully))
2820    (viper-skip-all-separators-backward 'within-line)
2821    (viper-backward-char-carefully)
2822    (if (looking-at "\n")
2823	(viper-skip-all-separators-backward 'within-line)
2824      (or (viper-looking-at-separator) (forward-char)))))
2825
2826
2827(defun viper-forward-word-kernel (val)
2828  (while (> val 0)
2829    (cond ((viper-looking-at-alpha)
2830	   (viper-skip-alpha-forward "_")
2831	   (viper-skip-separators t))
2832	  ((viper-looking-at-separator)
2833	   (viper-skip-separators t))
2834	  ((not (viper-looking-at-alphasep))
2835	   (viper-skip-nonalphasep-forward)
2836	   (viper-skip-separators t)))
2837    (setq val (1- val))))
2838
2839;; first skip non-newline separators backward, then skip \n.  Then, if TWICE is
2840;; non-nil, skip non-\n back again, but don't overshoot the limit LIM.
2841(defun viper-separator-skipback-special (twice lim)
2842  (let ((prev-char (viper-char-at-pos 'backward))
2843	(saved-point (point)))
2844    ;; skip non-newline separators backward
2845    (while (and (not (viper-memq-char prev-char '(nil \n)))
2846		(< lim (point))
2847		;; must be non-newline separator
2848		(if (eq viper-syntax-preference 'strict-vi)
2849		    (viper-memq-char prev-char '(?\  ?\t))
2850		  (viper-memq-char (char-syntax prev-char) '(?\  ?-))))
2851      (viper-backward-char-carefully)
2852      (setq prev-char (viper-char-at-pos 'backward)))
2853
2854    (if (and (< lim (point)) (eq prev-char ?\n))
2855	(backward-char)
2856      ;; If we skipped to the next word and the prefix of this line doesn't
2857      ;; consist of separators preceded by a newline, then don't skip backwards
2858      ;; at all.
2859      (goto-char saved-point))
2860    (setq prev-char (viper-char-at-pos 'backward))
2861
2862    ;; skip again, but make sure we don't overshoot the limit
2863    (if twice
2864	(while (and (not (viper-memq-char prev-char '(nil \n)))
2865		    (< lim (point))
2866		    ;; must be non-newline separator
2867		    (if (eq viper-syntax-preference 'strict-vi)
2868			(viper-memq-char prev-char '(?\  ?\t))
2869		      (viper-memq-char (char-syntax prev-char) '(?\  ?-))))
2870	  (viper-backward-char-carefully)
2871	  (setq prev-char (viper-char-at-pos 'backward))))
2872
2873    (if (= (point) lim)
2874	(viper-forward-char-carefully))
2875    ))
2876
2877
2878(defun viper-forward-word (arg)
2879  "Forward word."
2880  (interactive "P")
2881  (viper-leave-region-active)
2882  (let ((val (viper-p-val arg))
2883	(com (viper-getcom arg)))
2884    (if com (viper-move-marker-locally 'viper-com-point (point)))
2885    (viper-forward-word-kernel val)
2886    (if com
2887	(progn
2888	  (cond ((viper-char-equal com ?c)
2889		 (viper-separator-skipback-special 'twice viper-com-point))
2890		;; Yank words including the whitespace, but not newline
2891		((viper-char-equal com ?y)
2892		 (viper-separator-skipback-special nil viper-com-point))
2893		((viper-dotable-command-p com)
2894		 (viper-separator-skipback-special nil viper-com-point)))
2895	  (viper-execute-com 'viper-forward-word val com)))
2896    ))
2897
2898
2899(defun viper-forward-Word (arg)
2900  "Forward word delimited by white characters."
2901  (interactive "P")
2902  (viper-leave-region-active)
2903  (let ((val (viper-p-val arg))
2904	(com (viper-getcom arg)))
2905    (if com (viper-move-marker-locally 'viper-com-point (point)))
2906    (viper-loop val
2907		(viper-skip-nonseparators 'forward)
2908		(viper-skip-separators t))
2909    (if com (progn
2910	      (cond ((viper-char-equal com ?c)
2911		     (viper-separator-skipback-special 'twice viper-com-point))
2912		    ;; Yank words including the whitespace, but not newline
2913		    ((viper-char-equal com ?y)
2914		     (viper-separator-skipback-special nil viper-com-point))
2915		    ((viper-dotable-command-p com)
2916		     (viper-separator-skipback-special nil viper-com-point)))
2917	      (viper-execute-com 'viper-forward-Word val com)))))
2918
2919
2920;; this is a bit different from Vi, but Vi's end of word
2921;; makes no sense whatsoever
2922(defun viper-end-of-word-kernel ()
2923  (if (viper-end-of-word-p) (forward-char))
2924  (if (viper-looking-at-separator)
2925      (viper-skip-all-separators-forward))
2926
2927  (cond ((viper-looking-at-alpha) (viper-skip-alpha-forward "_"))
2928	((not (viper-looking-at-alphasep)) (viper-skip-nonalphasep-forward)))
2929  (viper-backward-char-carefully))
2930
2931(defun viper-end-of-word-p ()
2932  (or (eobp)
2933      (save-excursion
2934	(cond ((viper-looking-at-alpha)
2935	       (forward-char)
2936	       (not (viper-looking-at-alpha)))
2937	      ((not (viper-looking-at-alphasep))
2938	       (forward-char)
2939	       (viper-looking-at-alphasep))))))
2940
2941
2942(defun viper-end-of-word (arg &optional careful)
2943  "Move point to end of current word."
2944  (interactive "P")
2945  (viper-leave-region-active)
2946  (let ((val (viper-p-val arg))
2947	(com (viper-getcom arg)))
2948    (if com (viper-move-marker-locally 'viper-com-point (point)))
2949    (viper-loop val (viper-end-of-word-kernel))
2950    (if com
2951	(progn
2952	  (forward-char)
2953	  (viper-execute-com 'viper-end-of-word val com)))))
2954
2955(defun viper-end-of-Word (arg)
2956  "Forward to end of word delimited by white character."
2957  (interactive "P")
2958  (viper-leave-region-active)
2959  (let ((val (viper-p-val arg))
2960	(com (viper-getcom arg)))
2961    (if com (viper-move-marker-locally 'viper-com-point (point)))
2962    (viper-loop val
2963		(viper-end-of-word-kernel)
2964		(viper-skip-nonseparators 'forward)
2965		(backward-char))
2966    (if com
2967	(progn
2968	  (forward-char)
2969	  (viper-execute-com 'viper-end-of-Word val com)))))
2970
2971(defun viper-backward-word-kernel (val)
2972  (while (> val 0)
2973    (viper-backward-char-carefully)
2974    (cond ((viper-looking-at-alpha)
2975	   (viper-skip-alpha-backward "_"))
2976	  ((viper-looking-at-separator)
2977	   (forward-char)
2978	   (viper-skip-separators nil)
2979	   (viper-backward-char-carefully)
2980	   (cond ((viper-looking-at-alpha)
2981		  (viper-skip-alpha-backward "_"))
2982		 ((not (viper-looking-at-alphasep))
2983		  (viper-skip-nonalphasep-backward))
2984		 ((bobp)) ; could still be at separator, but at beg of buffer
2985		 (t (forward-char))))
2986	  ((not (viper-looking-at-alphasep))
2987	   (viper-skip-nonalphasep-backward)))
2988    (setq val (1- val))))
2989
2990(defun viper-backward-word (arg)
2991  "Backward word."
2992  (interactive "P")
2993  (viper-leave-region-active)
2994  (let ((val (viper-p-val arg))
2995	(com (viper-getcom arg)))
2996    (if com
2997	(let (i)
2998	  (if (setq i (save-excursion (backward-char) (looking-at "\n")))
2999	      (backward-char))
3000	  (viper-move-marker-locally 'viper-com-point (point))
3001	  (if i (forward-char))))
3002    (viper-backward-word-kernel val)
3003    (if com (viper-execute-com 'viper-backward-word val com))))
3004
3005(defun viper-backward-Word (arg)
3006  "Backward word delimited by white character."
3007  (interactive "P")
3008  (viper-leave-region-active)
3009  (let ((val (viper-p-val arg))
3010	(com (viper-getcom arg)))
3011    (if com
3012	(let (i)
3013	  (if (setq i (save-excursion (backward-char) (looking-at "\n")))
3014	      (backward-char))
3015	  (viper-move-marker-locally 'viper-com-point (point))
3016	  (if i (forward-char))))
3017    (viper-loop val
3018		(viper-skip-separators nil) ; nil means backward here
3019		(viper-skip-nonseparators 'backward))
3020    (if com (viper-execute-com 'viper-backward-Word val com))))
3021
3022
3023
3024;; line commands
3025
3026(defun viper-beginning-of-line (arg)
3027  "Go to beginning of line."
3028  (interactive "P")
3029  (viper-leave-region-active)
3030  (let ((val (viper-p-val arg))
3031	(com (viper-getcom arg)))
3032    (if com (viper-move-marker-locally 'viper-com-point (point)))
3033    (beginning-of-line val)
3034    (if com (viper-execute-com 'viper-beginning-of-line val com))))
3035
3036(defun viper-bol-and-skip-white (arg)
3037  "Beginning of line at first non-white character."
3038  (interactive "P")
3039  (viper-leave-region-active)
3040  (let ((val (viper-p-val arg))
3041	(com (viper-getcom arg)))
3042    (if com (viper-move-marker-locally 'viper-com-point (point)))
3043    (forward-to-indentation (1- val))
3044    (if com (viper-execute-com 'viper-bol-and-skip-white val com))))
3045
3046(defun viper-goto-eol (arg)
3047  "Go to end of line."
3048  (interactive "P")
3049  (viper-leave-region-active)
3050  (let ((val (viper-p-val arg))
3051	(com (viper-getcom arg)))
3052    (if com (viper-move-marker-locally 'viper-com-point (point)))
3053    (end-of-line val)
3054    (if com (viper-execute-com 'viper-goto-eol val com))
3055    (if viper-ex-style-motion
3056	(if (and (eolp) (not (bolp))
3057		 ;; a fix for viper-change-to-eol
3058		 (not (equal viper-current-state 'insert-state)))
3059	    (backward-char 1)
3060    ))))
3061
3062
3063(defun viper-goto-col (arg)
3064  "Go to ARG's column."
3065  (interactive "P")
3066  (viper-leave-region-active)
3067  (let ((val (viper-p-val arg))
3068	(com (viper-getcom arg))
3069	line-len)
3070    (setq line-len
3071	  (viper-chars-in-region
3072	   (viper-line-pos 'start) (viper-line-pos 'end)))
3073    (if com (viper-move-marker-locally 'viper-com-point (point)))
3074    (beginning-of-line)
3075    (forward-char (1- (min line-len val)))
3076    (while (> (current-column) (1- val))
3077      (backward-char 1))
3078    (if com (viper-execute-com 'viper-goto-col val com))
3079    (save-excursion
3080      (end-of-line)
3081      (if (> val (current-column)) (error "")))
3082    ))
3083
3084
3085(defun viper-next-line (arg)
3086  "Go to next line."
3087  (interactive "P")
3088  (viper-leave-region-active)
3089  (let ((val (viper-p-val arg))
3090	(com (viper-getCom arg)))
3091    (if com (viper-move-marker-locally 'viper-com-point (point)))
3092    (next-line val)
3093    (if viper-ex-style-motion
3094	(if (and (eolp) (not (bolp))) (backward-char 1)))
3095    (setq this-command 'next-line)
3096    (if com (viper-execute-com 'viper-next-line val com))))
3097
3098
3099(defun viper-next-line-at-bol (arg)
3100  "Next line at beginning of line.
3101If point is on a widget or a button, simulate clicking on that widget/button."
3102  (interactive "P")
3103  (let* ((field (get-char-property (point) 'field))
3104	 (button (get-char-property (point) 'button))
3105	 (doc (get-char-property (point) 'widget-doc))
3106	 (widget (or field button doc)))
3107    (if (and widget
3108             (if (symbolp widget)
3109                 (get widget 'widget-type)
3110               (and (consp widget)
3111                    (get (widget-type widget) 'widget-type))))
3112        (widget-button-press (point))
3113      (if (and (fboundp 'button-at) (fboundp 'push-button) (button-at (point)))
3114          (push-button)
3115	;; not a widget or a button
3116        (viper-leave-region-active)
3117        (save-excursion
3118          (end-of-line)
3119          (if (eobp) (error "Last line in buffer")))
3120        (let ((val (viper-p-val arg))
3121              (com (viper-getCom arg)))
3122          (if com (viper-move-marker-locally 'viper-com-point (point)))
3123          (forward-line val)
3124          (back-to-indentation)
3125          (if com (viper-execute-com 'viper-next-line-at-bol val com)))))))
3126
3127
3128(defun viper-previous-line (arg)
3129  "Go to previous line."
3130  (interactive "P")
3131  (viper-leave-region-active)
3132  (let ((val (viper-p-val arg))
3133	(com (viper-getCom arg)))
3134    (if com (viper-move-marker-locally 'viper-com-point (point)))
3135    (previous-line val)
3136    (if viper-ex-style-motion
3137	(if (and (eolp) (not (bolp))) (backward-char 1)))
3138    (setq this-command 'previous-line)
3139    (if com (viper-execute-com 'viper-previous-line val com))))
3140
3141
3142(defun viper-previous-line-at-bol (arg)
3143  "Previous line at beginning of line."
3144  (interactive "P")
3145  (viper-leave-region-active)
3146  (save-excursion
3147    (beginning-of-line)
3148    (if (bobp) (error "First line in buffer")))
3149  (let ((val (viper-p-val arg))
3150	(com (viper-getCom arg)))
3151    (if com (viper-move-marker-locally 'viper-com-point (point)))
3152    (forward-line (- val))
3153    (back-to-indentation)
3154    (if com (viper-execute-com 'viper-previous-line val com))))
3155
3156(defun viper-change-to-eol (arg)
3157  "Change to end of line."
3158  (interactive "P")
3159  (viper-goto-eol (cons arg ?c)))
3160
3161(defun viper-kill-line (arg)
3162  "Delete line."
3163  (interactive "P")
3164  (viper-goto-eol (cons arg ?d)))
3165
3166(defun viper-erase-line (arg)
3167  "Erase line."
3168  (interactive "P")
3169  (viper-beginning-of-line (cons arg ?d)))
3170
3171
3172;;; Moving around
3173
3174(defun viper-goto-line (arg)
3175  "Go to ARG's line.  Without ARG go to end of buffer."
3176  (interactive "P")
3177  (let ((val (viper-P-val arg))
3178	(com (viper-getCom arg)))
3179    (viper-move-marker-locally 'viper-com-point (point))
3180    (viper-deactivate-mark)
3181    (push-mark nil t)
3182    (if (null val)
3183	(goto-char (point-max))
3184      (goto-char (point-min))
3185      (forward-line (1- val)))
3186
3187    ;; positioning is done twice: before and after command execution
3188    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3189    (back-to-indentation)
3190
3191    (if com (viper-execute-com 'viper-goto-line val com))
3192
3193    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3194    (back-to-indentation)
3195    ))
3196
3197;; Find ARG's occurrence of CHAR on the current line.
3198;; If FORWARD then search is forward, otherwise backward.  OFFSET is used to
3199;; adjust point after search.
3200(defun viper-find-char (arg char forward offset)
3201  (or (char-or-string-p char) (error ""))
3202  (let ((arg (if forward arg (- arg)))
3203	(cmd (if (eq viper-intermediate-command 'viper-repeat)
3204		 (nth 5 viper-d-com)
3205	       (viper-array-to-string (this-command-keys))))
3206	point region-beg region-end)
3207    (save-excursion
3208      (save-restriction
3209	(if (> arg 0) ; forward
3210	    (progn
3211	      (setq region-beg (point))
3212	      (if viper-allow-multiline-replace-regions
3213		  (viper-forward-paragraph 1)
3214		(end-of-line))
3215	      (setq region-end (point)))
3216	  (setq region-end (point))
3217	      (if viper-allow-multiline-replace-regions
3218		  (viper-backward-paragraph 1)
3219		(beginning-of-line))
3220	      (setq region-beg (point)))
3221	(if (or (and (< arg 0)
3222		     (< (- region-end region-beg)
3223			(if viper-allow-multiline-replace-regions
3224			    2 1))
3225		     (bolp))
3226		(and (> arg 0)
3227		     (< (- region-end region-beg)
3228			(if viper-allow-multiline-replace-regions
3229			    3 2))
3230		     (eolp)))
3231	    (error "Command `%s':  At %s of %s"
3232		   cmd
3233		   (if (> arg 0) "end" "beginning")
3234		   (if viper-allow-multiline-replace-regions
3235		       "paragraph" "line")))
3236	(narrow-to-region region-beg region-end)
3237	;; if arg > 0, point is forwarded before search.
3238	(if (> arg 0) (goto-char (1+ (point-min)))
3239	  (goto-char (point-max)))
3240	(if (let ((case-fold-search nil))
3241	      (search-forward (char-to-string char) nil 0 arg))
3242	    (setq point (point))
3243	  (error "Command `%s':  `%c' not found" cmd char))))
3244    (goto-char point)
3245    (if (> arg 0)
3246	(backward-char (if offset 2 1))
3247      (forward-char (if offset 1 0)))))
3248
3249(defun viper-find-char-forward (arg)
3250  "Find char on the line.
3251If called interactively read the char to find from the terminal, and if
3252called from viper-repeat, the char last used is used.  This behavior is
3253controlled by the sign of prefix numeric value."
3254  (interactive "P")
3255  (let ((val (viper-p-val arg))
3256	(com (viper-getcom arg))
3257	(cmd-representation (nth 5 viper-d-com)))
3258    (if (> val 0)
3259	;; this means that the function was called interactively
3260	(setq viper-f-char (read-char)
3261	      viper-f-forward t
3262	      viper-f-offset nil)
3263      ;; viper-repeat --- set viper-F-char from command-keys
3264      (setq viper-F-char (if (stringp cmd-representation)
3265			   (viper-seq-last-elt cmd-representation)
3266			 viper-F-char)
3267	    viper-f-char viper-F-char)
3268      (setq val (- val)))
3269    (if com (viper-move-marker-locally 'viper-com-point (point)))
3270    (viper-find-char
3271     val (if (> (viper-p-val arg) 0) viper-f-char viper-F-char) t nil)
3272    (setq val (- val))
3273    (if com
3274	(progn
3275	  (setq viper-F-char viper-f-char) ; set new viper-F-char
3276	  (forward-char)
3277	  (viper-execute-com 'viper-find-char-forward val com)))))
3278
3279(defun viper-goto-char-forward (arg)
3280  "Go up to char ARG forward on line."
3281  (interactive "P")
3282  (let ((val (viper-p-val arg))
3283	(com (viper-getcom arg))
3284	(cmd-representation (nth 5 viper-d-com)))
3285    (if (> val 0)
3286	;; this means that the function was called interactively
3287	(setq viper-f-char (read-char)
3288	      viper-f-forward t
3289	      viper-f-offset t)
3290      ;; viper-repeat --- set viper-F-char from command-keys
3291      (setq viper-F-char (if (stringp cmd-representation)
3292			     (viper-seq-last-elt cmd-representation)
3293			   viper-F-char)
3294	    viper-f-char viper-F-char)
3295      (setq val (- val)))
3296    (if com (viper-move-marker-locally 'viper-com-point (point)))
3297    (viper-find-char
3298     val (if (> (viper-p-val arg) 0) viper-f-char viper-F-char) t t)
3299    (setq val (- val))
3300    (if com
3301	(progn
3302	  (setq viper-F-char viper-f-char) ; set new viper-F-char
3303	  (forward-char)
3304	  (viper-execute-com 'viper-goto-char-forward val com)))))
3305
3306(defun viper-find-char-backward (arg)
3307  "Find char ARG on line backward."
3308  (interactive "P")
3309  (let ((val (viper-p-val arg))
3310	(com (viper-getcom arg))
3311	(cmd-representation (nth 5 viper-d-com)))
3312    (if (> val 0)
3313	;; this means that the function was called interactively
3314	(setq viper-f-char (read-char)
3315	      viper-f-forward nil
3316	      viper-f-offset nil)
3317      ;; viper-repeat --- set viper-F-char from command-keys
3318      (setq viper-F-char (if (stringp cmd-representation)
3319			   (viper-seq-last-elt cmd-representation)
3320			 viper-F-char)
3321	    viper-f-char viper-F-char)
3322      (setq val (- val)))
3323    (if com (viper-move-marker-locally 'viper-com-point (point)))
3324    (viper-find-char
3325     val (if (> (viper-p-val arg) 0) viper-f-char viper-F-char) nil nil)
3326    (setq val (- val))
3327    (if com
3328	(progn
3329	  (setq viper-F-char viper-f-char) ; set new viper-F-char
3330	  (viper-execute-com 'viper-find-char-backward val com)))))
3331
3332(defun viper-goto-char-backward (arg)
3333  "Go up to char ARG backward on line."
3334  (interactive "P")
3335  (let ((val (viper-p-val arg))
3336	(com (viper-getcom arg))
3337	(cmd-representation (nth 5 viper-d-com)))
3338    (if (> val 0)
3339	;; this means that the function was called interactively
3340	(setq viper-f-char (read-char)
3341	      viper-f-forward nil
3342	      viper-f-offset t)
3343      ;; viper-repeat --- set viper-F-char from command-keys
3344      (setq viper-F-char (if (stringp cmd-representation)
3345			   (viper-seq-last-elt cmd-representation)
3346			 viper-F-char)
3347	    viper-f-char viper-F-char)
3348      (setq val (- val)))
3349    (if com (viper-move-marker-locally 'viper-com-point (point)))
3350    (viper-find-char
3351     val (if (> (viper-p-val arg) 0) viper-f-char viper-F-char) nil t)
3352    (setq val (- val))
3353    (if com
3354	(progn
3355	  (setq viper-F-char viper-f-char) ; set new viper-F-char
3356	  (viper-execute-com 'viper-goto-char-backward val com)))))
3357
3358(defun viper-repeat-find (arg)
3359  "Repeat previous find command."
3360  (interactive "P")
3361  (let ((val (viper-p-val arg))
3362	(com (viper-getcom arg)))
3363    (viper-deactivate-mark)
3364    (if com (viper-move-marker-locally 'viper-com-point (point)))
3365    (viper-find-char val viper-f-char viper-f-forward viper-f-offset)
3366    (if com
3367	(progn
3368	  (if viper-f-forward (forward-char))
3369	  (viper-execute-com 'viper-repeat-find val com)))))
3370
3371(defun viper-repeat-find-opposite (arg)
3372  "Repeat previous find command in the opposite direction."
3373  (interactive "P")
3374  (let ((val (viper-p-val arg))
3375	(com (viper-getcom arg)))
3376    (viper-deactivate-mark)
3377    (if com (viper-move-marker-locally 'viper-com-point (point)))
3378    (viper-find-char val viper-f-char (not viper-f-forward) viper-f-offset)
3379    (if com
3380	(progn
3381	  (if viper-f-forward (forward-char))
3382	  (viper-execute-com 'viper-repeat-find-opposite val com)))))
3383
3384
3385;; window scrolling etc.
3386
3387(defun viper-window-top (arg)
3388  "Go to home window line."
3389  (interactive "P")
3390  (let ((val (viper-p-val arg))
3391	(com (viper-getCom arg)))
3392    (viper-leave-region-active)
3393    (if com (viper-move-marker-locally 'viper-com-point (point)))
3394    (push-mark nil t)
3395    (move-to-window-line (1- val))
3396
3397    ;; positioning is done twice: before and after command execution
3398    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3399    (back-to-indentation)
3400
3401    (if com (viper-execute-com 'viper-window-top val com))
3402
3403    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3404    (back-to-indentation)
3405    ))
3406
3407(defun viper-window-middle (arg)
3408  "Go to middle window line."
3409  (interactive "P")
3410  (let ((val (viper-p-val arg))
3411	(com (viper-getCom arg)))
3412    (viper-leave-region-active)
3413    (if com (viper-move-marker-locally 'viper-com-point (point)))
3414    (push-mark nil t)
3415    (move-to-window-line (+ (/ (1- (window-height)) 2) (1- val)))
3416
3417    ;; positioning is done twice: before and after command execution
3418    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3419    (back-to-indentation)
3420
3421    (if com (viper-execute-com 'viper-window-middle val com))
3422
3423    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3424    (back-to-indentation)
3425    ))
3426
3427(defun viper-window-bottom (arg)
3428  "Go to last window line."
3429  (interactive "P")
3430  (let ((val (viper-p-val arg))
3431	(com (viper-getCom arg)))
3432    (viper-leave-region-active)
3433    (if com (viper-move-marker-locally 'viper-com-point (point)))
3434    (push-mark nil t)
3435    (move-to-window-line (- val))
3436
3437    ;; positioning is done twice: before and after command execution
3438    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3439    (back-to-indentation)
3440
3441    (if com (viper-execute-com 'viper-window-bottom val com))
3442
3443    (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
3444    (back-to-indentation)
3445    ))
3446
3447(defun viper-line-to-top (arg)
3448  "Put current line on the home line."
3449  (interactive "p")
3450  (recenter (1- arg)))
3451
3452(defun viper-line-to-middle (arg)
3453  "Put current line on the middle line."
3454  (interactive "p")
3455  (recenter (+ (1- arg) (/ (1- (window-height)) 2))))
3456
3457(defun viper-line-to-bottom (arg)
3458  "Put current line on the last line."
3459  (interactive "p")
3460  (recenter (- (window-height) (1+ arg))))
3461
3462;; If point is within viper-search-scroll-threshold of window top or bottom,
3463;; scroll up or down 1/7 of window height, depending on whether we are at the
3464;; bottom or at the top of the  window.  This function is called by viper-search
3465;; (which is called from viper-search-forward/backward/next).  If the value of
3466;; viper-search-scroll-threshold is negative - don't scroll.
3467(defun viper-adjust-window ()
3468  (let ((win-height (viper-cond-compile-for-xemacs-or-emacs
3469		     (window-displayed-height) ; xemacs
3470		     ;; emacs
3471		     (1- (window-height)) ; adjust for modeline
3472		     ))
3473	(pt (point))
3474	at-top-p at-bottom-p
3475	min-scroll direction)
3476    (save-excursion
3477      (move-to-window-line 0) ; top
3478      (setq at-top-p
3479	    (<= (count-lines pt (point))
3480		viper-search-scroll-threshold))
3481      (move-to-window-line -1) ; bottom
3482      (setq at-bottom-p
3483	    (<= (count-lines pt (point)) viper-search-scroll-threshold))
3484      )
3485    (cond (at-top-p (setq min-scroll (1- viper-search-scroll-threshold)
3486			  direction  1))
3487	  (at-bottom-p (setq min-scroll (1+ viper-search-scroll-threshold)
3488			     direction -1)))
3489    (if min-scroll
3490	(recenter
3491	 (* (max min-scroll (/ win-height 7)) direction)))
3492    ))
3493
3494
3495;; paren match
3496;; must correct this to only match ( to ) etc.  On the other hand
3497;; it is good that paren match gets confused, because that way you
3498;; catch _all_ imbalances.
3499
3500(defun viper-paren-match (arg)
3501  "Go to the matching parenthesis."
3502  (interactive "P")
3503  (viper-leave-region-active)
3504  (let ((com (viper-getcom arg))
3505	(parse-sexp-ignore-comments viper-parse-sexp-ignore-comments)
3506	anchor-point)
3507    (if (integerp arg)
3508	(if (or (> arg 99) (< arg 1))
3509	    (error "Prefix must be between 1 and 99")
3510	  (goto-char
3511	   (if (> (point-max) 80000)
3512	       (* (/ (point-max) 100) arg)
3513	     (/ (* (point-max) arg) 100)))
3514	  (back-to-indentation))
3515      (let (beg-lim end-lim)
3516	(if (and (eolp) (not (bolp))) (forward-char -1))
3517	(if (not (looking-at "[][(){}]"))
3518	    (setq anchor-point (point)))
3519	(save-excursion
3520	  (beginning-of-line)
3521	  (setq beg-lim (point))
3522	  (end-of-line)
3523	  (setq end-lim (point)))
3524	(cond ((re-search-forward "[][(){}]" end-lim t)
3525	       (backward-char) )
3526	      ((re-search-backward "[][(){}]" beg-lim t))
3527	      (t
3528	       (error "No matching character on line"))))
3529      (cond ((looking-at "[\(\[{]")
3530	     (if com (viper-move-marker-locally 'viper-com-point (point)))
3531	     (forward-sexp 1)
3532	     (if com
3533		 (viper-execute-com 'viper-paren-match nil com)
3534	       (backward-char)))
3535	    (anchor-point
3536	     (if com
3537		 (progn
3538		   (viper-move-marker-locally 'viper-com-point anchor-point)
3539		   (forward-char 1)
3540		   (viper-execute-com 'viper-paren-match nil com)
3541		   )))
3542	    ((looking-at "[])}]")
3543	     (forward-char)
3544	     (if com (viper-move-marker-locally 'viper-com-point (point)))
3545	     (backward-sexp 1)
3546	     (if com (viper-execute-com 'viper-paren-match nil com)))
3547	    (t (error ""))))))
3548
3549(defun viper-toggle-parse-sexp-ignore-comments ()
3550  (interactive)
3551  (setq viper-parse-sexp-ignore-comments
3552	(not viper-parse-sexp-ignore-comments))
3553  (princ (format
3554	  "From now on, `%%' will %signore parentheses inside comment fields"
3555	  (if viper-parse-sexp-ignore-comments "" "NOT "))))
3556
3557
3558;; sentence, paragraph and heading
3559
3560(defun viper-forward-sentence (arg)
3561  "Forward sentence."
3562  (interactive "P")
3563  (or (eq last-command this-command)
3564      (push-mark nil t))
3565  (let ((val (viper-p-val arg))
3566	(com (viper-getcom arg)))
3567    (if com (viper-move-marker-locally 'viper-com-point (point)))
3568    (forward-sentence val)
3569    (if com (viper-execute-com 'viper-forward-sentence nil com))))
3570
3571(defun viper-backward-sentence (arg)
3572  "Backward sentence."
3573  (interactive "P")
3574  (or (eq last-command this-command)
3575      (push-mark nil t))
3576  (let ((val (viper-p-val arg))
3577	(com (viper-getcom arg)))
3578    (if com (viper-move-marker-locally 'viper-com-point (point)))
3579    (backward-sentence val)
3580    (if com (viper-execute-com 'viper-backward-sentence nil com))))
3581
3582(defun viper-forward-paragraph (arg)
3583  "Forward paragraph."
3584  (interactive "P")
3585  (or (eq last-command this-command)
3586      (push-mark nil t))
3587  (let ((val (viper-p-val arg))
3588	;; if you want d} operate on whole lines, change viper-getcom to
3589	;; viper-getCom below
3590	(com (viper-getcom arg)))
3591    (if com (viper-move-marker-locally 'viper-com-point (point)))
3592    (forward-paragraph val)
3593    (if com
3594	(progn
3595	  (backward-char 1)
3596	  (viper-execute-com 'viper-forward-paragraph nil com)))))
3597
3598(defun viper-backward-paragraph (arg)
3599  "Backward paragraph."
3600  (interactive "P")
3601  (or (eq last-command this-command)
3602      (push-mark nil t))
3603  (let ((val (viper-p-val arg))
3604	;; if you want d{ operate on whole lines, change viper-getcom to
3605	;; viper-getCom below
3606	(com (viper-getcom arg)))
3607    (if com (viper-move-marker-locally 'viper-com-point (point)))
3608    (backward-paragraph val)
3609    (if com
3610	(progn
3611	  (forward-char 1)
3612	  (viper-execute-com 'viper-backward-paragraph nil com)
3613	  (backward-char 1)))))
3614
3615;; should be mode-specific
3616(defun viper-prev-heading (arg)
3617  (interactive "P")
3618  (let ((val (viper-p-val arg))
3619	(com (viper-getCom arg)))
3620    (if com (viper-move-marker-locally 'viper-com-point (point)))
3621    (re-search-backward viper-heading-start nil t val)
3622    (goto-char (match-beginning 0))
3623    (if com (viper-execute-com 'viper-prev-heading nil com))))
3624
3625(defun viper-heading-end (arg)
3626  (interactive "P")
3627  (let ((val (viper-p-val arg))
3628	(com (viper-getCom arg)))
3629    (if com (viper-move-marker-locally 'viper-com-point (point)))
3630    (re-search-forward viper-heading-end nil t val)
3631    (goto-char (match-beginning 0))
3632    (if com (viper-execute-com 'viper-heading-end nil com))))
3633
3634(defun viper-next-heading (arg)
3635  (interactive "P")
3636  (let ((val (viper-p-val arg))
3637	(com (viper-getCom arg)))
3638    (if com (viper-move-marker-locally 'viper-com-point (point)))
3639    (end-of-line)
3640    (re-search-forward viper-heading-start nil t val)
3641    (goto-char (match-beginning 0))
3642    (if com (viper-execute-com 'viper-next-heading nil com))))
3643
3644
3645;; scrolling
3646
3647(defun viper-scroll-screen (arg)
3648  "Scroll to next screen."
3649  (interactive "p")
3650  (condition-case nil
3651      (if (> arg 0)
3652	  (while (> arg 0)
3653	    (scroll-up)
3654	    (setq arg (1- arg)))
3655	(while (> 0 arg)
3656	  (scroll-down)
3657	  (setq arg (1+ arg))))
3658    (error (beep 1)
3659	   (if (> arg 0)
3660	       (progn
3661		 (message "End of buffer")
3662		 (goto-char (point-max)))
3663	     (message "Beginning of buffer")
3664	     (goto-char (point-min))))
3665    ))
3666
3667(defun viper-scroll-screen-back (arg)
3668  "Scroll to previous screen."
3669  (interactive "p")
3670  (viper-scroll-screen (- arg)))
3671
3672(defun viper-scroll-down (arg)
3673  "Pull down half screen."
3674  (interactive "P")
3675  (condition-case nil
3676      (if (null arg)
3677	  (scroll-down (/ (window-height) 2))
3678	(scroll-down arg))
3679    (error (beep 1)
3680	   (message "Beginning of buffer")
3681	   (goto-char (point-min)))))
3682
3683(defun viper-scroll-down-one (arg)
3684  "Scroll up one line."
3685  (interactive "p")
3686  (scroll-down arg))
3687
3688(defun viper-scroll-up (arg)
3689  "Pull up half screen."
3690  (interactive "P")
3691  (condition-case nil
3692      (if (null arg)
3693	  (scroll-up (/ (window-height) 2))
3694	(scroll-up arg))
3695    (error (beep 1)
3696	   (message "End of buffer")
3697	   (goto-char (point-max)))))
3698
3699(defun viper-scroll-up-one (arg)
3700  "Scroll down one line."
3701  (interactive "p")
3702  (scroll-up arg))
3703
3704
3705;; searching
3706
3707(defun viper-if-string (prompt)
3708  (if (memq viper-intermediate-command
3709	    '(viper-command-argument viper-digit-argument viper-repeat))
3710      (setq viper-this-command-keys (this-command-keys)))
3711  (let ((s (viper-read-string-with-history
3712	    prompt
3713	    nil ; no initial
3714	    'viper-search-history
3715	    (car viper-search-history))))
3716    (if (not (string= s ""))
3717	(setq viper-s-string s))))
3718
3719
3720(defun viper-toggle-search-style (arg)
3721  "Toggle the value of viper-case-fold-search/viper-re-search.
3722Without prefix argument, will ask which search style to toggle.  With prefix
3723arg 1,toggles viper-case-fold-search; with arg 2 toggles viper-re-search.
3724
3725Although this function is bound to \\[viper-toggle-search-style], the most
3726convenient way to use it is to bind `//' to the macro
3727`1 M-x viper-toggle-search-style' and `///' to
3728`2 M-x viper-toggle-search-style'.  In this way, hitting `//' quickly will
3729toggle case-fold-search and hitting `/' three times witth toggle regexp
3730search.  Macros are more convenient in this case because they don't affect
3731the Emacs binding of `/'."
3732  (interactive "P")
3733  (let (msg)
3734    (cond ((or (eq arg 1)
3735	       (and (null arg)
3736		    (y-or-n-p (format "Search style: '%s'.  Want '%s'? "
3737				      (if viper-case-fold-search
3738					  "case-insensitive" "case-sensitive")
3739				      (if viper-case-fold-search
3740					  "case-sensitive"
3741					"case-insensitive")))))
3742	   (setq viper-case-fold-search (null viper-case-fold-search))
3743	   (if viper-case-fold-search
3744	       (setq msg "Search becomes case-insensitive")
3745	     (setq msg "Search becomes case-sensitive")))
3746	  ((or (eq arg 2)
3747	       (and (null arg)
3748		    (y-or-n-p (format "Search style: '%s'.  Want '%s'? "
3749				      (if viper-re-search
3750					  "regexp-search" "vanilla-search")
3751				      (if viper-re-search
3752					  "vanilla-search"
3753					"regexp-search")))))
3754	   (setq viper-re-search (null viper-re-search))
3755	   (if viper-re-search
3756	       (setq msg "Search becomes regexp-style")
3757	     (setq msg "Search becomes vanilla-style")))
3758	  (t
3759	   (setq msg "Search style remains unchanged")))
3760    (princ msg t)))
3761
3762(defun viper-set-searchstyle-toggling-macros (unset &optional major-mode)
3763  "Set the macros for toggling the search style in Viper's vi-state.
3764The macro that toggles case sensitivity is bound to `//', and the one that
3765toggles regexp search is bound to `///'.
3766With a prefix argument, this function unsets the macros.
3767If MAJOR-MODE is set, set the macros only in that major mode."
3768  (interactive "P")
3769  (let (scope)
3770    (if (and major-mode (symbolp major-mode))
3771	(setq scope major-mode)
3772      (setq scope 't))
3773    (or noninteractive
3774	(if (not unset)
3775	    (progn
3776	      ;; toggle case sensitivity in search
3777	      (viper-record-kbd-macro
3778	       "//" 'vi-state
3779	       [1 (meta x) v i p e r - t o g g l e - s e a r c h - s t y l e return]
3780	       scope)
3781	      ;; toggle regexp/vanila search
3782	      (viper-record-kbd-macro
3783	       "///" 'vi-state
3784	       [2 (meta x) v i p e r - t o g g l e - s e a r c h - s t y l e return]
3785	       scope)
3786	      (if (interactive-p)
3787		  (message
3788		   "// and /// now toggle case-sensitivity and regexp search")))
3789	  (viper-unrecord-kbd-macro "//" 'vi-state)
3790	  (sit-for 2)
3791	  (viper-unrecord-kbd-macro "///" 'vi-state)))
3792    ))
3793
3794
3795(defun viper-set-parsing-style-toggling-macro (unset)
3796  "Set `%%%' to be a macro that toggles whether comment fields should be parsed for matching parentheses.
3797This is used in conjunction with the `%' command.
3798
3799With a prefix argument, unsets the macro."
3800  (interactive "P")
3801  (or noninteractive
3802      (if (not unset)
3803	  (progn
3804	    ;; Make %%% toggle parsing comments for matching parentheses
3805	    (viper-record-kbd-macro
3806	     "%%%" 'vi-state
3807	     [(meta x) v i p e r - t o g g l e - p a r s e - s e x p - i g n o r e - c o m m e n t s return]
3808	     't)
3809	    (if (interactive-p)
3810		(message
3811		 "%%%%%% now toggles whether comments should be parsed for matching parentheses")))
3812	(viper-unrecord-kbd-macro "%%%" 'vi-state))))
3813
3814
3815(defun viper-set-emacs-state-searchstyle-macros (unset &optional arg-majormode)
3816  "Set the macros for toggling the search style in Viper's emacs-state.
3817The macro that toggles case sensitivity is bound to `//', and the one that
3818toggles regexp search is bound to `///'.
3819With a prefix argument, this function unsets the macros.
3820If the optional prefix argument is non-nil and specifies a valid major mode,
3821this sets the macros only in the macros in that major mode.  Otherwise,
3822the macros are set in the current major mode.
3823\(When unsetting the macros, the second argument has no effect.\)"
3824  (interactive "P")
3825  (or noninteractive
3826      (if (not unset)
3827	  (progn
3828	    ;; toggle case sensitivity in search
3829	    (viper-record-kbd-macro
3830	     "//" 'emacs-state
3831	     [1 (meta x) v i p e r - t o g g l e - s e a r c h - s t y l e return]
3832	     (or arg-majormode major-mode))
3833	    ;; toggle regexp/vanila search
3834	    (viper-record-kbd-macro
3835	     "///" 'emacs-state
3836	     [2 (meta x) v i p e r - t o g g l e - s e a r c h - s t y l e return]
3837	     (or arg-majormode major-mode))
3838	    (if (interactive-p)
3839		(message
3840		 "// and /// now toggle case-sensitivity and regexp search.")))
3841	(viper-unrecord-kbd-macro "//" 'emacs-state)
3842	(sit-for 2)
3843	(viper-unrecord-kbd-macro "///" 'emacs-state))))
3844
3845
3846(defun viper-search-forward (arg)
3847  "Search a string forward.
3848ARG is used to find the ARG's occurrence of the string.
3849Null string will repeat previous search."
3850  (interactive "P")
3851  (let ((val (viper-P-val arg))
3852	(com (viper-getcom arg))
3853	(old-str viper-s-string)
3854	debug-on-error)
3855    (setq viper-s-forward t)
3856    (viper-if-string "/")
3857    ;; this is not used at present, but may be used later
3858    (if (or (not (equal old-str viper-s-string))
3859	    (not (markerp viper-local-search-start-marker))
3860	    (not (marker-buffer viper-local-search-start-marker)))
3861	(setq viper-local-search-start-marker (point-marker)))
3862    (viper-search viper-s-string t val)
3863    (if com
3864	(progn
3865	  (viper-move-marker-locally 'viper-com-point (mark t))
3866	  (viper-execute-com 'viper-search-next val com)))
3867    ))
3868
3869(defun viper-search-backward (arg)
3870  "Search a string backward.
3871ARG is used to find the ARG's occurrence of the string.
3872Null string will repeat previous search."
3873  (interactive "P")
3874  (let ((val (viper-P-val arg))
3875	(com (viper-getcom arg))
3876	(old-str viper-s-string)
3877	debug-on-error)
3878    (setq viper-s-forward nil)
3879    (viper-if-string "?")
3880    ;; this is not used at present, but may be used later
3881    (if (or (not (equal old-str viper-s-string))
3882	    (not (markerp viper-local-search-start-marker))
3883	    (not (marker-buffer viper-local-search-start-marker)))
3884	(setq viper-local-search-start-marker (point-marker)))
3885    (viper-search viper-s-string nil val)
3886    (if com
3887	(progn
3888	  (viper-move-marker-locally 'viper-com-point (mark t))
3889	  (viper-execute-com 'viper-search-next val com)))))
3890
3891
3892;; Search for COUNT's occurrence of STRING.
3893;; Search is forward if FORWARD is non-nil, otherwise backward.
3894;; INIT-POINT is the position where search is to start.
3895;; Arguments:
3896;;   (STRING FORW COUNT &optional NO-OFFSET INIT-POINT LIMIT FAIL-IF-NOT-FOUND)
3897(defun viper-search (string forward arg
3898			    &optional no-offset init-point fail-if-not-found)
3899  (if (not (equal string ""))
3900    (let ((val (viper-p-val arg))
3901	  (com (viper-getcom arg))
3902	  (offset (not no-offset))
3903	  (case-fold-search viper-case-fold-search)
3904	  (start-point (or init-point (point))))
3905      (viper-deactivate-mark)
3906      (if forward
3907	  (condition-case nil
3908	      (progn
3909	        (if offset (viper-forward-char-carefully))
3910	        (if viper-re-search
3911		    (progn
3912		      (re-search-forward string nil nil val)
3913		      (re-search-backward string))
3914		  (search-forward string nil nil val)
3915		  (search-backward string))
3916		(if (not (equal start-point (point)))
3917		    (push-mark start-point t)))
3918	    (search-failed
3919	     (if (and (not fail-if-not-found) viper-search-wrap-around-t)
3920	         (progn
3921		   (message "Search wrapped around BOTTOM of buffer")
3922		   (goto-char (point-min))
3923		   (viper-search string forward (cons 1 com) t start-point 'fail)
3924		   ;; don't wait in macros
3925		   (or executing-kbd-macro
3926		       (memq viper-intermediate-command
3927			     '(viper-repeat
3928			       viper-digit-argument
3929			       viper-command-argument))
3930		       (sit-for 2))
3931		   ;; delete the wrap-around message
3932		   (message "")
3933		   )
3934	       (goto-char start-point)
3935	       (error "`%s': %s not found"
3936		      string
3937		      (if viper-re-search "Pattern" "String"))
3938	       )))
3939	;; backward
3940        (condition-case nil
3941	    (progn
3942	      (if viper-re-search
3943		  (re-search-backward string nil nil val)
3944	        (search-backward string nil nil val))
3945	      (if (not (equal start-point (point)))
3946		  (push-mark start-point t)))
3947	  (search-failed
3948	   (if (and (not fail-if-not-found) viper-search-wrap-around-t)
3949	       (progn
3950		 (message "Search wrapped around TOP of buffer")
3951	         (goto-char (point-max))
3952	         (viper-search string forward (cons 1 com) t start-point 'fail)
3953		 ;; don't wait in macros
3954		 (or executing-kbd-macro
3955		     (memq viper-intermediate-command
3956			   '(viper-repeat
3957			     viper-digit-argument
3958			     viper-command-argument))
3959		     (sit-for 2))
3960		 ;; delete the wrap-around message
3961		 (message "")
3962		 )
3963	     (goto-char start-point)
3964	     (error "`%s': %s not found"
3965		    string
3966		    (if viper-re-search "Pattern" "String"))
3967	     ))))
3968      ;; pull up or down if at top/bottom of window
3969      (viper-adjust-window)
3970      ;; highlight the result of search
3971      ;; don't wait and don't highlight in macros
3972      (or executing-kbd-macro
3973	  (memq viper-intermediate-command
3974		'(viper-repeat viper-digit-argument viper-command-argument))
3975	  (viper-flash-search-pattern))
3976      )))
3977
3978(defun viper-search-next (arg)
3979  "Repeat previous search."
3980  (interactive "P")
3981  (let ((val (viper-p-val arg))
3982	(com (viper-getcom arg))
3983	debug-on-error)
3984    (if (or (null viper-s-string) (string= viper-s-string ""))
3985	(error viper-NoPrevSearch))
3986    (viper-search viper-s-string viper-s-forward arg)
3987    (if com
3988	(progn
3989	  (viper-move-marker-locally 'viper-com-point (mark t))
3990	  (viper-execute-com 'viper-search-next val com)))))
3991
3992(defun viper-search-Next (arg)
3993  "Repeat previous search in the reverse direction."
3994  (interactive "P")
3995  (let ((val (viper-p-val arg))
3996	(com (viper-getcom arg))
3997	debug-on-error)
3998    (if (null viper-s-string) (error viper-NoPrevSearch))
3999    (viper-search viper-s-string (not viper-s-forward) arg)
4000    (if com
4001	(progn
4002	  (viper-move-marker-locally 'viper-com-point (mark t))
4003	  (viper-execute-com 'viper-search-Next val com)))))
4004
4005
4006;; Search contents of buffer defined by one of Viper's motion commands.
4007;; Repeatable via `n' and `N'.
4008(defun viper-buffer-search-enable (&optional c)
4009  (cond (c (setq viper-buffer-search-char c))
4010	((null viper-buffer-search-char)
4011	 ;; ?g acts as a default value for viper-buffer-search-char
4012	 (setq viper-buffer-search-char ?g)))
4013  (define-key viper-vi-basic-map
4014    (cond ((viper-characterp viper-buffer-search-char)
4015	   (char-to-string viper-buffer-search-char))
4016	  (t (error "viper-buffer-search-char: wrong value type, %S"
4017		    viper-buffer-search-char)))
4018    'viper-command-argument)
4019  (aset viper-exec-array viper-buffer-search-char 'viper-exec-buffer-search)
4020  (setq viper-prefix-commands
4021	(cons viper-buffer-search-char viper-prefix-commands)))
4022
4023;; This is a Viper wraper for isearch-forward.
4024(defun viper-isearch-forward (arg)
4025  "Do incremental search forward."
4026  (interactive "P")
4027  ;; emacs bug workaround
4028  (if (listp arg) (setq arg (car arg)))
4029  (viper-exec-form-in-emacs (list 'isearch-forward arg)))
4030
4031;; This is a Viper wraper for isearch-backward."
4032(defun viper-isearch-backward (arg)
4033  "Do incremental search backward."
4034  (interactive "P")
4035  ;; emacs bug workaround
4036  (if (listp arg) (setq arg (car arg)))
4037  (viper-exec-form-in-emacs (list 'isearch-backward arg)))
4038
4039
4040;; visiting and killing files, buffers
4041
4042(defun viper-switch-to-buffer ()
4043  "Switch to buffer in the current window."
4044  (interactive)
4045  (let ((other-buffer (other-buffer (current-buffer)))
4046	buffer)
4047    (setq buffer
4048	  (funcall viper-read-buffer-function
4049		   "Switch to buffer in this window: " other-buffer))
4050    (switch-to-buffer buffer)))
4051
4052(defun viper-switch-to-buffer-other-window ()
4053  "Switch to buffer in another window."
4054  (interactive)
4055  (let ((other-buffer (other-buffer (current-buffer)))
4056	buffer)
4057    (setq buffer
4058	  (funcall viper-read-buffer-function
4059		   "Switch to buffer in another window: " other-buffer))
4060    (switch-to-buffer-other-window buffer)))
4061
4062(defun viper-kill-buffer ()
4063  "Kill a buffer."
4064  (interactive)
4065  (let (buffer buffer-name)
4066    (setq buffer-name
4067	  (funcall viper-read-buffer-function
4068		   (format "Kill buffer \(%s\): "
4069			   (buffer-name (current-buffer)))))
4070    (setq buffer
4071	  (if (null buffer-name)
4072	      (current-buffer)
4073	    (get-buffer buffer-name)))
4074    (if (null buffer) (error "`%s': No such buffer" buffer-name))
4075    (if (or (not (buffer-modified-p buffer))
4076	    (y-or-n-p
4077	     (format
4078	      "Buffer `%s' is modified, are you sure you want to kill it? "
4079	      buffer-name)))
4080	(kill-buffer buffer)
4081      (error "Buffer not killed"))))
4082
4083
4084
4085;; yank and pop
4086
4087(defsubst viper-yank (text)
4088  "Yank TEXT silently.  This works correctly with Emacs's yank-pop command."
4089    (insert text)
4090    (setq this-command 'yank))
4091
4092(defun viper-put-back (arg)
4093  "Put back after point/below line."
4094  (interactive "P")
4095  (let ((val (viper-p-val arg))
4096	(text (if viper-use-register
4097		  (cond ((viper-valid-register viper-use-register '(digit))
4098			 (current-kill
4099			  (- viper-use-register ?1) 'do-not-rotate))
4100			((viper-valid-register viper-use-register)
4101			 (get-register (downcase viper-use-register)))
4102			(t (error viper-InvalidRegister viper-use-register)))
4103		(current-kill 0)))
4104	sv-point chars-inserted lines-inserted)
4105    (if (null text)
4106	(if viper-use-register
4107	    (let ((reg viper-use-register))
4108	      (setq viper-use-register nil)
4109	      (error viper-EmptyRegister reg))
4110	  (error "")))
4111    (setq viper-use-register nil)
4112    (if (viper-end-with-a-newline-p text)
4113	(progn
4114	  (end-of-line)
4115	  (if (eobp)
4116	      (insert "\n")
4117	    (forward-line 1))
4118	  (beginning-of-line))
4119      (if (not (eolp)) (viper-forward-char-carefully)))
4120    (set-marker (viper-mark-marker) (point) (current-buffer))
4121    (viper-set-destructive-command
4122     (list 'viper-put-back val nil viper-use-register nil nil))
4123    (setq sv-point (point))
4124    (viper-loop val (viper-yank text))
4125    (setq chars-inserted (abs (- (point) sv-point))
4126	  lines-inserted (abs (count-lines (point) sv-point)))
4127    (if (or (> chars-inserted viper-change-notification-threshold)
4128	    (> lines-inserted viper-change-notification-threshold))
4129	(unless (viper-is-in-minibuffer)
4130	  (message "Inserted %d character(s), %d line(s)"
4131		   chars-inserted lines-inserted))))
4132  ;; Vi puts cursor on the last char when the yanked text doesn't contain a
4133  ;; newline; it leaves the cursor at the beginning when the text contains
4134  ;; a newline
4135  (if (viper-same-line (point) (mark))
4136      (or (= (point) (mark)) (viper-backward-char-carefully))
4137    (exchange-point-and-mark)
4138    (if (bolp)
4139	(back-to-indentation)))
4140  (viper-deactivate-mark))
4141
4142(defun viper-Put-back (arg)
4143  "Put back at point/above line."
4144  (interactive "P")
4145  (let ((val (viper-p-val arg))
4146	(text (if viper-use-register
4147		  (cond ((viper-valid-register viper-use-register '(digit))
4148			 (current-kill
4149			  (- viper-use-register ?1) 'do-not-rotate))
4150			((viper-valid-register viper-use-register)
4151			 (get-register (downcase viper-use-register)))
4152			(t (error viper-InvalidRegister viper-use-register)))
4153		(current-kill 0)))
4154	sv-point chars-inserted lines-inserted)
4155    (if (null text)
4156	(if viper-use-register
4157	    (let ((reg viper-use-register))
4158	      (setq viper-use-register nil)
4159	      (error viper-EmptyRegister reg))
4160	  (error "")))
4161    (setq viper-use-register nil)
4162    (if (viper-end-with-a-newline-p text) (beginning-of-line))
4163    (viper-set-destructive-command
4164     (list 'viper-Put-back val nil viper-use-register nil nil))
4165    (set-marker (viper-mark-marker) (point) (current-buffer))
4166    (setq sv-point (point))
4167    (viper-loop val (viper-yank text))
4168    (setq chars-inserted (abs (- (point) sv-point))
4169	  lines-inserted (abs (count-lines (point) sv-point)))
4170    (if (or (> chars-inserted viper-change-notification-threshold)
4171	    (> lines-inserted viper-change-notification-threshold))
4172	(unless (viper-is-in-minibuffer)
4173	  (message "Inserted %d character(s), %d line(s)"
4174		   chars-inserted lines-inserted))))
4175  ;; Vi puts cursor on the last char when the yanked text doesn't contain a
4176  ;; newline; it leaves the cursor at the beginning when the text contains
4177  ;; a newline
4178  (if (viper-same-line (point) (mark))
4179      (or (= (point) (mark)) (viper-backward-char-carefully))
4180    (exchange-point-and-mark)
4181    (if (bolp)
4182	(back-to-indentation)))
4183  (viper-deactivate-mark))
4184
4185
4186;; Copy region to kill-ring.
4187;; If BEG and END do not belong to the same buffer, copy empty region.
4188(defun viper-copy-region-as-kill (beg end)
4189  (condition-case nil
4190      (copy-region-as-kill beg end)
4191    (error (copy-region-as-kill beg beg))))
4192
4193
4194(defun viper-delete-char (arg)
4195  "Delete next character."
4196  (interactive "P")
4197  (let ((val (viper-p-val arg))
4198	end-del-pos)
4199    (viper-set-destructive-command
4200     (list 'viper-delete-char val nil nil nil nil))
4201    (if (and viper-ex-style-editing
4202	     (> val (viper-chars-in-region (point) (viper-line-pos 'end))))
4203	(setq val (viper-chars-in-region (point) (viper-line-pos 'end))))
4204    (if (and viper-ex-style-motion (eolp))
4205	(if (bolp) (error "") (setq val 0))) ; not bol---simply back 1 ch
4206    (save-excursion
4207      (viper-forward-char-carefully val)
4208      (setq end-del-pos (point)))
4209    (if viper-use-register
4210	(progn
4211	  (cond ((viper-valid-register viper-use-register '((Letter)))
4212		 (viper-append-to-register
4213		  (downcase viper-use-register) (point) end-del-pos))
4214		((viper-valid-register viper-use-register)
4215		 (copy-to-register
4216		  viper-use-register (point) end-del-pos nil))
4217		(t (error viper-InvalidRegister viper-use-register)))
4218	  (setq viper-use-register nil)))
4219
4220    (delete-char val t)
4221    (if viper-ex-style-motion
4222	(if (and (eolp) (not (bolp))) (backward-char 1)))
4223    ))
4224
4225(defun viper-delete-backward-char (arg)
4226  "Delete previous character.  On reaching beginning of line, stop and beep."
4227  (interactive "P")
4228  (let ((val (viper-p-val arg))
4229	end-del-pos)
4230    (viper-set-destructive-command
4231     (list 'viper-delete-backward-char val nil nil nil nil))
4232    (if (and
4233	 viper-ex-style-editing
4234	 (> val (viper-chars-in-region (viper-line-pos 'start) (point))))
4235	(setq val (viper-chars-in-region (viper-line-pos 'start) (point))))
4236    (save-excursion
4237      (viper-backward-char-carefully val)
4238      (setq end-del-pos (point)))
4239    (if viper-use-register
4240	(progn
4241	  (cond ((viper-valid-register viper-use-register '(Letter))
4242		 (viper-append-to-register
4243		  (downcase viper-use-register) end-del-pos (point)))
4244		((viper-valid-register viper-use-register)
4245		 (copy-to-register
4246		  viper-use-register end-del-pos (point) nil))
4247		(t (error viper-InvalidRegister viper-use-register)))
4248	  (setq viper-use-register nil)))
4249    (if (and (bolp) viper-ex-style-editing)
4250	(ding))
4251    (delete-backward-char val t)))
4252
4253
4254(defun viper-del-backward-char-in-insert ()
4255  "Delete 1 char backwards while in insert mode."
4256  (interactive)
4257  (if (and viper-ex-style-editing (bolp))
4258      (beep 1)
4259    ;; don't put on kill ring
4260    (delete-backward-char 1 nil)))
4261
4262
4263(defun viper-del-backward-char-in-replace ()
4264  "Delete one character in replace mode.
4265If `viper-delete-backwards-in-replace' is t, then DEL key actually deletes
4266charecters.  If it is nil, then the cursor just moves backwards, similarly
4267to Vi.  The variable `viper-ex-style-editing', if t, doesn't let the
4268cursor move past the beginning of line."
4269  (interactive)
4270  (cond (viper-delete-backwards-in-replace
4271	 (cond ((not (bolp))
4272		;; don't put on kill ring
4273		(delete-backward-char 1 nil))
4274	       (viper-ex-style-editing
4275		(beep 1))
4276	       ((bobp)
4277		(beep 1))
4278	       (t
4279		;; don't put on kill ring
4280		(delete-backward-char 1 nil))))
4281	(viper-ex-style-editing
4282	 (if (bolp)
4283	     (beep 1)
4284	   (backward-char 1)))
4285	(t
4286	 (backward-char 1))))
4287
4288
4289
4290;; join lines.
4291
4292(defun viper-join-lines (arg)
4293  "Join this line to next, if ARG is nil.  Otherwise, join ARG lines."
4294  (interactive "*P")
4295  (let ((val (viper-P-val arg)))
4296    (viper-set-destructive-command
4297     (list 'viper-join-lines val nil nil nil nil))
4298    (viper-loop (if (null val) 1 (1- val))
4299		(end-of-line)
4300		(if (not (eobp))
4301		    (progn
4302		      (forward-line 1)
4303		      (delete-region (point) (1- (point)))
4304		      (fixup-whitespace)
4305		      ;; fixup-whitespace sometimes does not leave space
4306		      ;; between objects, so we insert it as in Vi
4307		      (or (looking-at " ")
4308			  (insert " ")
4309			  (backward-char 1))
4310		      )))))
4311
4312
4313;; Replace state
4314
4315(defun viper-change (beg end)
4316  (if (markerp beg) (setq beg (marker-position beg)))
4317  (if (markerp end) (setq end (marker-position end)))
4318  ;; beg is sometimes (mark t), which may be nil
4319  (or beg (setq beg end))
4320
4321  (viper-set-complex-command-for-undo)
4322  (if viper-use-register
4323      (progn
4324	(copy-to-register viper-use-register beg end nil)
4325	(setq viper-use-register nil)))
4326  (viper-set-replace-overlay beg end)
4327  (setq last-command nil) ; separate repl text from prev kills
4328
4329  (if (= (viper-replace-start) (point-max))
4330      (error "End of buffer"))
4331
4332  (setq viper-last-replace-region
4333	(buffer-substring (viper-replace-start)
4334			  (viper-replace-end)))
4335
4336  ;; protect against error while inserting "@" and other disasters
4337  ;; (e.g., read-only buff)
4338  (condition-case conds
4339      (if (or viper-allow-multiline-replace-regions
4340	      (viper-same-line (viper-replace-start)
4341			       (viper-replace-end)))
4342	  (progn
4343	    ;; tabs cause problems in replace, so untabify
4344	    (goto-char (viper-replace-end))
4345	    (insert-before-markers "@") ; put placeholder after the TAB
4346	    (untabify (viper-replace-start) (point))
4347	    ;; del @, don't put on kill ring
4348	    (delete-backward-char 1)
4349
4350	    (viper-set-replace-overlay-glyphs
4351	     viper-replace-region-start-delimiter
4352	     viper-replace-region-end-delimiter)
4353	    ;; this move takes care of the last posn in the overlay, which
4354	    ;; has to be shifted because of insert.  We can't simply insert
4355	    ;; "$" before-markers because then overlay-start will shift the
4356	    ;; beginning of the overlay in case we are replacing a single
4357	    ;; character.  This fixes the bug with `s' and `cl' commands.
4358	    (viper-move-replace-overlay (viper-replace-start) (point))
4359	    (goto-char (viper-replace-start))
4360	    (viper-change-state-to-replace t))
4361	(kill-region (viper-replace-start)
4362		     (viper-replace-end))
4363	(viper-hide-replace-overlay)
4364	(viper-change-state-to-insert))
4365    (error ;; make sure that the overlay doesn't stay.
4366           ;; go back to the original point
4367     (goto-char (viper-replace-start))
4368     (viper-hide-replace-overlay)
4369     (viper-message-conditions conds))))
4370
4371
4372(defun viper-change-subr (beg end)
4373  ;; beg is sometimes (mark t), which may be nil
4374  (or beg (setq beg end))
4375  (if viper-use-register
4376      (progn
4377	(copy-to-register viper-use-register beg end nil)
4378	(setq viper-use-register nil)))
4379  (kill-region beg end)
4380  (setq this-command 'viper-change)
4381  (viper-yank-last-insertion))
4382
4383(defun viper-toggle-case (arg)
4384  "Toggle character case."
4385  (interactive "P")
4386  (let ((val (viper-p-val arg)) (c))
4387    (viper-set-destructive-command
4388     (list 'viper-toggle-case val nil nil nil nil))
4389    (while (> val 0)
4390      (setq c (following-char))
4391      (delete-char 1 nil)
4392      (if (eq c (upcase c))
4393	  (insert-char (downcase c) 1)
4394	(insert-char (upcase c) 1))
4395      (if (eolp) (backward-char 1))
4396      (setq val (1- val)))))
4397
4398
4399;; query replace
4400
4401(defun viper-query-replace ()
4402  "Query replace.
4403If a null string is suplied as the string to be replaced,
4404the query replace mode will toggle between string replace
4405and regexp replace."
4406  (interactive)
4407  (let (str)
4408    (setq str (viper-read-string-with-history
4409	       (if viper-re-query-replace "Query replace regexp: "
4410		 "Query replace: ")
4411	       nil  ; no initial
4412	       'viper-replace1-history
4413	       (car viper-replace1-history) ; default
4414	       ))
4415    (if (string= str "")
4416	(progn
4417	  (setq viper-re-query-replace (not viper-re-query-replace))
4418	  (message "Query replace mode changed to %s"
4419		   (if viper-re-query-replace "regexp replace"
4420		     "string replace")))
4421      (if viper-re-query-replace
4422	  (query-replace-regexp
4423	   str
4424	   (viper-read-string-with-history
4425	    (format "Query replace regexp `%s' with: " str)
4426	    nil  ; no initial
4427	    'viper-replace1-history
4428	    (car viper-replace1-history) ; default
4429	    ))
4430	(query-replace
4431	 str
4432	 (viper-read-string-with-history
4433	  (format "Query replace `%s' with: " str)
4434	  nil  ; no initial
4435	  'viper-replace1-history
4436	  (car viper-replace1-history) ; default
4437	  ))))))
4438
4439
4440;; marking
4441
4442(defun viper-mark-beginning-of-buffer ()
4443  "Mark beginning of buffer."
4444  (interactive)
4445  (push-mark (point))
4446  (goto-char (point-min))
4447  (exchange-point-and-mark)
4448  (message "Mark set at the beginning of buffer"))
4449
4450(defun viper-mark-end-of-buffer ()
4451  "Mark end of buffer."
4452  (interactive)
4453  (push-mark (point))
4454  (goto-char (point-max))
4455  (exchange-point-and-mark)
4456  (message "Mark set at the end of buffer"))
4457
4458(defun viper-mark-point ()
4459  "Set mark at point of buffer."
4460  (interactive)
4461  (let ((char (read-char)))
4462    (cond ((and (<= ?a char) (<= char ?z))
4463	   (point-to-register (viper-int-to-char (1+ (- char ?a)))))
4464	  ((viper= char ?<) (viper-mark-beginning-of-buffer))
4465	  ((viper= char ?>) (viper-mark-end-of-buffer))
4466	  ((viper= char ?.) (viper-set-mark-if-necessary))
4467	  ((viper= char ?,) (viper-cycle-through-mark-ring))
4468	  ((viper= char ?^) (push-mark viper-saved-mark t t))
4469	  ((viper= char ?D) (mark-defun))
4470	  (t (error ""))
4471	  )))
4472
4473;; Algorithm: If first invocation of this command save mark on ring, goto
4474;; mark, M0, and pop the most recent elt from the mark ring into mark,
4475;; making it into the new mark, M1.
4476;; Push this mark back and set mark to the original point position, p1.
4477;; So, if you hit '' or `` then you can return to p1.
4478;;
4479;; If repeated command, pop top elt from the ring into mark and
4480;; jump there.  This forgets the position, p1, and puts M1 back into mark.
4481;; Then we save the current pos, which is M0, jump to M1 and pop M2 from
4482;; the ring into mark.  Push M2 back on the ring and set mark to M0.
4483;; etc.
4484(defun viper-cycle-through-mark-ring ()
4485  "Visit previous locations on the mark ring.
4486One can use `` and '' to temporarily jump 1 step back."
4487  (let* ((sv-pt (point)))
4488       ;; if repeated `m,' command, pop the previously saved mark.
4489       ;; Prev saved mark is actually prev saved point.  It is used if the
4490       ;; user types `` or '' and is discarded
4491       ;; from the mark ring by the next `m,' command.
4492       ;; In any case, go to the previous or previously saved mark.
4493       ;; Then push the current mark (popped off the ring) and set current
4494       ;; point to be the mark.  Current pt as mark is discarded by the next
4495       ;; m, command.
4496       (if (eq last-command 'viper-cycle-through-mark-ring)
4497	   ()
4498	 ;; save current mark if the first iteration
4499	 (setq mark-ring (delete (viper-mark-marker) mark-ring))
4500	 (if (mark t)
4501	     (push-mark (mark t) t)) )
4502       (pop-mark)
4503       (set-mark-command 1)
4504       ;; don't duplicate mark on the ring
4505       (setq mark-ring (delete (viper-mark-marker) mark-ring))
4506       (push-mark sv-pt t)
4507       (viper-deactivate-mark)
4508       (setq this-command 'viper-cycle-through-mark-ring)
4509       ))
4510
4511
4512(defun viper-goto-mark (arg)
4513  "Go to mark."
4514  (interactive "P")
4515  (let ((char (read-char))
4516	(com (viper-getcom arg)))
4517    (viper-goto-mark-subr char com nil)))
4518
4519(defun viper-goto-mark-and-skip-white (arg)
4520  "Go to mark and skip to first non-white character on line."
4521  (interactive "P")
4522  (let ((char (read-char))
4523	(com (viper-getCom arg)))
4524    (viper-goto-mark-subr char com t)))
4525
4526(defun viper-goto-mark-subr (char com skip-white)
4527  (if (eobp)
4528      (if (bobp)
4529	  (error "Empty buffer")
4530	(backward-char 1)))
4531  (cond ((viper-valid-register char '(letter))
4532	 (let* ((buff (current-buffer))
4533	        (reg (viper-int-to-char (1+ (- char ?a))))
4534	        (text-marker (get-register reg)))
4535	   ;; If marker points to file that had markers set (and those markers
4536	   ;; were saved (as e.g., in session.el), then restore those markers
4537	   (if (and (consp text-marker)
4538 		    (eq (car text-marker) 'file-query)
4539 		    (or (find-buffer-visiting (nth 1 text-marker))
4540 			(y-or-n-p (format "Visit file %s again? "
4541 					  (nth 1 text-marker)))))
4542 	       (save-excursion
4543 		 (find-file (nth 1 text-marker))
4544 		 (when (and (<= (nth 2 text-marker) (point-max))
4545 			    (<= (point-min) (nth 2 text-marker)))
4546 		   (setq text-marker (copy-marker (nth 2 text-marker)))
4547 		   (set-register reg text-marker))))
4548	   (if com (viper-move-marker-locally 'viper-com-point (point)))
4549	   (if (not (viper-valid-marker text-marker))
4550	       (error viper-EmptyTextmarker char))
4551	   (if (and (viper-same-line (point) viper-last-jump)
4552		    (= (point) viper-last-jump-ignore))
4553	       (push-mark viper-last-jump t)
4554	     (push-mark nil t)) ; no msg
4555	   (viper-register-to-point reg)
4556	   (setq viper-last-jump (point-marker))
4557	   (cond (skip-white
4558		  (back-to-indentation)
4559		  (setq viper-last-jump-ignore (point))))
4560	   (if com
4561	       (if (equal buff (current-buffer))
4562		   (viper-execute-com (if skip-white
4563					  'viper-goto-mark-and-skip-white
4564					'viper-goto-mark)
4565				    nil com)
4566		 (switch-to-buffer buff)
4567		 (goto-char viper-com-point)
4568		 (viper-change-state-to-vi)
4569		 (error "")))))
4570	((and (not skip-white) (viper= char ?`))
4571	 (if com (viper-move-marker-locally 'viper-com-point (point)))
4572	 (if (and (viper-same-line (point) viper-last-jump)
4573		  (= (point) viper-last-jump-ignore))
4574	     (goto-char viper-last-jump))
4575	 (if (null (mark t)) (error "Mark is not set in this buffer"))
4576	 (if (= (point) (mark t)) (pop-mark))
4577	 (exchange-point-and-mark)
4578	 (setq viper-last-jump (point-marker)
4579	       viper-last-jump-ignore 0)
4580	 (if com (viper-execute-com 'viper-goto-mark nil com)))
4581	((and skip-white (viper= char ?'))
4582	 (if com (viper-move-marker-locally 'viper-com-point (point)))
4583	 (if (and (viper-same-line (point) viper-last-jump)
4584		  (= (point) viper-last-jump-ignore))
4585	     (goto-char viper-last-jump))
4586	 (if (= (point) (mark t)) (pop-mark))
4587	 (exchange-point-and-mark)
4588	 (setq viper-last-jump (point))
4589	 (back-to-indentation)
4590	 (setq viper-last-jump-ignore (point))
4591	 (if com (viper-execute-com 'viper-goto-mark-and-skip-white nil com)))
4592	(t (error viper-InvalidTextmarker char))))
4593
4594(defun viper-insert-tab ()
4595  (interactive)
4596  (insert-tab))
4597
4598(defun viper-exchange-point-and-mark ()
4599  (interactive)
4600  (exchange-point-and-mark)
4601  (back-to-indentation))
4602
4603;; Input Mode Indentation
4604
4605;; Returns t, if the string before point matches the regexp STR.
4606(defsubst viper-looking-back (str)
4607  (and (save-excursion (re-search-backward str nil t))
4608       (= (point) (match-end 0))))
4609
4610
4611(defun viper-forward-indent ()
4612  "Indent forward -- `C-t' in Vi."
4613  (interactive)
4614  (setq viper-cted t)
4615  (indent-to (+ (current-column) viper-shift-width)))
4616
4617(defun viper-backward-indent ()
4618  "Backtab, C-d in VI"
4619  (interactive)
4620  (if viper-cted
4621      (let ((p (point)) (c (current-column)) bol (indent t))
4622	(if (viper-looking-back "[0^]")
4623	    (progn
4624	      (if (eq ?^ (preceding-char))
4625		  (setq viper-preserve-indent t))
4626	      (delete-backward-char 1)
4627	      (setq p (point))
4628	      (setq indent nil)))
4629	(save-excursion
4630	  (beginning-of-line)
4631	  (setq bol (point)))
4632	(if (re-search-backward "[^ \t]" bol 1) (forward-char))
4633	(delete-region (point) p)
4634	(if indent
4635	    (indent-to (- c viper-shift-width)))
4636	(if (or (bolp) (viper-looking-back "[^ \t]"))
4637	    (setq viper-cted nil)))))
4638
4639;; do smart indent
4640(defun viper-indent-line (col)
4641  (if viper-auto-indent
4642      (progn
4643	(setq viper-cted t)
4644	(if (and viper-electric-mode
4645		 (not (memq major-mode '(fundamental-mode
4646					 text-mode
4647					 paragraph-indent-text-mode))))
4648	    (indent-according-to-mode)
4649	  (indent-to col)))))
4650
4651
4652(defun viper-autoindent ()
4653  "Auto Indentation, Vi-style."
4654  (interactive)
4655  (let ((col (current-indentation)))
4656    (if abbrev-mode (expand-abbrev))
4657    (if viper-preserve-indent
4658	(setq viper-preserve-indent nil)
4659      (setq viper-current-indent col))
4660    ;; don't leave whitespace lines around
4661    (if (memq last-command
4662	      '(viper-autoindent
4663		viper-open-line viper-Open-line
4664		viper-replace-state-exit-cmd))
4665	(indent-to-left-margin))
4666    ;; use \n instead of newline, or else <Return> will move the insert point
4667    ;;(newline 1)
4668    (insert "\n")
4669    (viper-indent-line viper-current-indent)
4670    ))
4671
4672
4673;; Viewing registers
4674
4675(defun viper-ket-function (arg)
4676  "Function called by \], the ket.  View registers and call \]\]."
4677  (interactive "P")
4678  (let ((reg (read-char)))
4679    (cond ((viper-valid-register reg '(letter Letter))
4680	   (view-register (downcase reg)))
4681	  ((viper-valid-register reg '(digit))
4682	   (let ((text (current-kill (- reg ?1) 'do-not-rotate)))
4683	     (with-output-to-temp-buffer " *viper-info*"
4684	       (princ (format "Register %c contains the string:\n" reg))
4685	       (princ text))
4686	     ))
4687	  ((viper= ?\] reg)
4688	   (viper-next-heading arg))
4689	  (t (error
4690	      viper-InvalidRegister reg)))))
4691
4692(defun viper-brac-function (arg)
4693  "Function called by \[, the brac.  View textmarkers and call \[\["
4694  (interactive "P")
4695  (let ((reg (read-char)))
4696    (cond ((viper= ?\[ reg)
4697	   (viper-prev-heading arg))
4698	  ((viper= ?\] reg)
4699	   (viper-heading-end arg))
4700	  ((viper-valid-register reg '(letter))
4701	   (let* ((val (get-register (viper-int-to-char (1+ (- reg ?a)))))
4702		  (buf (if (not (markerp val))
4703			   (error viper-EmptyTextmarker reg)
4704			 (marker-buffer val)))
4705		  (pos (marker-position val))
4706		  line-no text (s pos) (e pos))
4707	     (with-output-to-temp-buffer " *viper-info*"
4708	       (if (and buf pos)
4709		   (progn
4710		     (save-excursion
4711		       (set-buffer buf)
4712		       (setq line-no (1+ (count-lines (point-min) val)))
4713		       (goto-char pos)
4714		       (beginning-of-line)
4715		       (if (re-search-backward "[^ \t]" nil t)
4716			   (progn
4717			     (beginning-of-line)
4718			     (setq s (point))))
4719		       (goto-char pos)
4720		       (forward-line 1)
4721		       (if (re-search-forward "[^ \t]" nil t)
4722			   (progn
4723			     (end-of-line)
4724			     (setq e (point))))
4725		       (setq text (buffer-substring s e))
4726		       (setq text (format "%s<%c>%s"
4727					  (substring text 0 (- pos s))
4728					  reg (substring text (- pos s)))))
4729		     (princ
4730		      (format
4731		       "Textmarker `%c' is in buffer `%s' at line %d.\n"
4732				     reg (buffer-name buf) line-no))
4733		     (princ (format "Here is some text around %c:\n\n %s"
4734				     reg text)))
4735		 (princ (format viper-EmptyTextmarker reg))))
4736	     ))
4737	  (t (error viper-InvalidTextmarker reg)))))
4738
4739
4740
4741(defun viper-delete-backward-word (arg)
4742  "Delete previous word."
4743  (interactive "p")
4744  (save-excursion
4745    (push-mark nil t)
4746    (backward-word arg)
4747    (delete-region (point) (mark t))
4748    (pop-mark)))
4749
4750
4751
4752;; Get viper standard value of SYMBOL.  If symbol is customized, get its
4753;; standard value.  Otherwise, get the value saved in the alist STORAGE.  If
4754;; STORAGE is nil, use viper-saved-user-settings.
4755(defun viper-standard-value (symbol &optional storage)
4756  (or (eval (car (get symbol 'customized-value)))
4757      (eval (car (get symbol 'saved-value)))
4758      (nth 1 (assoc symbol (or storage viper-saved-user-settings)))))
4759
4760
4761
4762(defun viper-set-expert-level (&optional dont-change-unless)
4763  "Sets the expert level for a Viper user.
4764Can be called interactively to change (temporarily or permanently) the
4765current expert level.
4766
4767The optional argument DONT-CHANGE-UNLESS, if not nil, says that
4768the level should not be changed, unless its current value is
4769meaningless (i.e., not one of 1,2,3,4,5).
4770
4771User level determines the setting of Viper variables that are most
4772sensitive for VI-style look-and-feel."
4773
4774  (interactive)
4775
4776  (if (not (natnump viper-expert-level)) (setq viper-expert-level 0))
4777
4778  (save-window-excursion
4779    (delete-other-windows)
4780    ;; if 0 < viper-expert-level < viper-max-expert-level
4781    ;;    & dont-change-unless = t -- use it; else ask
4782    (viper-ask-level dont-change-unless))
4783
4784  (setq viper-always          	    		t
4785	viper-ex-style-motion 	    		t
4786	viper-ex-style-editing			t
4787	viper-want-ctl-h-help nil)
4788
4789  (cond ((eq viper-expert-level 1) ; novice or beginner
4790	 (global-set-key   ; in emacs-state
4791	  viper-toggle-key
4792	  (if (viper-window-display-p) 'viper-iconify 'suspend-emacs))
4793	 (setq viper-no-multiple-ESC	       t
4794	       viper-re-search	    	       t
4795	       viper-vi-style-in-minibuffer    t
4796	       viper-search-wrap-around-t      t
4797	       viper-electric-mode	       nil
4798	       viper-want-emacs-keys-in-vi     nil
4799	       viper-want-emacs-keys-in-insert nil))
4800
4801	((and (> viper-expert-level 1) (< viper-expert-level 5))
4802	 ;; intermediate to guru
4803	 (setq viper-no-multiple-ESC           (if (viper-window-display-p)
4804						   t 'twice)
4805	       viper-electric-mode	       t
4806	       viper-want-emacs-keys-in-vi     t
4807	       viper-want-emacs-keys-in-insert (> viper-expert-level 2))
4808
4809	 (if (eq viper-expert-level 4)  ; respect user's ex-style motion
4810					; and viper-no-multiple-ESC
4811	     (progn
4812	       (setq-default
4813		viper-ex-style-editing
4814		(viper-standard-value 'viper-ex-style-editing)
4815		viper-ex-style-motion
4816		(viper-standard-value 'viper-ex-style-motion))
4817	       (setq viper-ex-style-motion
4818		     (viper-standard-value 'viper-ex-style-motion)
4819		     viper-ex-style-editing
4820		     (viper-standard-value 'viper-ex-style-editing)
4821		     viper-re-search
4822		     (viper-standard-value 'viper-re-search)
4823		     viper-no-multiple-ESC
4824		     (viper-standard-value 'viper-no-multiple-ESC)))))
4825
4826	;; A wizard!!
4827	;; Ideally, if 5 is selected, a buffer should pop up to let the
4828	;; user toggle the values of variables.
4829	(t (setq-default viper-ex-style-editing
4830			 (viper-standard-value 'viper-ex-style-editing)
4831			 viper-ex-style-motion
4832			 (viper-standard-value 'viper-ex-style-motion))
4833	   (setq  viper-want-ctl-h-help
4834		  (viper-standard-value 'viper-want-ctl-h-help)
4835		  viper-always
4836		  (viper-standard-value 'viper-always)
4837		  viper-no-multiple-ESC
4838		  (viper-standard-value 'viper-no-multiple-ESC)
4839		  viper-ex-style-motion
4840		  (viper-standard-value 'viper-ex-style-motion)
4841		  viper-ex-style-editing
4842		  (viper-standard-value 'viper-ex-style-editing)
4843		  viper-re-search
4844		  (viper-standard-value 'viper-re-search)
4845		  viper-electric-mode
4846		  (viper-standard-value 'viper-electric-mode)
4847		  viper-want-emacs-keys-in-vi
4848		  (viper-standard-value 'viper-want-emacs-keys-in-vi)
4849		  viper-want-emacs-keys-in-insert
4850		  (viper-standard-value 'viper-want-emacs-keys-in-insert))))
4851
4852  (viper-set-mode-vars-for viper-current-state)
4853  (if (or viper-always
4854	  (and (> viper-expert-level 0) (> 5 viper-expert-level)))
4855      (viper-set-hooks)))
4856
4857
4858;; Ask user expert level.
4859(defun viper-ask-level (dont-change-unless)
4860  (let ((ask-buffer " *viper-ask-level*")
4861	level-changed repeated)
4862    (save-window-excursion
4863      (switch-to-buffer ask-buffer)
4864
4865      (while (or (> viper-expert-level viper-max-expert-level)
4866		 (< viper-expert-level 1)
4867		 (null dont-change-unless))
4868	(erase-buffer)
4869	(if repeated
4870	    (progn
4871	      (message "Invalid user level")
4872	      (beep 1))
4873	  (setq repeated t))
4874	(setq dont-change-unless t
4875	      level-changed t)
4876	(insert "
4877Please specify your level of familiarity with the venomous VI PERil
4878\(and the VI Plan for Emacs Rescue).
4879You can change it at any time by typing `M-x viper-set-expert-level RET'
4880
4881 1 -- BEGINNER: Almost all Emacs features are suppressed.
4882       Feels almost like straight Vi.  File name completion and
4883       command history in the minibuffer are thrown in as a bonus.
4884       To use Emacs productively, you must reach level 3 or higher.
4885 2 -- MASTER: C-c now has its standard Emacs meaning in Vi command state,
4886       so most Emacs commands can be used when Viper is in Vi state.
4887       Good progress---you are well on the way to level 3!
4888 3 -- GRAND MASTER: Like 2, but most Emacs commands are available also
4889       in Viper's insert state.
4890 4 -- GURU: Like 3, but user settings are respected for viper-no-multiple-ESC,
4891       viper-ex-style-motion, viper-ex-style-editing, and
4892       viper-re-search variables.  Adjust these settings to your taste.
4893 5 -- WIZARD: Like 4, but user settings are also respected for viper-always,
4894       viper-electric-mode, viper-want-ctl-h-help, viper-want-emacs-keys-in-vi,
4895       and viper-want-emacs-keys-in-insert.  Adjust these to your taste.
4896
4897Please, specify your level now: ")
4898
4899	(setq viper-expert-level (- (viper-read-char-exclusive) ?0))
4900	) ; end while
4901
4902      ;; tell the user if level was changed
4903      (and level-changed
4904	   (progn
4905	     (insert
4906	      (format "\n\n\n\n\n\t\tYou have selected user level %d"
4907		      viper-expert-level))
4908	     (if (y-or-n-p "Do you wish to make this change permanent? ")
4909		 ;; save the setting for viper-expert-level
4910		 (viper-save-setting
4911		  'viper-expert-level
4912		  (format "Saving user level %d ..." viper-expert-level)
4913		  viper-custom-file-name))
4914	     ))
4915      (bury-buffer) ; remove ask-buffer from screen
4916      (message "")
4917      )))
4918
4919
4920(defun viper-nil ()
4921  (interactive)
4922  (beep 1))
4923
4924
4925;; if ENFORCE-BUFFER is not nil, error if CHAR is a marker in another buffer
4926(defun viper-register-to-point (char &optional enforce-buffer)
4927  "Like jump-to-register, but switches to another buffer in another window."
4928  (interactive "cViper register to point: ")
4929  (let ((val (get-register char)))
4930    (cond
4931     ((and (fboundp 'frame-configuration-p)
4932	   (frame-configuration-p val))
4933      (set-frame-configuration val))
4934     ((window-configuration-p val)
4935      (set-window-configuration val))
4936     ((viper-valid-marker val)
4937      (if (and enforce-buffer
4938	       (not (equal (current-buffer) (marker-buffer val))))
4939	  (error (concat viper-EmptyTextmarker " in this buffer")
4940		 (viper-int-to-char (1- (+ char ?a)))))
4941      (pop-to-buffer  (marker-buffer val))
4942      (goto-char val))
4943     ((and (consp val) (eq (car val) 'file))
4944      (find-file (cdr val)))
4945     (t
4946      (error viper-EmptyTextmarker (viper-int-to-char (1- (+ char ?a))))))))
4947
4948
4949(defun viper-save-kill-buffer ()
4950  "Save then kill current buffer."
4951  (interactive)
4952  (if (< viper-expert-level 2)
4953      (save-buffers-kill-emacs)
4954    (save-buffer)
4955    (kill-buffer (current-buffer))))
4956
4957
4958
4959;;; Bug Report
4960
4961(defun viper-submit-report ()
4962  "Submit bug report on Viper."
4963  (interactive)
4964  (let ((reporter-prompt-for-summary-p t)
4965	(viper-device-type (viper-device-type))
4966	color-display-p frame-parameters
4967	minibuffer-emacs-face minibuffer-vi-face minibuffer-insert-face
4968	varlist salutation window-config)
4969
4970    ;; If mode info is needed, add variable to `let' and then set it below,
4971    ;; like we did with color-display-p.
4972    (setq color-display-p (if (viper-window-display-p)
4973			      (viper-color-display-p)
4974			    'non-x)
4975	  minibuffer-vi-face (if (viper-has-face-support-p)
4976				 (viper-get-face viper-minibuffer-vi-face)
4977			       'non-x)
4978	  minibuffer-insert-face (if (viper-has-face-support-p)
4979				     (viper-get-face
4980				      viper-minibuffer-insert-face)
4981				   'non-x)
4982	  minibuffer-emacs-face (if (viper-has-face-support-p)
4983				    (viper-get-face
4984				     viper-minibuffer-emacs-face)
4985				  'non-x)
4986	  frame-parameters (if (fboundp 'frame-parameters)
4987			       (frame-parameters (selected-frame))))
4988
4989    (setq varlist (list 'viper-vi-minibuffer-minor-mode
4990		        'viper-insert-minibuffer-minor-mode
4991		        'viper-vi-intercept-minor-mode
4992		        'viper-vi-local-user-minor-mode
4993		        'viper-vi-kbd-minor-mode
4994		        'viper-vi-global-user-minor-mode
4995		        'viper-vi-state-modifier-minor-mode
4996		        'viper-vi-diehard-minor-mode
4997		        'viper-vi-basic-minor-mode
4998		        'viper-replace-minor-mode
4999		        'viper-insert-intercept-minor-mode
5000		        'viper-insert-local-user-minor-mode
5001		        'viper-insert-kbd-minor-mode
5002		        'viper-insert-global-user-minor-mode
5003		        'viper-insert-state-modifier-minor-mode
5004		        'viper-insert-diehard-minor-mode
5005		        'viper-insert-basic-minor-mode
5006		        'viper-emacs-intercept-minor-mode
5007		        'viper-emacs-local-user-minor-mode
5008		        'viper-emacs-kbd-minor-mode
5009		        'viper-emacs-global-user-minor-mode
5010		        'viper-emacs-state-modifier-minor-mode
5011		        'viper-automatic-iso-accents
5012			'viper-special-input-method
5013		        'viper-want-emacs-keys-in-insert
5014		        'viper-want-emacs-keys-in-vi
5015		        'viper-keep-point-on-undo
5016		        'viper-no-multiple-ESC
5017		        'viper-electric-mode
5018		        'viper-ESC-key
5019		        'viper-want-ctl-h-help
5020		        'viper-ex-style-editing
5021		        'viper-delete-backwards-in-replace
5022		        'viper-vi-style-in-minibuffer
5023		        'viper-vi-state-hook
5024		        'viper-insert-state-hook
5025		        'viper-replace-state-hook
5026		        'viper-emacs-state-hook
5027		        'ex-cycle-other-window
5028		        'ex-cycle-through-non-files
5029		        'viper-expert-level
5030		        'major-mode
5031		        'viper-device-type
5032			'color-display-p
5033			'frame-parameters
5034			'minibuffer-vi-face
5035			'minibuffer-insert-face
5036			'minibuffer-emacs-face
5037			))
5038	  (setq salutation "
5039Congratulations! You may have unearthed a bug in Viper!
5040Please mail a concise, accurate summary of the problem to the address above.
5041
5042-------------------------------------------------------------------")
5043	  (setq window-config (current-window-configuration))
5044	  (with-output-to-temp-buffer " *viper-info*"
5045	    (switch-to-buffer " *viper-info*")
5046	    (delete-other-windows)
5047	    (princ "
5048PLEASE FOLLOW THESE PROCEDURES
5049------------------------------
5050
5051Before reporting a bug, please verify that it is related to Viper, and is
5052not cause by other packages you are using.
5053
5054Don't report compilation warnings, unless you are certain that there is a
5055problem.  These warnings are normal and unavoidable.
5056
5057Please note that users should not modify variables and keymaps other than
5058those advertised in the manual.  Such `customization' is likely to crash
5059Viper, as it would any other improperly customized Emacs package.
5060
5061If you are reporting an error message received while executing one of the
5062Viper commands, type:
5063
5064    M-x set-variable <Return> debug-on-error <Return> t <Return>
5065
5066Then reproduce the error.  The above command will cause Emacs to produce a
5067back trace of the execution that leads to the error.  Please include this
5068trace in your bug report.
5069
5070If you believe that one of Viper's commands goes into an infinite loop
5071\(e.g., Emacs freezes\), type:
5072
5073    M-x set-variable <Return> debug-on-quit <Return> t <Return>
5074
5075Then reproduce the problem.  Wait for a few seconds, then type C-g to abort
5076the current command.  Include the resulting back trace in the bug report.
5077
5078Mail anyway (y or n)? ")
5079	    (if (y-or-n-p "Mail anyway? ")
5080		()
5081	      (set-window-configuration window-config)
5082	      (error "Bug report aborted")))
5083
5084	  (require 'reporter)
5085	  (set-window-configuration window-config)
5086
5087	  (reporter-submit-bug-report "kifer@cs.stonybrook.edu"
5088				      (viper-version)
5089				      varlist
5090				      nil 'delete-other-windows
5091				      salutation)
5092	  ))
5093
5094
5095
5096
5097;; arch-tag: 739a6450-5fda-44d0-88b0-325053d888c2
5098;;; viper-cmd.el ends here
5099