forked from abo-abo/lispy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
le-python.el
377 lines (348 loc) · 13.6 KB
/
le-python.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
;;; le-python.el --- lispy support for Python. -*- lexical-binding: t -*-
;; Copyright (C) 2016 Oleh Krehel
;; This file is not part of GNU Emacs
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; For a full copy of the GNU General Public License
;; see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(require 'python)
(require 'json)
(defun lispy-trim-python (str)
"Trim extra Python indentation from STR.
STR is a string copied from Python code. It can be that each line
of STR is prefixed by e.g. 4 or 8 or 12 spaces.
Stripping them will produce code that's valid for an eval."
(if (string-match "\\`\\( +\\)" str)
(let* ((indent (match-string 1 str))
(re (concat "^" indent)))
(apply #'concat
(split-string str re t)))
str))
(defun lispy-eval-python-str ()
(let (str res bnd)
(setq str
(save-excursion
(cond ((region-active-p)
(setq str (buffer-substring-no-properties
(region-beginning)
(region-end)))
(if (= (cl-count ?\n str) 0)
str
;; get rid of "unexpected indent"
(replace-regexp-in-string
(concat
"^"
(save-excursion
(goto-char (region-beginning))
(buffer-substring-no-properties
(line-beginning-position)
(point))))
"" (lispy--string-dwim))))
((looking-at lispy-outline)
(string-trim-right
(lispy--string-dwim
(lispy--bounds-dwim))))
((setq bnd (lispy-bounds-python-block))
(lispy-trim-python
(lispy--string-dwim bnd)))
((lispy-bolp)
(string-trim-left
(lispy--string-dwim
(lispy--bounds-c-toplevel))))
(t
(cond ((lispy-left-p))
((lispy-right-p)
(backward-list))
(t
(error "Unexpected")))
(setq bnd (lispy--bounds-dwim))
(ignore-errors (backward-sexp))
(while (or (eq (char-before) ?.)
(eq (char-after) ?\())
(backward-sexp))
(setcar bnd (point))
(lispy--string-dwim bnd)))))
(replace-regexp-in-string
",\n +" ","
(replace-regexp-in-string
"\\\\\n +" "" str))))
(defun lispy-bounds-python-block ()
(if (save-excursion
(when (looking-at " ")
(forward-char))
(python-info-beginning-of-block-p))
(let ((indent (1+ (- (point) (line-beginning-position)))))
(cons
(line-beginning-position)
(save-excursion
(python-nav-end-of-block)
(while (looking-at (format "[\n ]\\{%d,\\}\\(except\\|else\\)" indent))
(goto-char (match-beginning 1))
(python-nav-end-of-block))
(point))))
(cons (point)
(save-excursion
(end-of-line)
(while (member (char-before)
'(?\\ ?,))
(end-of-line 2))
(point)))))
(defun lispy-eval-python (&optional plain)
(let ((res (lispy--eval-python
(lispy-eval-python-str)
plain)))
(if (and res (not (equal res "")))
(lispy-message
(replace-regexp-in-string
"%" "%%" res))
(lispy-message lispy-eval-error))))
(defun lispy--python-proc ()
(let ((proc-name "Python Internal[lispy]"))
(if (process-live-p proc-name)
(get-process proc-name)
(setq lispy--python-middleware-loaded-p nil)
(let ((python-shell-font-lock-enable nil)
(inferior-python-mode-hook nil)
(python-binary-name (python-shell-calculate-command)))
(save-excursion
(goto-char (point-min))
(when (looking-at "#!\\(.*\\)$")
(setq python-binary-name
(concat
(match-string-no-properties 1)
" "
python-shell-interpreter-args))))
(get-buffer-process
(python-shell-make-comint
python-binary-name proc-name nil t))))))
(defun lispy--eval-python (str &optional plain)
"Eval STR as Python code."
(let ((single-line-p (= (cl-count ?\n str) 0)))
(unless plain
(setq str (string-trim-left str))
(when (and single-line-p
(string-match "\\`\\(\\(?:[., ]\\|\\sw\\|\\s_\\|[][]\\)+\\) += " str))
(setq str (concat str (format "\nprint (repr ((%s)))" (match-string 1 str))))))
(let ((res
(cond ((or single-line-p
(string-match "\n .*\\'" str)
(string-match "\"\"\"" str))
(python-shell-send-string-no-output
str (lispy--python-proc)))
((string-match "\\`\\([\0-\377[:nonascii:]]*\\)\n\\([^\n]*\\)\\'" str)
(let* ((p1 (match-string 1 str))
(p2 (match-string 2 str))
(p1-output (python-shell-send-string-no-output
p1 (lispy--python-proc)))
p2-output)
(cond ((null p1-output)
(lispy-message lispy-eval-error))
((null (setq p2-output (lispy--eval-python p2)))
(lispy-message lispy-eval-error))
(t
(concat
(if (string= p1-output "")
""
(concat p1-output "\n"))
p2-output)))))
(t
(error "unexpected")))))
(cond ((string-match "^Traceback.*:" res)
(set-text-properties
(match-beginning 0)
(match-end 0)
'(face error)
res)
(setq lispy-eval-error res)
nil)
((equal res "")
(setq lispy-eval-error "(ok)")
"")
(t
(replace-regexp-in-string "\\\\n" "\n" res))))))
(defun lispy--python-array-to-elisp (array-str)
"Transform a Python string ARRAY-STR to an Elisp string array."
(when (stringp array-str)
(mapcar (lambda (s)
(if (string-match "\\`\"" s)
(read s)
s))
(split-string
(substring array-str 1 -1)
", "
t
"u?'"))))
(defun lispy-python-completion-at-point ()
(cond ((looking-back "^\\(import\\|from\\) .*" (line-beginning-position))
(let* ((line (buffer-substring-no-properties
(line-beginning-position)
(point)))
(str
(format
"import jedi; script=jedi.Script(\"%s\",1,%d); [_x_.name for _x_ in script.completions()]"
line (length line)))
(cands
(lispy--python-array-to-elisp
(lispy--eval-python str)))
(bnd (bounds-of-thing-at-point 'symbol))
(beg (if bnd (car bnd) (point)))
(end (if bnd (cdr bnd) (point))))
(list beg end cands)))
(t
(python-shell-completion-at-point (lispy--python-proc)))))
(defvar lispy--python-arg-key-re "\\`\\(\\(?:\\sw\\|\\s_\\)+\\) ?= ?\\(.*\\)\\'"
"Constant regexp for matching function keyword spec.")
(defun lispy--python-args (beg end)
(let (res)
(save-excursion
(goto-char beg)
(while (< (point) end)
(forward-sexp)
(while (and (< (point) end)
(not (looking-at ",")))
(forward-sexp))
(push (buffer-substring-no-properties
beg (point))
res)
(skip-chars-forward ", \n")
(setq beg (point))))
(nreverse res)))
(defun lispy--python-debug-step-in ()
(re-search-forward "(" (line-end-position))
(backward-char)
(let* ((p-ar-beg (point))
(p-ar-end (save-excursion
(forward-list)
(point)))
(p-fn-end (progn
(skip-chars-backward " ")
(point)))
(p-fn-beg (progn
(backward-sexp)
(point)))
(fn (buffer-substring-no-properties
p-fn-beg p-fn-end))
(args
(lispy--python-args (1+ p-ar-beg) (1- p-ar-end)))
(args-key (cl-remove-if-not
(lambda (s)
(string-match lispy--python-arg-key-re s))
args))
(args-normal (cl-set-difference args args-key))
(fn-data
(json-read-from-string
(substring
(lispy--eval-python
(format "import inspect, json; json.dumps (inspect.getargspec (%s))"
fn))
1 -1)))
(fn-args
(mapcar #'identity (elt fn-data 0)))
(fn-defaults
(mapcar
(lambda (x)
(if (null x)
"None"
(prin1-to-string x)))
(elt fn-data 3)))
(fn-alist
(cl-mapcar #'cons
fn-args
(append (make-list (- (length fn-args)
(length fn-defaults))
nil)
fn-defaults)))
(fn-alist-x fn-alist)
dbg-cmd)
(dolist (arg args-normal)
(setcdr (pop fn-alist-x) arg))
(dolist (arg args-key)
(if (string-match lispy--python-arg-key-re arg)
(let ((arg-name (match-string 1 arg))
(arg-val (match-string 2 arg))
arg-cell)
(if (setq arg-cell (assoc arg-name fn-alist))
(setcdr arg-cell arg-val)
(error "\"%s\" is not in %s" arg-name fn-alist)))
(error "\"%s\" does not match the regex spec" arg)))
(when (memq nil (mapcar #'cdr fn-alist))
(error "Not all args were provided: %s" fn-alist))
(setq dbg-cmd
(mapconcat (lambda (x)
(format "%s = %s" (car x) (cdr x)))
fn-alist
"; "))
(if (lispy--eval-python dbg-cmd t)
(lispy-goto-symbol fn)
(goto-char p-ar-beg)
(message lispy-eval-error))))
(defun lispy-goto-symbol-python (symbol)
(save-restriction
(widen)
(let ((res (ignore-errors
(or
(deferred:sync!
(jedi:goto-definition))
t))))
(if (member res '(nil "Definition not found."))
(let* ((symbol (python-info-current-symbol))
(file (car
(lispy--python-array-to-elisp
(lispy--eval-python
(format
"import inspect\ninspect.getsourcefile(%s)" symbol))))))
(if file
(progn
(find-file file)
(goto-char (point-min))
(re-search-forward
(concat "^def.*" (car (last (split-string symbol "\\." t)))))
(beginning-of-line))
(error "Both jedi and inspect failed")))
(unless (looking-back "def " (line-beginning-position))
(jedi:goto-definition))))))
(defun lispy--python-docstring (symbol)
"Look up the docstring for SYMBOL.
First, try to see if SYMBOL.__doc__ returns a string in the
current REPL session (dynamic).
Otherwise, fall back to Jedi (static)."
(let ((dynamic-result (lispy--eval-python (concat symbol ".__doc__"))))
(if (> (length dynamic-result) 0)
(mapconcat #'string-trim-left
(split-string (substring dynamic-result 1 -1) "\\\\n")
"\n")
(require 'jedi)
(plist-get (car (deferred:sync!
(jedi:call-deferred 'get_definition)))
:doc))))
(defvar lispy--python-middleware-loaded-p nil
"Nil if the Python middleware in \"lispy-python.py\" wasn't loaded yet.")
(defun lispy--python-middleware-load ()
"Load the custom Python code in \"lispy-python.py\"."
(unless lispy--python-middleware-loaded-p
(lispy--eval-python
(format "import imp;lp=imp.load_source('lispy-python','%s')"
(expand-file-name "lispy-python.py" lispy-site-directory)))
(setq lispy--python-middleware-loaded-p t)))
(defun lispy--python-arglist (symbol filename line column)
(lispy--python-middleware-load)
(format "%s (%s)"
symbol
(mapconcat #'identity
(delete "self"
(lispy--python-array-to-elisp
(lispy--eval-python
(format "lp.arglist(%s, '%s', %s, %s)"
symbol filename line column))))
", ")))
(provide 'le-python)
;;; le-python.el ends here