11458f582803c106382e0bde8be2453785e35b41
[emacs-init.git] / python / init_python.el
1 ;(autoload 'python-mode "python-mode" "Python Mode." t)
2 ;(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
3 ;(add-to-list 'interpreter-mode-alist '("python" . python-mode))
4 ;(require 'python-mode)
5 ;(provide 'python)
6 ;(provide 'python21)
7 (require 'python)
8
9 ;; pymacs
10 (autoload 'pymacs-apply "pymacs")
11 (autoload 'pymacs-call "pymacs")
12 (autoload 'pymacs-eval "pymacs" nil t)
13 (autoload 'pymacs-exec "pymacs" nil t)
14 (autoload 'pymacs-load "pymacs" nil t)
15 ;;(eval-after-load "pymacs"
16 ;;  '(add-to-list 'pymacs-load-path YOUR-PYMACS-DIRECTORY"))
17 (pymacs-load "ropemacs" "rope-")
18 (setq ropemacs-enable-autoimport t)
19
20 ;; M-/               rope-code-assist
21 ;; C-c g             rope-goto-definition
22 ;; C-c d             rope-show-doc
23 ;; C-c f             rope-find-occurrences
24 ;; M-?               rope-lucky-assist
25
26 (define-key ropemacs-local-keymap "\M-/" 'hippie-expand)
27
28 (defun write-file-py-cleanup-imports ()
29   (save-excursion
30     (condition-case nil
31         (py-cleanup-imports t)
32       (error . nil)))
33   nil)
34
35 (defun python-init-auto-cleanup-imports-on-save ()
36   (add-hook 'write-file-functions 'write-file-py-cleanup-imports nil t))
37
38 (defun my-flymake-error-at-point ()
39   (condition-case nil
40       (flymake-ler-text (car (nth 0 (flymake-find-err-info flymake-err-info
41                                                            (flymake-current-line-no)))))
42     (error (error "no flymake error at point"))))
43
44 (defun my-flymake-show-error ()
45   (interactive)
46   (message (my-flymake-error-at-point)))
47
48 (defun my-pyflymake-add-import-from-error ()
49   (interactive)
50   (let ((err (my-flymake-error-at-point)))
51     (if (string-match "undefined name '\\(.*\\)'" err)
52         (py-add-import (match-string 1 err))
53       (error "no missing symbol at point"))))
54
55 (defun py-add-import (import)
56   (interactive "sModule to import: ")
57   (save-window-excursion
58     (save-excursion
59       (goto-char (car (py-imports-region)))
60       (insert "import " import "\n")
61       (py-cleanup-imports t)
62       (sit-for 2))))
63
64 (defun my-flymake-check-and-wait ()
65   (if (boundp flymake-is-running)
66       (progn
67         (while flymake-is-running (sit-for .1))
68         (flymake-start-syntax-check)
69         (while flymake-is-running (sit-for .1)))))
70
71 (defun my-flymake-goto-next-error ()
72   (interactive)
73   (my-flymake-check-and-wait)
74   (flymake-goto-next-error)
75   (my-flymake-show-error))
76
77 (defun my-flymake-goto-prev-error ()
78   (interactive)
79   (my-flymake-check-and-wait)
80   (flymake-goto-prev-error)
81   (my-flymake-show-error))
82
83 (defun py-find-file (errormark filename defaultdir)
84   (let ((fullname (expand-file-name filename defaultdir)))
85     (or (and (not (file-exists-p fullname))
86              (let* ((name (loop for name = fullname then (directory-file-name
87                                                           (file-name-directory name))
88                                 if (file-exists-p name) return name))
89                     (fmt (and name (with-temp-buffer
90                                      (insert-file-contents name nil 0 1024 t) (archive-find-type))))
91                     (tail (and fmt (substring fullname (1+ (length name))))))
92                (if fmt
93                    (with-current-buffer (find-file-noselect name)
94                      (goto-char (point-min))
95                      (re-search-forward (concat " " (regexp-quote tail) "$"))
96                      (save-window-excursion
97                        (archive-extract)
98                        (current-buffer))))))
99         (compilation-find-file errormark filename defaultdir))))
100
101 (require 'arc-mode)
102
103 (defun py-eshell-goto-error (&optional back)
104   (interactive "P")
105   (display-buffer "*eshell*" t)
106   (let (here end start dir file line errmk example)
107     (with-current-buffer "*eshell*"
108       (save-excursion
109         ;; Find and validate last traceback
110         (goto-char (point-max))
111         (re-search-backward "^\\(.*\\)Traceback \\|^Failed example:")
112         (beginning-of-line)
113         (if (looking-at "Failed example:")
114             (progn
115               (forward-line -2)
116               (setq example t)))
117         (if (or (not (and (boundp 'py-eshell-last-error)
118                           (boundp 'py-eshell-last-point)))
119                 (null py-eshell-last-error)
120                 (null py-eshell-last-point)
121                 (null py-eshell-last-dir)
122                 (not (= py-eshell-last-error (point))))
123             (progn
124               (set (make-local-variable 'py-eshell-last-error) (point))
125               (set (make-local-variable 'py-eshell-prefix) (or (match-string 1) ""))
126               (if (string-match "Original $" py-eshell-prefix)
127                   (setq py-eshell-prefix (substring py-eshell-prefix 0 (match-beginning 0))))
128               (if example
129                   (forward-line 2)
130                 (while (and (< (forward-line 1) 1) (looking-at (concat py-eshell-prefix "  ")))))
131               (set (make-local-variable 'py-eshell-last-point) (point))
132               (set (make-local-variable 'py-eshell-last-dir) default-directory)
133               (while
134                   (and (< (forward-line 1) 1)
135                        (not (if (looking-at ".*Leaving directory ")
136                                 (progn
137                                   (goto-char (match-end 0))
138                                   (skip-chars-forward "'\"`")
139                                   (let ((dir (current-word)))
140                                     (and dir (setq py-eshell-last-dir
141                                                    (file-name-as-directory dir)))))))))))
142         (goto-char py-eshell-last-point)
143
144         ;; Nove to next / prev frame in traceback
145         (if back
146             (progn
147               (while (and (looking-at (concat py-eshell-prefix "  "))
148                           (< (forward-line 1) 1)
149                           (not (looking-at (concat py-eshell-prefix "  File ")))))
150               (setq start (point))
151               (while (and (looking-at (concat py-eshell-prefix "  "))
152                           (< (forward-line 1) 1)
153                           (not (looking-at (concat py-eshell-prefix "  File ")))))
154               (setq end (point)))
155           (while (and (> (forward-line -1) -1)
156                       (not (looking-at (concat py-eshell-prefix (if example "File " "  File "))))
157                       (> (point) py-eshell-last-error)))
158           (setq end py-eshell-last-point start (point)))
159
160         ;; Parse information and set overlay
161         (if (save-excursion (goto-char start) (setq errmk (point-marker))
162                             (looking-at (concat py-eshell-prefix (if example "File " "  File "))))
163             (let ((default-directory py-eshell-last-dir))
164               (set (make-local-variable 'py-eshell-last-point) start)
165               (if (and (boundp 'py-eshell-overlay) py-eshell-overlay)
166                   (move-overlay py-eshell-overlay start end)
167                 (set (make-local-variable 'py-eshell-overlay) (make-overlay start end))
168                 (overlay-put py-eshell-overlay 'face 'highlight))
169               (save-excursion
170                 (goto-char start)
171                 (forward-char (+ (length py-eshell-prefix) 7))
172                 (skip-chars-forward "\"")
173                 (setq file (current-word))
174                 (search-forward " line ")
175                 (skip-chars-forward " ")
176                 (setq line (string-to-number
177                             (buffer-substring-no-properties
178                              (point) (progn (skip-chars-forward "0-9") (point)))))
179                 (setq dir default-directory))
180               (if (null file)
181                   (error "File not found")))
182           (py-eshell-error-reset)
183           (error "No further traceback line"))))
184
185     ;; move to error locus
186     (if (and file line errmk)
187         (with-current-buffer (py-find-file errmk file dir)
188           (compilation-goto-locus errmk (save-excursion (goto-line line) (point-marker)) nil)))))
189
190 (defun py-eshell-error-reset ()
191   (interactive)
192   (save-excursion
193     (set-buffer "*eshell*")
194     (if (and (boundp 'py-eshell-overlay) py-eshell-overlay)
195         (delete-overlay py-eshell-overlay))
196     (set (make-local-variable 'py-eshell-last-error) nil)
197     (set (make-local-variable 'py-eshell-last-point) nil)
198     (set (make-local-variable 'py-eshell-last-dir) nil)
199     (set (make-local-variable 'py-eshell-prefix) nil)
200     (set (make-local-variable 'py-eshell-overlay) nil)))
201
202 (global-set-key "\C-xP" 'py-eshell-goto-error)
203 (global-set-key "\C-x\C-p" 'python-shell)
204
205 (add-hook 'python-mode-hook 'python-init-auto-cleanup-imports-on-save)
206
207 (defun py-setup-hook ()
208   ;(set-variable 'py-indent-offset 4)
209   ;(set-variable 'py-smart-indentation nil)
210   (set-variable 'indent-tabs-mode nil)
211   ;(define-key py-mode-map (kbd "RET") 'newline-and-indent)
212   ;(define-key py-mode-map [tab] 'yas/expand)
213   ;(setq yas/after-exit-snippet-hook 'indent-according-to-mode)
214   ;(smart-operator-mode-on)
215   (define-key python-mode-map "\C-ci" 'my-pyflymake-add-import-from-error)
216   (define-key python-mode-map "\C-ce" 'my-flymake-show-error)
217   (define-key python-mode-map "\C-cn" 'my-flymake-goto-next-error)
218   (define-key python-mode-map "\C-cp" 'my-flymake-goto-prev-error)
219   (define-key python-mode-map "\C-cI" 'py-cleanup-imports)
220 )
221
222 (add-hook 'python-mode-hook 'py-setup-hook)
223
224 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
225 ;;; Auto-completion
226 ;;;  Integrates:
227 ;;;   1) Rope
228 ;;;   2) Yasnippet
229 ;;;   all with AutoComplete.el
230 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
231 (defun prefix-list-elements (list prefix)
232   (let (value)
233     (nreverse
234      (dolist (element list value)
235       (setq value (cons (format "%s%s" prefix element) value))))))
236 (defvar ac-source-rope
237   '((candidates
238      . (lambda ()
239          (prefix-list-elements (rope-completions) ac-target))))
240   "Source for Rope")
241 (defun ac-python-find ()
242   "Python `ac-find-function'."
243   (require 'thingatpt)
244   (let ((symbol (car-safe (bounds-of-thing-at-point 'symbol))))
245     (if (null symbol)
246         (if (string= "." (buffer-substring (- (point) 1) (point)))
247             (point)
248           nil)
249       symbol)))
250 (defun ac-python-candidate ()
251   "Python `ac-candidates-function'"
252   (let (candidates)
253     (dolist (source ac-sources)
254       (if (symbolp source)
255           (setq source (symbol-value source)))
256       (let* ((ac-limit (or (cdr-safe (assq 'limit source)) ac-limit))
257              (requires (cdr-safe (assq 'requires source)))
258              cand)
259         (if (or (null requires)
260                 (>= (length ac-target) requires))
261             (setq cand
262                   (delq nil
263                         (mapcar (lambda (candidate)
264                                   (propertize candidate 'source source))
265                                 (funcall (cdr (assq 'candidates source)))))))
266         (if (and (> ac-limit 1)
267                  (> (length cand) ac-limit))
268             (setcdr (nthcdr (1- ac-limit) cand) nil))
269         (setq candidates (append candidates cand))))
270     (delete-dups candidates)))
271 (add-hook 'python-mode-hook
272           (lambda ()
273                  (auto-complete-mode 1)
274                  (set (make-local-variable 'ac-sources)
275                       (append ac-sources '(ac-source-rope) '(ac-source-yasnippet)))
276                  (set (make-local-variable 'ac-find-function) 'ac-python-find)
277                  (set (make-local-variable 'ac-candidate-function) 'ac-python-candidate)
278                  (set (make-local-variable 'ac-auto-start) nil)))
279 ;;Ryan's python specific tab completion
280 (defun ryan-python-tab ()
281   ; Try the following:
282   ; 1) Do a yasnippet expansion
283   ; 2) Do a Rope code completion
284   ; 3) Do an indent
285   (interactive)
286   (if (eql (ac-start) 0)
287       (indent-for-tab-command)))
288 (defadvice ac-start (before advice-turn-on-auto-start activate)
289   (set (make-local-variable 'ac-auto-start) t))
290 (defadvice ac-cleanup (after advice-turn-off-auto-start activate)
291   (set (make-local-variable 'ac-auto-start) nil))
292 ;(define-key py-mode-map "\t" 'ryan-python-tab)
293 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
294 ;;; End Auto Completion
295 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
296 ;; Auto Syntax Error Hightlight
297 (when (load "flymake" t)
298   (defun flymake-pyflakes-init ()
299     (let* ((temp-file (flymake-init-create-temp-buffer-copy
300                        'flymake-create-temp-inplace))
301            (local-file (file-relative-name
302                         temp-file
303                         (file-name-directory buffer-file-name))))
304       (message "flymake init pyflakes %s" local-file)
305       (list "pyflakes" (list local-file))))
306   (add-to-list 'flymake-allowed-file-name-masks
307                '("\\.py\\'" flymake-pyflakes-init)))
308 (add-hook 'find-file-hook 'flymake-find-file-hook)
309
310 (defun py-imports-region ()
311   (save-excursion
312     (goto-char (point-min))
313     (while (and (re-search-forward "^\\(import\\s-+\\|from\\s-+\\)" nil t)
314                 (looking-at "__future__")))
315     (beginning-of-line)
316     (setq beg (point))
317     (if (not (looking-at "\\(import\\s-+\\|from\\s-+\\)"))
318         (cons beg beg)
319       (while (looking-at "\\(import\\s-+\\|from\\s-+\\)")
320         (forward-line 1))
321       (cons beg (point)))))
322
323 (defun py-cleanup-imports (&optional nowait)
324   (interactive)
325   (let (beg end)
326     (if (region-active-p)
327         (setq beg (region-beginning)
328               end (region-end))
329       (setq reg (py-imports-region))
330       (if (= (car reg) (cdr reg))
331           (error "No imports found"))
332       (setq beg (car reg) end (cdr reg)))
333     (sort-lines t beg end)
334     (goto-char beg)
335     (let ((end-marker (make-marker))
336           (doing-imports t)
337           (b beg))
338       (set-marker end-marker end)
339       (while (< (point) end-marker)
340         (let ((is-import (looking-at "import\\s-+"))
341               (eol-marker (save-excursion (end-of-line) (point-marker)))
342               prefix)
343           (if (and doing-imports (not is-import))
344               (progn
345                 (if (> (point) b)
346                     (progn
347                       (sort-lines nil beg (point))
348                       (setq b (point))))
349                 (setq doing-imports nil)))
350           (setq prefix (if is-import "import "
351                          (buffer-substring-no-properties
352                           (point) (re-search-forward "\\s-+import\\s-+" eol-marker t))))
353           (while (search-forward "," eol-marker t)
354             (delete-char -1)
355             (delete-horizontal-space)
356             (insert "\n" prefix))
357           (forward-line 1)))
358       (sort-lines nil b (point))
359       (if (and (not nowait) (boundp flymake-is-running))
360           (progn
361             (my-flymake-check-and-wait)
362             (goto-char beg)
363             (while (< (point) end-marker)
364               (if (and (loop for ov in (overlays-at (point))
365                              thereis (flymake-overlay-p ov))
366                        (not (save-excursion (search-forward "unused"
367                                                             (save-excursion (end-of-line) (point))
368                                                             t ))))
369                   (delete-region (point)
370                                  (progn (forward-line 1) (point)))
371                 (forward-line 1))))))))
372
373 (defun flyspell-py-progmode-verify ()
374   "Replacement for standard flyspell-generic-progmode-verify which
375 checks for C/C++ preproc directives. Additionally, anything after ^L
376 is ignored (Those are the file local variables and local words)."
377   (let ((f (get-text-property (point) 'face)))
378     (and (memq f flyspell-prog-text-faces)
379          (not (save-excursion
380                 (beginning-of-line)
381                 (looking-at "#!")))
382          (not (let ((l (max (point-min) (- (point-max) 4096))))
383                 (and (< l (point))
384                      (save-excursion (search-backward "\f" l t)))))
385          (not (let* ((pos (python-in-string/comment))
386                      (c (and pos (char-after pos))))
387                 (and pos (not (save-excursion
388                                 (goto-char pos)
389                                 (beginning-of-line)
390                                 (looking-at (concat "^\\s-*[uUrR]?" (regexp-quote (make-string 3 c))))))))))))
391
392 (defun flyspell-py-mode ()
393   "Turn on `flyspell-mode` for comments and multi-line strings"
394   (interactive)
395   (setq flyspell-generic-check-word-p 'flyspell-py-progmode-verify)
396   (flyspell-mode t))
397
398 (provide 'init_python)