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