[net.emacs] write-file-hook

rusty@sdcarl.UUCP (rusty c. wright) (07/26/85)

after all of my hysterics about gnu emacs' c-mode i decided to write
my own version of what i call autoindent-mode which mimics the
autoindent mode of vi.  it seems to all work except for one problem:
because of the way autoindent-mode works it is likely that there will
be lines that have only tabs or spaces on them.  so i wrote a little
routine that gets called when the file is written out and it cleans
off all white space at the end of lines.  unfortunately when i do the
setq of write-file-hook it makes it global and this cleanup routine
gets called for all buffers regardless of their mode when i do a
save-buffer (ctl-s); i only want it to apply to buffers that
autoindent-mode is invoked in.  if i insert a make-local-variable
before the setq then my cleanup routine doesn't even get called.  what
am i doing wrong?

here is my autoindent-mode.el file:

(defvar ai-mode-hook nil
  "If non-nil, its value is called on entry to autoindent-mode.")

(defvar ai-mode-map nil
  "Keymap used in autoindent mode.")

(defun autoindent-mode ()
  "Autoindent mode mimics the autoindent mode of the vi editor.
Specifically, a newline and open-line start the new line at the
proper place to cause the new to line up with the previous line's
indentation, if any."
    (kill-all-local-variables)
    (if (not ai-mode-map)
	(progn
	  (setq ai-mode-map (make-sparse-keymap))
	  (define-key ai-mode-map "\^m" 'ai-newline)
	  (define-key ai-mode-map "\^o" 'ai-open-line)))
    (use-local-map ai-mode-map)
    (setq mode-name "Autoindent")
    (set major-mode 'autoindent-mode)
    (setq write-file-hook 'ai-cleanup)
    (and (boundp 'ai-mode-hook)
	 ai-mode-hook
	 (funcall ai-mode-hook))
)

(defun ai-newline ()
  "When starting a new line start it with the same level of indentation
as the preceeding line."
  (interactive)
  (let ((previous-indentation (current-indentation)))
    (insert "\n")
    (indent-to previous-indentation)))

(defun ai-open-line ()
  "When opening up a new line, start it with the same level of indentation
as the preceeding line."
  (interactive)
  (let ((previous-indentation (current-indentation)))
    (open-line 1)
    (indent-to previous-indentation)))

(defun ai-cleanup ()
  "Because of the klunky way that autoindent mode works it is necessary
to clean up lines that may have unnecessary white space at the end; most
notably empty lines that consist entirely of nothing but white space."
  (progn
    (message "starting cleanup...")
    (push-mark)
    (beginning-of-buffer)
    (while (not (eobp))
      (end-of-line)
      (delete-horizontal-space)
      (if (not (equal (dot) (dot-max)))
	  (forward-char)))
    (pop-mark)
    (exchange-dot-and-mark)))
-- 
	rusty c. wright
	{ucbvax,ihnp4,akgua,hplabs,sdcsvax}!sdcarl!rusty