Insert magic encoding comment upon save
This commit is contained in:
parent
41e153058c
commit
17cf2c710a
1 changed files with 41 additions and 1 deletions
|
@ -35,6 +35,45 @@
|
||||||
|
|
||||||
(require 'prelude-programming)
|
(require 'prelude-programming)
|
||||||
|
|
||||||
|
;; Copy pasted from ruby-mode.el
|
||||||
|
(defun prelude-python--encoding-comment-required-p ()
|
||||||
|
(re-search-forward "[^\0-\177]" nil t))
|
||||||
|
|
||||||
|
(defun prelude-python--detect-encoding ()
|
||||||
|
(let ((coding-system
|
||||||
|
(or save-buffer-coding-system
|
||||||
|
buffer-file-coding-system)))
|
||||||
|
(if coding-system
|
||||||
|
(symbol-name
|
||||||
|
(or (coding-system-get coding-system 'mime-charset)
|
||||||
|
(coding-system-change-eol-conversion coding-system nil)))
|
||||||
|
"ascii-8bit")))
|
||||||
|
|
||||||
|
(defun prelude-python--insert-coding-comment (encoding)
|
||||||
|
(let ((newlines (if (looking-at "^\\s *$") "\n" "\n\n")))
|
||||||
|
(insert (format "# coding: %s" encoding) newlines)))
|
||||||
|
|
||||||
|
(defun prelude-python-mode-set-encoding ()
|
||||||
|
"Insert a magic comment header with the proper encoding if necessary."
|
||||||
|
(save-excursion
|
||||||
|
(widen)
|
||||||
|
(goto-char (point-min))
|
||||||
|
(when (prelude-python--encoding-comment-required-p)
|
||||||
|
(goto-char (point-min))
|
||||||
|
(let ((coding-system (prelude-python--detect-encoding)))
|
||||||
|
(when coding-system
|
||||||
|
(if (looking-at "^#!") (beginning-of-line 2))
|
||||||
|
(cond ((looking-at "\\s *#\\s *.*\\(en\\)?coding\\s *:\\s *\\([-a-z0-9_]*\\)")
|
||||||
|
;; update existing encoding comment if necessary
|
||||||
|
(unless (string= (match-string 2) coding-system)
|
||||||
|
(goto-char (match-beginning 2))
|
||||||
|
(delete-region (point) (match-end 2))
|
||||||
|
(insert coding-system)))
|
||||||
|
((looking-at "\\s *#.*coding\\s *[:=]"))
|
||||||
|
(t (prelude-python--insert-coding-comment coding-system)))
|
||||||
|
(when (buffer-modified-p)
|
||||||
|
(basic-save-buffer-1)))))))
|
||||||
|
|
||||||
(defun prelude-python-mode-defaults ()
|
(defun prelude-python-mode-defaults ()
|
||||||
"Defaults for Python programming."
|
"Defaults for Python programming."
|
||||||
(subword-mode +1)
|
(subword-mode +1)
|
||||||
|
@ -42,7 +81,8 @@
|
||||||
'((?: . (lambda ()
|
'((?: . (lambda ()
|
||||||
(if (python-info-statement-starts-block-p)
|
(if (python-info-statement-starts-block-p)
|
||||||
'after)))))
|
'after)))))
|
||||||
(electric-layout-mode +1))
|
(electric-layout-mode +1)
|
||||||
|
(add-hook 'after-save-hook 'prelude-python-mode-set-encoding nil 'local))
|
||||||
|
|
||||||
(setq prelude-python-mode-hook 'prelude-python-mode-defaults)
|
(setq prelude-python-mode-hook 'prelude-python-mode-defaults)
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue