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