Auto-insert of colons in Emacs

John Wiegley jwiegley at inprise.com
Wed May 17 13:58:46 EDT 2000


Why hobble your mind with a detail the computer can figure out for
itself?

It's very strictly defined where a colon should go in Python, so it
makes little sense that humans should be bothered with this detail.
If it makes the code more readable for those who didn't write it, I
can understand; but the author has better things to think about.

Accordingly, the following snippet of Emacs code will ensure there is
always a colon where it should be.  You should never have to type them
again, except when you want the whole statement to fit on one line.

To use it, just put everything after the "----" in your .emacs file.

Enjoy.  This was written for users of python-mode.el
(http://www.python.org/emacs/python-mode/)

----------------------------------------------------------------------

(eval-after-load "python-mode"
  '(progn
     (defvar python-keywords-wanting-colon
       '("def" "class" "if" "while" "else"
         "try" "except" "finally" "for" "lambda"))
     
     (defvar python-kwc-regexp nil)

     (require 'advice)
     (defadvice py-newline-and-indent (before always-insert-colons activate)
       "Always make sure that colons appear in the appropriate place."
       (unless (eq (char-before) ?:)
         (let ((here (point))
               insert-colon already-has-it)
           (save-excursion
             (beginning-of-line)
             (save-excursion
               (if (search-forward ":" here t)
                   (setq already-has-it t)))
             (unless already-has-it
               (unless python-kwc-regexp
                 (require 'regexp-opt)
                 (setq python-kwc-regexp
                       (concat "\\s-*\\<"
                               (regexp-opt python-keywords-wanting-colon t)
                               "\\>")))
               (if (looking-at python-kwc-regexp)
                   (setq insert-colon t))))
           (if insert-colon
               (let ((last-command-char ?:))
                 (py-electric-colon nil))))))))



More information about the Python-list mailing list