home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / viper / viper.el < prev    next >
Encoding:
Text File  |  1995-08-11  |  187.2 KB  |  5,545 lines

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