-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyimp.el
More file actions
1805 lines (1603 loc) · 73.2 KB
/
pyimp.el
File metadata and controls
1805 lines (1603 loc) · 73.2 KB
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; pyimp.el --- Add import statements in Python -*- lexical-binding: t; -*-
;; Copyright (C) 2024 Karim Aziiev <karim.aziiev@gmail.com>
;; Author: Karim Aziiev <karim.aziiev@gmail.com>
;; URL: https://github.com/KarimAziev/pyimp
;; Version: 0.2.0
;; Keywords: languages
;; Package-Requires: ((emacs "29.1") (pyvenv "1.21") (project "0.11.1"))
;; SPDX-License-Identifier: GPL-3.0-or-later
;; This file is NOT part of GNU Emacs.
;; This program 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.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This library helps to insert Python import statements.
;; Usage:
;; Invoke the command `pyimp-import' to insert an import statement:
;; 1. You will be prompted for a Python module. pyimp searches your project,
;; installed libraries, and built-in modules.
;; 2. After selecting a module, pyimp presents a list of exported symbols from
;; the module. You can choose a single symbol or mark multiple symbols (if you
;; enable minibuffer marking, see `pyimp-allow-minibuffer-marking').
;; 3. Once selected, `pyimp' automatically inserts or updates the appropriate
;; import statement in your Python file.
;; If you ever need to read module documentation or review what's been imported,
;; you can use the provided module description functionality (bound under `C-j'
;; by default).
;;; Code:
(require 'project)
(require 'pyvenv)
(require 'treesit)
(defcustom pyimp-files-sorting-threshold 5000
"Threshold for enabling sorting in project files.
If the number of project files exceeds this threshold, sorting will be
inhibited.
Set this to nil to always allow sorting, or to a numeric value to
specify the threshold."
:group 'pyimp
:type '(radio
(natnum :tag "Threshold")
(const :tag "Always allow sorting" nil)))
(defcustom pyimp-extract-module-export-functions
'(pyimp-parse-exposed-exports-in-module
pyimp-eval-python-to-extract-symbols-from-module
pyimp-extract-non-imported-top-nodes)
"List of functions to extract exported symbols from a Python module.
Each function in the list should accept a single argument,the module, and return
a list of symbols that are considered exports.
The functions are executed in order until one successfully returns
a non-nil value.
To modify the behavior, add or remove functions from the list
according to the desired export extraction logic."
:group 'pyimp
:type 'hook)
(defcustom pyimp-allow-minibuffer-marking nil
"Permission to mark symbols in the minibuffer during import selection.
Determines whether marking is allowed in the minibuffer during symbol
selection for Python imports. When set to true, users can select multiple
symbols from a module using marking commands in the minibuffer.
If false, only a single symbol can be selected at a time.
See `pyimp-multiple-symbols-minibuffer-map'."
:group 'pyimp
:type 'boolean)
(defcustom pyimp-exclude-patterns-file-patterns '("\\.venv\\'"
"__editable__")
"List of regex patterns used to exclude files from project search.
A list of regular expressions used to exclude certain files when
searching for Python files in a project directory. Each element
in the list should be a string representing a regular expression
pattern. Files matching any of these patterns will be excluded
from the search results."
:group 'pyimp
:type '(repeat (regexp)))
(defcustom pyimp-debug nil
"Whether to allow debug logging.
Debug messages are logged to the *PYIMP-DEBUG* buffer.
If t, all messages will be logged.
If a number, all messages will be logged, as well shown via `message'.
If a list, it is a list of the types of messages to be logged."
:group 'pyimp
:type '(radio
(const :tag "none" nil)
(const :tag "all" t)
(checklist :tag "custom"
(integer :tag "Allow echo message buffer")
(const :tag "Cache" cache)
(symbol :tag "Other"))))
(defun pyimp-debug (tag &rest args)
"Log debug messages based on the variable `pyimp-debug'.
Argument TAG is a symbol or string used to identify the debug message.
Remaining arguments ARGS are format string followed by objects to format,
similar to `format' function arguments."
(when (or (numberp pyimp-debug)
(seq-find #'numberp pyimp-debug))
(apply #'message args))
(when (and pyimp-debug
(or (eq pyimp-debug t)
(and (listp pyimp-debug)
(memq tag pyimp-debug))))
(with-current-buffer (get-buffer-create "*PYIMP-DEBUG*")
(goto-char (point-max))
(insert (format "%s" tag) " -> " (apply #'format args) "\n"))))
(defconst pyimp--all-modules-code "\
import pkgutil
import sys
installed_modules = [
module.name for module in pkgutil.iter_modules() if module.name.isidentifier()
]
builtin_modules = [name for name in sys.builtin_module_names if name.isidentifier()]
all_modules = installed_modules + builtin_modules
emacs_lisp_readable_str = \"(\" + \" \".join(f'\"{item}\"' for item in all_modules) + \")\"
print(emacs_lisp_readable_str)
"
"Script to list import statements in Python code.")
(defconst pyimp--describe-module-code "\
import %s
print(help(%s))
"
"Script to describe Python module.")
(defconst pyimp--describe-module-symbol-code "\
from %s import %s
print(help(%s))
"
"Script to describe Python module's symbol.")
(defconst pyimp--module-symbols-script "
import %s
all_symbols = dir(%s)
symbols = [symb for symb in all_symbols if not symb.startswith(\"__\")]
emacs_lisp_readable_str = \"(\" + \" \".join(f'\"{item}\"' for item in symbols) + \")\"
print(emacs_lisp_readable_str)
"
"Template script to extract symbols from specific module.")
(defconst pyimp--module-to-file-name-code "
import importlib.util
spec = importlib.util.find_spec(%s)
if spec is not None:
print(spec.origin)
"
"String containing Python code to find a module's file path.")
(defvar pyimp-whole-module-indicator "*whole module*")
(defvar-local pyimp--current-module-to-import nil)
(defun pyimp--file-modification-time (file)
"Return the modification time of FILE.
Argument FILE is the path to the file whose modification time is needed."
(file-attribute-modification-time (file-attributes file)))
(defvar pyimp-builtins-cached nil)
(defun pyimp--locate-project-root ()
"Return the project root directory by locating the nearest `__init__.py' file."
(let ((dir default-directory)
(res))
(while
(when-let* ((last-dir (locate-dominating-file dir
"__init__.py")))
(setq res dir))
(setq dir (file-name-parent-directory dir)))
(when res
(file-name-parent-directory res))))
(defun pyimp-eval-python-to-extract-symbols-from-module (module)
"Extract and return non-private symbols from a Python module.
Argument MODULE is the name of the Python module from which to extract symbols."
(let* ((code (format pyimp--module-symbols-script module module)))
(pyimp--exec-python-code-to-elisp code)))
(defun pyimp-extract-exports-from-module (module)
"Extract exported symbols from the given MODULE."
(run-hook-with-args-until-success 'pyimp-extract-module-export-functions
module))
(defun pyimp-extract-module-exports-with-cache (module &optional filename force)
"Retrieve MODULE exports, using cache if available, else extract anew.
Argument MODULE is the name of the Python module whose exports are to be
extracted.
Optional argument FILENAME is the file path corresponding to the MODULE, which
defaults to the result of converting the MODULE name to a file name if not
provided.
Optional argument FORCE is a boolean that, when non-nil, forces the extraction
of exports without using the cache."
(unless filename
(setq filename (pyimp--module-to-file-name module)))
(if (not filename)
(pyimp-extract-exports-from-module module)
(or (and (not force)
(pyimp--get-file-cache filename))
(let ((result (pyimp-extract-exports-from-module module)))
(pyimp--set-file-cache filename result)))))
(defun pyimp--module-to-file-name (module)
"Convert a Python MODULE name to its corresponding file path.
Argument MODULE is the name of the Python module to be converted into a file
name."
(let ((cmd (if (bound-and-true-p python-interpreter)
python-interpreter
"python3")))
(unless (file-name-absolute-p cmd)
(setq cmd (executable-find cmd)))
(with-temp-buffer
(let ((status (call-process
cmd nil t nil
"-c" (format pyimp--module-to-file-name-code
(prin1-to-string
module))))
(file))
(when (zerop status)
(setq file (string-trim-right (buffer-string)))
(when (and file (file-name-absolute-p file)
(file-exists-p file))
file))))))
(defun pyimp--list-builtin-modules ()
"Return a list of all installed and built-in Python modules."
(pyimp--exec-python-code-to-elisp pyimp--all-modules-code))
(defun pyimp--exec-python-code-to-elisp (code)
"Execute Python CODE and return the trimmed output or nil on error.
Argument CODE is the Python code to be executed as a string."
(let ((cmd (if (bound-and-true-p python-interpreter)
python-interpreter
(executable-find "python3"))))
(with-temp-buffer
(let ((status (call-process
cmd nil t nil
"-c" code)))
(if (zerop status)
(progn (goto-char (point-max))
(skip-chars-backward "\s\t\n")
(backward-sexp)
(ignore-errors (read (current-buffer))))
(message "Pyimp: An error occured: %s" (buffer-string))
nil)))))
(defun pyimp--minibuffer-get-metadata ()
"Return current minibuffer completion metadata."
(completion-metadata
(buffer-substring-no-properties
(minibuffer-prompt-end)
(max (minibuffer-prompt-end)
(point)))
minibuffer-completion-table
minibuffer-completion-predicate))
(defun pyimp--minibuffer-ivy-selected-cand ()
"Return the currently selected item in Ivy."
(when (and (memq 'ivy--queue-exhibit post-command-hook)
(boundp 'ivy-text)
(boundp 'ivy--length)
(boundp 'ivy-last)
(fboundp 'ivy--expand-file-name)
(fboundp 'ivy-state-current))
(cons
(completion-metadata-get (ignore-errors (pyimp--minibuffer-get-metadata))
'category)
(ivy--expand-file-name
(if (and (> ivy--length 0)
(stringp (ivy-state-current ivy-last)))
(ivy-state-current ivy-last)
ivy-text)))))
(defun pyimp--minibuffer-get-default-candidates ()
"Return all current completion candidates from the minibuffer."
(when (minibufferp)
(let* ((all (completion-all-completions
(minibuffer-contents)
minibuffer-completion-table
minibuffer-completion-predicate
(max 0 (- (point)
(minibuffer-prompt-end)))))
(last (last all)))
(when last (setcdr last nil))
(cons
(completion-metadata-get (pyimp--minibuffer-get-metadata) 'category)
all))))
(defun pyimp--get-minibuffer-get-default-completion ()
"Target the top completion candidate in the minibuffer.
Return the category metadatum as the type of the target."
(when (and (minibufferp) minibuffer-completion-table)
(pcase-let* ((`(,category . ,candidates)
(pyimp--minibuffer-get-default-candidates))
(contents (minibuffer-contents))
(top (if (test-completion contents
minibuffer-completion-table
minibuffer-completion-predicate)
contents
(let ((completions (completion-all-sorted-completions)))
(if (null completions)
contents
(concat
(substring contents
0 (or (cdr (last completions)) 0))
(car completions)))))))
(cons category (or (car (member top candidates)) top)))))
(defvar pyimp--minibuffer-targets-finders
'(pyimp--minibuffer-ivy-selected-cand
pyimp--vertico-selected
pyimp--get-minibuffer-get-default-completion))
(defvar pyimp-modules-minibuffer-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-j") #'pyimp-show-python-help)
(define-key map (kbd "C-c C-o")
#'pyimp-abort-minibuffer-and-describe-module)
map)
"Keymap for minibuffer commands in Python import modules.")
(defvar pyimp-symbols-minibuffer-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-j") #'pyimp-show-python-help)
(define-key map (kbd "C-c C-o")
#'pyimp-abort-minibuffer-and-describe-symbol)
map))
(defvar pyimp-multiple-symbols-minibuffer-map
(let ((map (make-sparse-keymap)))
(define-key map
(kbd "C-<return>")
#'pyimp-minibuffer-done)
(define-key map
(kbd "RET")
#'pyimp-minibuffer-done)
(define-key map (kbd "C-M-j")
#'pyimp-minibuffer-done)
(define-key map (kbd "C-SPC")
#'pyimp-minibuffer-mark)
map))
(declare-function vertico--candidate "ext:vertico")
(declare-function vertico--update "ext:vertico")
(defun pyimp--vertico-selected ()
"Target the currently selected item in Vertico.
Return the category metadatum as the type of the target."
(when (bound-and-true-p vertico--input)
(vertico--update)
(cons (completion-metadata-get (pyimp--minibuffer-get-metadata) 'category)
(vertico--candidate))))
(defun pyimp--minibuffer-get-current-candidate ()
"Return cons filename for current completion candidate."
(let (target)
(run-hook-wrapped
'pyimp--minibuffer-targets-finders
(lambda (fun)
(when-let* ((result (funcall fun)))
(when (and (cdr-safe result)
(stringp (cdr-safe result))
(not (string-empty-p (cdr-safe result))))
(setq target result)))
(and target (minibufferp))))
target))
(defun pyimp--minibuffer-action-no-exit (action)
"Call ACTION with minibuffer candidate in its original window."
(pcase-let ((`(,_category . ,current)
(pyimp--minibuffer-get-current-candidate)))
(with-minibuffer-selected-window
(funcall action current))))
(defun pyimp--exec-async (program on-done on-error &rest args)
"Execute PROGRAM asynchronously with ARGS, handling completion and errors.
Argument PROGRAM is the shell command to run asynchronously.
Argument ON-DONE is the function to call when the process completes
successfully.
Argument ON-ERROR is the function to call when the process fails.
Remaining arguments ARGS are strings passed as command arguments to PROGRAM."
(require 'ansi-color)
(let* ((buff-name (generate-new-buffer-name (concat "*pyimp-" program "*")
program))
(buff (get-buffer-create buff-name))
(proc (apply #'start-file-process buff-name buff program args)))
(with-current-buffer buff
(let ((inhibit-read-only t))
(erase-buffer)))
(set-process-sentinel
proc
(lambda (process _)
(let ((buff (process-buffer process)))
(with-current-buffer buff
(if (zerop (process-exit-status process))
(when on-done
(funcall on-done))
(if on-error
(funcall on-error)
(funcall #'pop-to-buffer (current-buffer))))))))
(set-process-filter
proc
(lambda (proc string)
(when-let* ((buf (process-buffer proc)))
(with-current-buffer buf
(let ((inhibit-read-only t))
(save-excursion
(goto-char (point-max))
(insert string)))))))
proc))
(defun pyimp--get-other-wind ()
"Return another window or split sensibly if needed."
(if (minibuffer-selected-window)
(with-minibuffer-selected-window
(let ((wind (selected-window)))
(or
(window-right wind)
(window-left wind)
(split-window-sensibly)
wind)))
(let ((wind (selected-window)))
(or
(window-right wind)
(window-left wind)
(split-window-sensibly)
wind))))
(defun pyimp-abort-minibuffer-and-describe-module (module)
"Abort the minibuffer and describe the specified Python module.
Argument MODULE is the name of the Python module to describe."
(interactive
(list
(if (active-minibuffer-window)
(pcase-let
((`(,_category . ,current)
(pyimp--minibuffer-get-current-candidate)))
current)
(let ((default-directory (or
(pyimp--locate-project-root)
default-directory)))
(pyimp--completing-read-with-preview "Module: "
(pyimp--get-modules)
nil
pyimp-modules-minibuffer-map)))))
(if-let* ((wnd (active-minibuffer-window)))
(progn (select-window wnd)
(run-with-timer 0 nil #'pyimp-show-python-help module module t)
(abort-minibuffers))
(pyimp-show-python-help module module t)))
(defun pyimp-abort-minibuffer-and-describe-symbol (module symbol)
"Abort the minibuffer and display Python help for a symbol.
Argument MODULE is the name of the Python module for which help is requested.
Argument SYMBOL is the specific symbol within the MODULE for which help is
requested."
(interactive
(pyimp--module-and-symbol-for-help))
(if-let* ((wnd (active-minibuffer-window)))
(progn (select-window wnd)
(run-with-timer 0 nil #'pyimp-show-python-help module symbol t)
(abort-minibuffers))
(pyimp-show-python-help module symbol t)))
(defun pyimp--module-and-symbol-for-help ()
"Return a list containing a module and a symbol for displaying the help."
(let* ((module
(if (active-minibuffer-window)
(or pyimp--current-module-to-import
(pcase-let
((`(,_category . ,current)
(pyimp--minibuffer-get-current-candidate)))
current))
(let* ((default-directory (or
(pyimp--locate-project-root)
default-directory)))
(pyimp--completing-read-with-preview
"Module: "
(pyimp--get-modules)
nil
pyimp-modules-minibuffer-map))))
(symbol
(if (active-minibuffer-window)
(pcase-let
((`(,_category . ,current)
(pyimp--minibuffer-get-current-candidate)))
current)
(let ((default-directory (or
(pyimp--locate-project-root)
default-directory)))
(pyimp--completing-read-symbol module)))))
(list module (if (equal symbol pyimp-whole-module-indicator)
module
symbol))))
(defun pyimp-show-python-help (module symbol &optional select)
"Display Python help for a specified MODULE or SYMBOL in a buffer.
Argument MODULE is the name of the Python module for which help is requested.
Argument SYMBOL is the specific symbol within the MODULE for which help is
requested. If it is the same as MODULE, or as `pyimp-whole-module-indicator',
show documentation for the whole module.
Optional argument SELECT, when non-nil, selects the window displaying the help
buffer."
(interactive
(pyimp--module-and-symbol-for-help))
(require 'ansi-color)
(let* ((mini-wind (minibuffer-selected-window))
(buff-name (concat "*pyimp-help*"))
(buff (progn
(when (get-buffer buff-name)
(kill-buffer buff-name))
(get-buffer-create buff-name)))
(code
(if (equal module symbol)
(format pyimp--describe-module-code module symbol)
(format pyimp--describe-module-symbol-code module symbol symbol)))
(proc
(let ((default-directory (or
(pyimp--locate-project-root)
default-directory)))
(start-process buff-name buff "python" "-c" code))))
(with-current-buffer buff
(special-mode)
(let ((inhibit-read-only t))
(erase-buffer)))
(set-process-sentinel
proc
(lambda (process _)
(let ((buff (process-buffer process)))
(when (and (buffer-live-p buff)
(or (not mini-wind)
(eq mini-wind
(minibuffer-selected-window))))
(with-current-buffer buff
(let ((inhibit-read-only t))
(pyimp--fontify-module-help)
(goto-char (point-min))
(let ((wnd (pyimp--get-other-wind)))
(with-selected-window wnd
(pop-to-buffer-same-window buff))
(when select
(select-window wnd)))))))))
(set-process-filter
proc
(lambda (proc string)
(when-let* ((buf (process-buffer proc)))
(with-current-buffer buf
(let ((inhibit-read-only t))
(save-excursion
(goto-char (point-max))
(insert string)))))))
proc))
(defalias 'pyimp-describe-module #'pyimp-show-python-help)
(defvar Man-ansi-color-basic-faces-vector)
(defvar browse-url-button-regexp)
(defun pyimp--fontify-region (beg end)
"Fontify the region between BEG and END using Python mode.
Argument BEG is the beginning position of the region to fontify.
Argument END is the ending position of the region to fontify."
(let* ((str (buffer-substring beg end))
(fontified-str (with-temp-buffer
(delay-mode-hooks
(python-mode)
(goto-char (point-min))
(insert str)
(font-lock-ensure)
(buffer-string)))))
(goto-char beg)
(delete-region beg end)
(insert fontified-str)))
(defun pyimp--fontify-module-help ()
"Convert overstriking and underlining to the correct fonts.
Same for the ANSI bold and normal escape sequences."
(require 'man)
(require 'browse-url)
(goto-char (point-min))
(let ((ansi-color-apply-face-function #'ansi-color-apply-text-property-face)
(ansi-color-basic-faces-vector Man-ansi-color-basic-faces-vector))
(ansi-color-apply-on-region (point-min)
(point-max)))
(let ((buffer-undo-list t))
(if (< (buffer-size)
(position-bytes (point-max)))
(progn
(goto-char (point-min))
(while (and (search-forward "__\b\b" nil t)
(not (eobp)))
(delete-char -4)
(put-text-property (point)
(1+ (point))
'font-lock-face 'Man-underline))
(goto-char (point-min))
(while (search-forward "\b\b__" nil t)
(delete-char -4)
(put-text-property (1- (point))
(point)
'font-lock-face 'Man-underline))))
(goto-char (point-min))
(while (and (search-forward "_\b" nil t)
(not (eobp)))
(delete-char -2)
(put-text-property (point)
(1+ (point)) 'font-lock-face 'Man-underline))
(goto-char (point-min))
(while (search-forward "\b_" nil t)
(delete-char -2)
(put-text-property (1- (point))
(point) 'font-lock-face 'Man-underline))
(goto-char (point-min))
(while (re-search-forward "\\(.\\)\\(\b+\\1\\)+" nil t)
(replace-match "\\1")
(put-text-property (1- (point))
(point) 'font-lock-face 'Man-overstrike))
(goto-char (point-min))
(while (re-search-forward "o\b\\+\\|\\+\bo" nil t)
(replace-match "o")
(put-text-property (1- (point))
(point) 'font-lock-face 'bold))
(goto-char (point-min))
(while (re-search-forward "[-|]\\(\b[-|]\\)+" nil t)
(replace-match "+")
(put-text-property (1- (point))
(point) 'font-lock-face 'bold))
(goto-char (point-min))
(while (re-search-forward ".\b" nil t)
(delete-char -2))
(goto-char (point-min))
(unless (string-prefix-p "latin-" current-language-environment t)
(goto-char (point-min))
(while (search-forward "" nil t)
(replace-match "-")))
(goto-char (point-min))
(while (re-search-forward "^\\([[:upper:]][[:upper:]0-9 /-]+\\)$" nil t)
(put-text-property (match-beginning 0)
(match-end 0)
'font-lock-face 'Man-overstrike))
(goto-char (point-min))
(while (re-search-forward "^[\s\t]*\\(class\\|def\\)[\s]\\([a-z0-9_]+\\)"
nil
t)
(put-text-property (match-beginning 1)
(match-end 1)
'font-lock-face 'font-lock-keyword-face)
(put-text-property (match-beginning 2)
(match-end 2)
'font-lock-face 'font-lock-type-face))
(pcase-dolist
(`(,section . ,face)
'(("FUNCTIONS" . font-lock-function-name-face)
("CLASSES" . font-lock-function-name-face)
("DATA" . font-lock-function-name-face)))
(goto-char (point-min))
(when (re-search-forward (concat "^" (regexp-quote section) "\n") nil t)
(let ((end (save-excursion
(re-search-forward "^\\([[:upper:]][[:upper:]0-9 /-]+\\)$"
nil t))))
(while (re-search-forward "^[\s|]+\\([a-z0-9_.]+\\)[\s]*[(=]" end t 1)
(put-text-property (match-beginning 1)
(match-end 1)
'font-lock-face face)))))
(goto-char (point-max))
(when (re-search-backward "^FILE[\n][\s]+\\([^\n]+\\)" nil t
1)
(let ((file (match-string-no-properties 1))
(beg (match-beginning 1))
(end (match-end 1)))
(buttonize-region beg end #'find-file-other-window file)))
(goto-char (point-max))
(while (re-search-backward browse-url-button-regexp nil t 1)
(let ((beg (match-beginning 0))
(end (match-end 0)))
(buttonize-region beg end #'browse-url (buffer-substring-no-properties
beg end))))
(font-lock-update)
(goto-char (point-max))
(while (re-search-backward "['`]\\([a-zA-Z_][a-zA-Z0-9_.]+\\)['`]" nil t 1)
(let ((beg (match-beginning 1))
(end (match-end 1)))
(if (string-match-p "self\\." (buffer-substring-no-properties beg end))
(pyimp--fontify-region beg end)
(put-text-property beg
end
'font-lock-face 'font-lock-type-face))))
(goto-char (point-min))
(let ((re (rx (seq bol
(zero-or-more " ")
"| "
(group
(group
(any "a-z" "_")
(one-or-more
(any "0-9a-z" "_")))
(zero-or-more nonl))
"\n | "))))
(while
(re-search-forward
re
nil t 1)
(let* ((beg (match-beginning 1))
(end (match-end 1))
(beg-name (match-beginning 2))
(end-name (match-end 2)))
(pyimp--fontify-region beg
end)
(put-text-property beg-name
end-name
'font-lock-face 'font-lock-function-name-face))))
(goto-char (point-min))
(while (re-search-forward "^\\([a-z_][a-z0-9_]+\\)([^\n]+" nil t 1)
(let* ((beg (match-beginning 0))
(end (match-end 0))
(beg-name (match-beginning 1))
(end-name (match-end 1)))
(pyimp--fontify-region beg
end)
(put-text-property beg-name
end-name
'font-lock-face 'font-lock-function-name-face)))
(goto-char (point-min))
(let ((re (rx (group
(or (seq bol
(zero-or-more " ")
"|"
(zero-or-more " ")
(group "Methods defined here:"))
(seq bol
(zero-or-more " ")
"|"
(zero-or-more " ")
"----------------------------------------------------------------------\n"
(zero-or-more " ")
"|"
(one-or-more " ")
(group
(any "a-z")
(one-or-more nonl))))))))
(while (re-search-forward
re
nil t 1)
(put-text-property
(or (match-beginning 3)
(match-beginning 2))
(or (match-end 3)
(match-end 2))
'font-lock-face 'font-lock-keyword-face)))))
(defun pyimp--completing-read-with-preview (prompt collection &optional
preview-action keymap
predicate require-match
initial-input hist def
inherit-input-method)
"Read COLLECTION in minibuffer with PROMPT and KEYMAP.
See `completing-read' for PREDICATE REQUIRE-MATCH INITIAL-INPUT HIST DEF
INHERIT-INPUT-METHOD."
(let ((collection (if (stringp (car-safe collection))
(copy-tree collection)
collection)))
(minibuffer-with-setup-hook
(lambda ()
(when (minibufferp)
(when keymap
(let ((map (make-composed-keymap keymap
(current-local-map))))
(use-local-map map)))
(when preview-action
(add-hook 'pre-command-hook (lambda ()
(interactive)
(pyimp--minibuffer-action-no-exit
preview-action))
nil t))))
(completing-read prompt
collection
predicate
require-match initial-input hist
def inherit-input-method))))
(defun pyimp--get-modules ()
"Return a list of Python modules in the project."
(let* ((project
(or
(pyimp--locate-project-root)
default-directory))
(files
(directory-files-recursively
project
"\\.py\\'"
nil
(lambda (it)
(or (not pyvenv-virtual-env)
(not
(file-equal-p it pyvenv-virtual-env))))))
(sorted-files
(mapcar (lambda (file)
(replace-regexp-in-string
"/"
"."
(if (and pyvenv-virtual-env
(file-in-directory-p file pyvenv-virtual-env))
(car (last (split-string file "/site-packages/" t)))
(substring-no-properties
(expand-file-name (file-name-sans-extension
file))
(length project)))))
(remove buffer-file-name
(sort files
(lambda (a b)
(not
(time-less-p
(pyimp--file-modification-time
a)
(pyimp--file-modification-time
b))))))))
(builtins
(setq pyimp-builtins-cached (pyimp--list-builtin-modules)))
(all-modules (append sorted-files builtins)))
all-modules))
(defvar-local pyimp-modules nil)
(defvar pyimp--files-cache (make-hash-table :test 'equal))
(defun pyimp--get-file-cache (cache-key)
"Retrieve cached data if file hasn't changed.
Argument CACHE-KEY is a key used to retrieve the cache entry from
`pyimp--files-cache'."
(let* ((cache (gethash cache-key pyimp--files-cache))
(cache-tick (and cache (plist-get cache :tick)))
(tick (file-attribute-modification-time (file-attributes
cache-key
'string))))
(if (not (equal cache-tick tick))
(pyimp-debug 'cache "No cache found for %s" cache-key)
(pyimp-debug 'cache "Found cache for %s" cache-key)
(plist-get cache :cache))))
(defun pyimp--set-file-cache (path content)
"Cache file CONTENT with modification time.
Argument PATH is the file path for which to set the cache.
Argument CONTENT is the content to be cached for the specified file."
(let* ((cache (gethash path pyimp--files-cache))
(tick (file-attribute-modification-time (file-attributes
path
'string))))
(setq cache (list :tick tick
:cache content))
(puthash path cache
pyimp--files-cache)
(plist-get cache :cache)))
(defun pyimp--file-name-to-module-path (file &optional abs-prefix)
"Convert FILE path to module path, using ABS-PREFIX if provided.
Argument FILE is the name of the file to be converted into a module path.
Optional argument ABS-PREFIX is a prefix used when FILE is an absolute path."
(let ((module (if (and abs-prefix
(file-name-absolute-p file))
(substring-no-properties
(expand-file-name
(file-name-sans-extension
file))
(length
(expand-file-name
abs-prefix)))
(file-name-sans-extension file))))
(replace-regexp-in-string "/" "." (replace-regexp-in-string
"^\\|/__init__\\'" "" module))))
(defun pyimp--get-site-packages (lib-dir &optional force)
"Retrieve and cache Python module paths from a specified directory.
Argument LIB-DIR is the directory path to search for Python
site-packages.
Optional argument FORCE, when non-nil, bypasses the cache and forces a fresh
directory scan."
(setq lib-dir (file-name-as-directory (expand-file-name lib-dir)))
(or (and (not force)
(pyimp--get-file-cache lib-dir))
(let ((dirs (directory-files lib-dir t
directory-files-no-dot-files-regexp))
(result))
(while dirs
(let ((abs-dir (pop dirs)))
(cond ((and (file-directory-p abs-dir))
(when (file-accessible-directory-p abs-dir)
(let ((files
(delq nil
(mapcar
(lambda (file)
(unless (and (string=
(file-name-base file)
"__init__")
(equal (file-name-extension
file)
"py"))
(let ((module-path
(pyimp--file-name-to-module-path
file
lib-dir)))
(cons module-path file))))
(directory-files-recursively
abs-dir
"\\.py\\'"
t
(lambda
(subdirectory)
(file-exists-p
(expand-file-name
"__init__.py"
subdirectory))))))))
(when files
(setq files (push
(cons
(pyimp--file-name-to-module-path
abs-dir lib-dir)
abs-dir)
files))