forked from Wilfred/helpful
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpful.el
3023 lines (2732 loc) · 104 KB
/
helpful.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
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
;;; helpful.el --- A better *help* buffer -*- lexical-binding: t; -*-
;; Copyright (C) 2017-2022 Wilfred Hughes
;; Author: Wilfred Hughes <[email protected]>
;; URL: https://github.com/Wilfred/helpful
;; Keywords: help, lisp
;; Version: 0.20
;; Package-Requires: ((emacs "25") (dash "2.18.0") (s "1.11.0") (f "0.20.0") (elisp-refs "1.2"))
;; 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 of the License, 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:
;; Helpful is a replacement for *help* buffers that provides much more
;; contextual information. To get started, try:
;; `M-x helpful-function RET helpful-function
;;
;; The full set of commands you can try is:
;;
;; * helpful-function
;; * helpful-command
;; * helpful-key
;; * helpful-macro
;; * helpful-callable
;; * helpful-variable
;; * helpful-at-point
;;
;; For more information and screenshots, see
;; https://github.com/wilfred/helpful
;;; Code:
(require 'elisp-refs)
(require 'help)
(require 'help-fns)
(require 'dash)
(require 's)
(require 'f)
(require 'find-func)
(require 'nadvice)
(require 'info-look)
(require 'edebug)
(require 'trace)
(require 'imenu)
(require 'cc-langs)
(defvar-local helpful--sym nil)
(defvar-local helpful--callable-p nil)
(defvar-local helpful--associated-buffer nil
"The buffer being used when showing inspecting
buffer-local variables.")
(defvar-local helpful--start-buffer nil
"The buffer we were originally called from.")
(defvar-local helpful--view-literal nil
"Whether to show a value as a literal, or a pretty interactive
view.")
(defvar-local helpful--first-display t
"Whether this is the first time this results buffer has been
displayed.
Nil means that we're refreshing, so we don't want to clobber any
settings changed by the user.")
(defgroup helpful nil
"A rich help system with contextual information."
:link '(url-link "https://github.com/Wilfred/helpful")
:group 'help)
(defcustom helpful-max-buffers
5
"Helpful will kill the least recently used Helpful buffer
if there are more than this many.
To disable cleanup entirely, set this variable to nil. See also
`helpful-kill-buffers' for a one-off cleanup."
:type '(choice (const nil) number)
:group 'helpful)
(defcustom helpful-switch-buffer-function
#'pop-to-buffer
"Function called to display the *Helpful* buffer."
:type 'function
:group 'helpful)
;; TODO: explore whether more basic highlighting is fast enough to
;; handle larger functions. See `c-font-lock-init' and its use of
;; font-lock-keywords-1.
(defconst helpful-max-highlight 5000
"Don't highlight code with more than this many characters.
This is currently only used for C code, as lisp highlighting
seems to be more efficient. This may change again in future.
See `this-command' as an example of a large piece of C code that
can make Helpful very slow.")
(defun helpful--kind-name (symbol callable-p)
"Describe what kind of symbol this is."
(cond
((not callable-p) "variable")
((commandp symbol) "command")
((macrop symbol) "macro")
((functionp symbol) "function")
((special-form-p symbol) "special form")))
(defun helpful--buffer (symbol callable-p)
"Return a buffer to show help for SYMBOL in."
(let* ((current-buffer (current-buffer))
(buf-name
(format "*helpful %s*"
(if (symbolp symbol)
(format "%s: %s"
(helpful--kind-name symbol callable-p)
symbol)
"lambda")))
(buf (get-buffer buf-name)))
(unless buf
;; If we need to create the buffer, ensure we don't exceed
;; `helpful-max-buffers' by killing the least recently used.
(when (numberp helpful-max-buffers)
(let* ((buffers (buffer-list))
(helpful-bufs (--filter (with-current-buffer it
(eq major-mode 'helpful-mode))
buffers))
;; `buffer-list' seems to be ordered by most recently
;; visited first, so keep those.
(excess-buffers (-drop (1- helpful-max-buffers) helpful-bufs)))
;; Kill buffers so we have one buffer less than the maximum
;; before we create a new one.
(-each excess-buffers #'kill-buffer)))
(setq buf (get-buffer-create buf-name)))
;; Initialise the buffer with the symbol and associated data.
(with-current-buffer buf
(helpful-mode)
(setq helpful--sym symbol)
(setq helpful--callable-p callable-p)
(setq helpful--start-buffer current-buffer)
(setq helpful--associated-buffer current-buffer)
(setq list-buffers-directory
(if (symbolp symbol) (format "%s: %s" (helpful--kind-name symbol callable-p) symbol) "lambda"))
(if (helpful--primitive-p symbol callable-p)
(setq-local comment-start "//")
(setq-local comment-start ";")))
buf))
(defface helpful-heading
'((t (:weight bold)))
"Face used for headings in Helpful buffers.")
(defun helpful--heading (text)
"Propertize TEXT as a heading."
(format "%s\n" (propertize text 'face 'helpful-heading)))
(defun helpful--format-closure (sym form)
"Given a closure, return an equivalent defun form."
(-let (((_keyword _env args . body) form)
(docstring nil))
(when (stringp (car body))
(setq docstring (car body))
(setq body (cdr body))
;; Ensure that the docstring doesn't have lines starting with (,
;; or it breaks indentation.
(setq docstring
(s-replace "\n(" "\n\\(" docstring)))
(if docstring
`(defun ,sym ,args ,docstring ,@body)
`(defun ,sym ,args ,@body))))
(defun helpful--pretty-print (value)
"Pretty-print VALUE.
If VALUE is very big, the user may press \\[keyboard-quit] to
gracefully stop the printing. If VALUE is self-referential, the
error will be caught and displayed."
;; Inspired by `ielm-eval-input'.
(condition-case err
(s-trim-right (pp-to-string value))
(error
(propertize (format "(Display error: %s)" (cadr err))
'face 'font-lock-comment-face))
(quit
(propertize "(User quit during pretty-printing.)"
'face 'font-lock-comment-face))))
(defun helpful--sort-symbols (sym-list)
"Sort symbols in SYM-LIST alphabetically."
(--sort
(string< (symbol-name it) (symbol-name other))
sym-list))
(defun helpful--button (text type &rest properties)
;; `make-text-button' mutates our string to add properties. Copy
;; TEXT to prevent mutating our arguments, and to support 'pure'
;; strings, which are read-only.
(setq text (substring-no-properties text))
(apply #'make-text-button
text nil
:type type
properties))
(defun helpful--canonical-symbol (sym callable-p)
"If SYM is an alias, return the underlying symbol.
Return SYM otherwise."
(let ((depth 0))
(if (and (symbolp sym) callable-p)
(progn
;; Follow the chain of symbols until we find a symbol that
;; isn't pointing to a symbol.
(while (and (symbolp (symbol-function sym))
(< depth 10))
(setq sym (symbol-function sym))
(setq depth (1+ depth)))
;; If this is an alias to a primitive, return the
;; primitive's symbol.
(when (subrp (symbol-function sym))
(setq sym (intern (subr-name (symbol-function sym))))))
(setq sym (indirect-variable sym))))
sym)
(defun helpful--aliases (sym callable-p)
"Return all the aliases for SYM."
(let ((canonical (helpful--canonical-symbol sym callable-p))
aliases)
(mapatoms
(lambda (s)
(when (and
;; Skip variables that aren't bound, so we're faster.
(if callable-p (fboundp s) (boundp s))
;; If this symbol is a new alias for our target sym,
;; add it.
(eq canonical (helpful--canonical-symbol s callable-p))
;; Don't include SYM.
(not (eq sym s)))
(push s aliases))))
(helpful--sort-symbols aliases)))
(defun helpful--obsolete-info (sym callable-p)
(when (symbolp sym)
(get sym (if callable-p 'byte-obsolete-info 'byte-obsolete-variable))))
(defun helpful--format-alias (sym callable-p)
(let ((obsolete-info (helpful--obsolete-info sym callable-p))
(sym-button (helpful--button
(symbol-name sym)
'helpful-describe-exactly-button
'symbol sym
'callable-p callable-p)))
(cond
(obsolete-info
(-if-let (version (-last-item obsolete-info))
(format "%s (obsolete since %s)" sym-button version)
(format "%s (obsolete)" sym-button)))
(t
sym-button))))
(defun helpful--indent-rigidly (s amount)
"Indent string S by adding AMOUNT spaces to each line."
(with-temp-buffer
(insert s)
(indent-rigidly (point-min) (point-max) amount)
(buffer-string)))
(defun helpful--format-properties (symbol)
"Return a string describing all the properties of SYMBOL."
(let* ((syms-and-vals
(-partition 2 (and (symbolp symbol) (symbol-plist symbol))))
(syms-and-vals
(-sort (-lambda ((sym1 _) (sym2 _))
(string-lessp (symbol-name sym1) (symbol-name sym2)))
syms-and-vals))
(lines
(--map
(-let* (((sym val) it)
(pretty-val
(helpful--pretty-print val)))
(format "%s\n%s%s"
(propertize (symbol-name sym)
'face 'font-lock-constant-face)
(helpful--indent-rigidly pretty-val 2)
(cond
;; Also offer to disassemble byte-code
;; properties.
((byte-code-function-p val)
(format "\n %s"
(helpful--make-disassemble-button val)))
((eq sym 'ert--test)
(format "\n %s"
(helpful--make-run-test-button symbol)))
(t
""))))
syms-and-vals)))
(when lines
(s-join "\n" lines))))
(define-button-type 'helpful-forget-button
'action #'helpful--forget
'symbol nil
'callable-p nil
'follow-link t
'help-echo "Unbind this function")
;; TODO: it would be nice to optionally delete the source code too.
(defun helpful--forget (button)
"Unbind the current symbol."
(let* ((sym (button-get button 'symbol))
(callable-p (button-get button 'callable-p))
(kind (helpful--kind-name sym callable-p)))
(when (yes-or-no-p (format "Forget %s %s?" kind sym))
(if callable-p
(fmakunbound sym)
(makunbound sym))
(message "Forgot %s %s." kind sym)
(kill-buffer (current-buffer)))))
(define-button-type 'helpful-c-source-directory
'action #'helpful--c-source-directory
'follow-link t
'help-echo "Set directory to Emacs C source code")
(defun helpful--c-source-directory (_button)
"Set `find-function-C-source-directory' so we can show the
source code to primitives."
(let ((emacs-src-dir (read-directory-name "Path to Emacs source code: ")))
;; Let the user specify the source path with or without src/,
;; which is a subdirectory in the Emacs tree.
(unless (equal (f-filename emacs-src-dir) "src")
(setq emacs-src-dir (f-join emacs-src-dir "src")))
(setq find-function-C-source-directory emacs-src-dir))
(helpful-update))
(define-button-type 'helpful-disassemble-button
'action #'helpful--disassemble
'follow-link t
'object nil
'help-echo "Show disassembled bytecode")
(defun helpful--disassemble (button)
"Disassemble the current symbol."
;; `disassemble' can handle both symbols (e.g. 'when) and raw
;; byte-code objects.
(disassemble (button-get button 'object)))
(define-button-type 'helpful-run-test-button
'action #'helpful--run-test
'follow-link t
'symbol nil
'help-echo "Run ERT test")
(defun helpful--run-test (button)
"Disassemble the current symbol."
(ert (button-get button 'symbol)))
(define-button-type 'helpful-edebug-button
'action #'helpful--edebug
'follow-link t
'symbol nil
'help-echo "Toggle edebug (re-evaluates definition)")
(defun helpful--kbd-macro-p (sym)
"Is SYM a keyboard macro?"
(and (symbolp sym)
(let ((func (symbol-function sym)))
(or (stringp func)
(vectorp func)))))
(defun helpful--edebug-p (sym)
"Does function SYM have its definition patched by edebug?"
(let ((fn-def (indirect-function sym)))
;; Edebug replaces function source code with a sexp that has
;; `edebug-enter', `edebug-after' etc interleaved. This means the
;; function is interpreted, so `indirect-function' returns a list.
(when (and (consp fn-def) (consp (cdr fn-def)))
(-let [fn-end (-last-item fn-def)]
(and (consp fn-end)
(eq (car fn-end) 'edebug-enter))))))
(defun helpful--can-edebug-p (sym callable-p buf pos)
"Can we use edebug with SYM?"
(and
;; SYM must be a function.
callable-p
;; The function cannot be a primitive, it must be defined in elisp.
(not (helpful--primitive-p sym callable-p))
;; We need to be able to find its definition, or we can't step
;; through the source.
buf pos))
(defun helpful--toggle-edebug (sym)
"Enable edebug when function SYM is called,
or disable if already enabled."
(-let ((should-edebug (not (helpful--edebug-p sym)))
((buf pos created) (helpful--definition sym t)))
(if (and buf pos)
(progn
(with-current-buffer buf
(save-excursion
(save-restriction
(widen)
(goto-char pos)
(let* ((edebug-all-forms should-edebug)
(edebug-all-defs should-edebug)
(form (edebug-read-top-level-form)))
;; Based on `edebug-eval-defun'.
(eval (eval-sexp-add-defvars form) lexical-binding)))))
;; If we're enabling edebug, we need the source buffer to
;; exist. Otherwise, we can clean it up.
(when (and created (not should-edebug))
(kill-buffer buf)))
(user-error "Could not find source for edebug"))))
(defun helpful--edebug (button)
"Toggle edebug for the current symbol."
(helpful--toggle-edebug (button-get button 'symbol))
(helpful-update))
(define-button-type 'helpful-trace-button
'action #'helpful--trace
'follow-link t
'symbol nil
'help-echo "Toggle function tracing")
(defun helpful--trace (button)
"Toggle tracing for the current symbol."
(let ((sym (button-get button 'symbol)))
(if (trace-is-traced sym)
(untrace-function sym)
(trace-function sym)))
(helpful-update))
(define-button-type 'helpful-navigate-button
'action #'helpful--navigate
'path nil
'position nil
'follow-link t
'help-echo "Navigate to definition")
(defun helpful--goto-char-widen (pos)
"Move point to POS in the current buffer.
If narrowing is in effect, widen if POS isn't in the narrowed area."
(when (or (< pos (point-min))
(> pos (point-max)))
(widen))
(goto-char pos))
(defun helpful--navigate (button)
"Navigate to the path this BUTTON represents."
(find-file (substring-no-properties (button-get button 'path)))
;; We use `get-text-property' to work around an Emacs 25 bug:
;; http://git.savannah.gnu.org/cgit/emacs.git/commit/?id=f7c4bad17d83297ee9a1b57552b1944020f23aea
(-when-let (pos (get-text-property button 'position
(marker-buffer button)))
(helpful--goto-char-widen pos)))
(defun helpful--navigate-button (text path &optional pos)
"Return a button that opens PATH and puts point at POS."
(helpful--button
text
'helpful-navigate-button
'path path
'position pos))
(define-button-type 'helpful-buffer-button
'action #'helpful--switch-to-buffer
'buffer nil
'position nil
'follow-link t
'help-echo "Switch to this buffer")
(defun helpful--switch-to-buffer (button)
"Navigate to the buffer this BUTTON represents."
(let ((buf (button-get button 'buffer))
(pos (button-get button 'position)))
(switch-to-buffer buf)
(when pos
(helpful--goto-char-widen pos))))
(defun helpful--buffer-button (buffer &optional pos)
"Return a button that switches to BUFFER and puts point at POS."
(helpful--button
(buffer-name buffer)
'helpful-buffer-button
'buffer buffer
'position pos))
(define-button-type 'helpful-customize-button
'action #'helpful--customize
'symbol nil
'follow-link t
'help-echo "Open Customize for this symbol")
(defun helpful--customize (button)
"Open Customize for this symbol."
(customize-variable (button-get button 'symbol)))
(define-button-type 'helpful-associated-buffer-button
'action #'helpful--associated-buffer
'symbol nil
'prompt-p nil
'follow-link t
'help-echo "Change associated buffer")
(defun helpful--read-live-buffer (prompt predicate)
"Read a live buffer name, and return the buffer object.
This is largely equivalent to `read-buffer', but counsel.el
overrides that to include previously opened buffers."
(let* ((names (-map #'buffer-name (buffer-list)))
(default
(cond
;; If we're already looking at a buffer-local value, start
;; the prompt from the relevant buffer.
((and helpful--associated-buffer
(buffer-live-p helpful--associated-buffer))
(buffer-name helpful--associated-buffer))
;; If we're looking at the global value, offer the initial
;; buffer.
((and helpful--start-buffer
(buffer-live-p helpful--start-buffer))
(buffer-name helpful--start-buffer))
;; If we're looking at the global value and have no initial
;; buffer, choose the first normal buffer.
(t
(--first (and (not (s-starts-with-p " " it))
(not (s-starts-with-p "*" it)))
names))
)))
(get-buffer
(completing-read
prompt
names
predicate
t
nil
nil
default))))
(defun helpful--associated-buffer (button)
"Change the associated buffer, so we can see buffer-local values."
(let ((sym (button-get button 'symbol))
(prompt-p (button-get button 'prompt-p)))
(if prompt-p
(setq helpful--associated-buffer
(helpful--read-live-buffer
"View variable in: "
(lambda (buf-name)
(local-variable-p sym (get-buffer buf-name)))))
(setq helpful--associated-buffer nil)))
(helpful-update))
(define-button-type 'helpful-toggle-button
'action #'helpful--toggle
'symbol nil
'buffer nil
'follow-link t
'help-echo "Toggle this symbol between t and nil")
(defun helpful--toggle (button)
"Toggle the symbol between nil and t."
(let ((sym (button-get button 'symbol))
(buf (button-get button 'buffer)))
(save-current-buffer
;; If this is a buffer-local variable, ensure we're in the right
;; buffer.
(when buf
(set-buffer buf))
(set sym (not (symbol-value sym))))
(helpful-update)))
(define-button-type 'helpful-set-button
'action #'helpful--set
'symbol nil
'buffer nil
'follow-link t
'help-echo "Set the value of this symbol")
(defun helpful--set (button)
"Set the value of this symbol."
(let* ((sym (button-get button 'symbol))
(buf (button-get button 'buffer))
(sym-value (helpful--sym-value sym buf))
;; Inspired by `counsel-read-setq-expression'.
(expr
(minibuffer-with-setup-hook
(lambda ()
(add-function :before-until (local 'eldoc-documentation-function)
#'elisp-eldoc-documentation-function)
(run-hooks 'eval-expression-minibuffer-setup-hook)
(goto-char (minibuffer-prompt-end))
(forward-char (length (format "(setq %S " sym))))
(read-from-minibuffer
"Eval: "
(format
(if (or (consp sym-value)
(and (symbolp sym-value)
(not (null sym-value))
(not (keywordp sym-value))))
"(setq %s '%S)"
"(setq %s %S)")
sym sym-value)
read-expression-map t
'read-expression-history))))
(save-current-buffer
;; If this is a buffer-local variable, ensure we're in the right
;; buffer.
(when buf
(set-buffer buf))
(eval-expression expr))
(helpful-update)))
(define-button-type 'helpful-view-literal-button
'action #'helpful--view-literal
'help-echo "Toggle viewing as a literal")
(defun helpful--view-literal (_button)
"Set the value of this symbol."
(setq helpful--view-literal
(not helpful--view-literal))
(helpful-update))
(define-button-type 'helpful-all-references-button
'action #'helpful--all-references
'symbol nil
'callable-p nil
'follow-link t
'help-echo "Find all references to this symbol")
(defun helpful--all-references (button)
"Find all the references to the symbol that this BUTTON represents."
(let ((sym (button-get button 'symbol))
(callable-p (button-get button 'callable-p)))
(cond
((not callable-p)
(elisp-refs-variable sym))
((functionp sym)
(elisp-refs-function sym))
((macrop sym)
(elisp-refs-macro sym)))))
(define-button-type 'helpful-callees-button
'action #'helpful--show-callees
'symbol nil
'source nil
'follow-link t
'help-echo "Find the functions called by this function/macro")
(defun helpful--display-callee-group (callees)
"Insert every entry in CALLEES."
(dolist (sym (helpful--sort-symbols callees))
(insert " "
(helpful--button
(symbol-name sym)
'helpful-describe-exactly-button
'symbol sym
'callable-p t)
"\n")))
(defun helpful--show-callees (button)
"Find all the references to the symbol that this BUTTON represents."
(let* ((buf (get-buffer-create "*helpful callees*"))
(sym (button-get button 'symbol))
(raw-source (button-get button 'source))
(source
(if (stringp raw-source)
(read raw-source)
raw-source))
(syms (helpful--callees source))
(primitives (-filter (lambda (sym) (helpful--primitive-p sym t)) syms))
(compounds (-remove (lambda (sym) (helpful--primitive-p sym t)) syms)))
(pop-to-buffer buf)
(let ((inhibit-read-only t))
(erase-buffer)
;; TODO: Macros used, special forms used, global vars used.
(insert (format "Functions called by %s:\n\n" sym))
(helpful--display-callee-group compounds)
(when primitives
(insert "\n")
(insert (format "Primitives called by %s:\n\n" sym))
(helpful--display-callee-group primitives))
(goto-char (point-min))
(helpful-mode))))
(define-button-type 'helpful-manual-button
'action #'helpful--manual
'symbol nil
'follow-link t
'help-echo "View this symbol in the Emacs manual")
(defun helpful--manual (button)
"Open the manual for the system that this BUTTON represents."
(let ((sym (button-get button 'symbol)))
(info-lookup 'symbol sym #'emacs-lisp-mode)))
(define-button-type 'helpful-describe-button
'action #'helpful--describe
'symbol nil
'follow-link t
'help-echo "Describe this symbol")
(defun helpful--describe (button)
"Describe the symbol that this BUTTON represents."
(let ((sym (button-get button 'symbol)))
(helpful-symbol sym)))
(define-button-type 'helpful-describe-exactly-button
'action #'helpful--describe-exactly
'symbol nil
'callable-p nil
'follow-link t
'help-echo "Describe this symbol")
(defun helpful--describe-exactly (button)
"Describe the symbol that this BUTTON represents.
This differs from `helpful--describe' because here we know
whether the symbol represents a variable or a callable."
(let ((sym (button-get button 'symbol))
(callable-p (button-get button 'callable-p)))
(if callable-p
(helpful-callable sym)
(helpful-variable sym))))
(define-button-type 'helpful-info-button
'action #'helpful--info
'info-node nil
'follow-link t
'help-echo "View this Info node")
(defun helpful--info (button)
"Describe the symbol that this BUTTON represents."
(info (button-get button 'info-node)))
(define-button-type 'helpful-shortdoc-button
'action #'helpful--shortdoc
'info-node nil
'follow-link t
'help-echo "View this Shortdoc group")
(defun helpful--shortdoc (button)
"Describe the symbol that this BUTTON represents."
(shortdoc-display-group (button-get button 'shortdoc-group)
(button-get button 'symbol)))
(defun helpful--split-first-line (docstring)
"If the first line is a standalone sentence, ensure we have a
blank line afterwards."
(let* ((lines (s-lines docstring))
(first-line (-first-item lines))
(second-line (when (> (length lines) 1) (nth 1 lines))))
(if (and (s-ends-with-p "." first-line)
(stringp second-line)
(not (equal second-line "")))
(s-join "\n"
(-cons* first-line "" (cdr lines)))
docstring)))
(defun helpful--propertize-sym-ref (sym-name before-txt after-txt)
"Given a symbol name from a docstring, convert to a button (if
bound) or else highlight."
(let* ((sym (intern sym-name)))
(cond
;; Highlight keywords.
((s-matches-p
(rx ":"
symbol-start
(+? (or (syntax word) (syntax symbol)))
symbol-end)
sym-name)
(propertize sym-name
'face 'font-lock-builtin-face))
((and (boundp sym) (s-ends-with-p "variable " before-txt))
(helpful--button
sym-name
'helpful-describe-exactly-button
'symbol sym
'callable-p nil))
((and (fboundp sym) (or
(s-starts-with-p " command" after-txt)
(s-ends-with-p "command " before-txt)
(s-ends-with-p "function " before-txt)))
(helpful--button
sym-name
'helpful-describe-exactly-button
'symbol sym
'callable-p t))
;; Only create a link if this is a symbol that is bound as a
;; variable or callable.
((or (boundp sym) (fboundp sym))
(helpful--button
sym-name
'helpful-describe-button
'symbol sym))
;; If this is already a button, don't modify it.
((get-text-property 0 'button sym-name)
sym-name)
;; Highlight the quoted string.
(t
(propertize sym-name
'face 'font-lock-constant-face)))))
(defun helpful--propertize-info (docstring)
"Convert info references in DOCSTRING to buttons."
(replace-regexp-in-string
;; Replace all text that looks like a link to an Info page.
(rx (seq (group
bow
(any "Ii")
"nfo"
(one-or-more whitespace))
(group
(or "node" "anchor")
(one-or-more whitespace))
(any "'`‘")
(group
(one-or-more
(not (any "'’"))))
(any "'’")))
(lambda (it)
;; info-name matches "[Ii]nfo ".
;; space matches "node " or "anchor ".
;; info-node has the form "(cl)Loop Facility".
(let ((info-name (match-string 1 it))
(space (match-string 2 it))
(info-node (match-string 3 it)))
;; If the docstring doesn't specify a manual, assume the Emacs manual.
(save-match-data
(unless (string-match "^([^)]+)" info-node)
(setq info-node (concat "(emacs)" info-node))))
(concat
info-name
space
(helpful--button
info-node
'helpful-info-button
'info-node info-node))))
docstring
t t))
(defun helpful--keymap-keys (keymap)
"Return all the keys and commands in KEYMAP.
Flattens nested keymaps and follows remapped commands.
Returns a list of pairs (KEYCODES COMMAND), where KEYCODES is a
vector suitable for `key-description', and COMMAND is a smbol."
(cond
;; Prefix keys.
((and
(symbolp keymap)
(fboundp keymap)
;; Prefix keys use a keymap in the function slot of a symbol.
(keymapp (symbol-function keymap)))
(helpful--keymap-keys (symbol-function keymap)))
;; Other symbols or compiled functions mean we've reached a leaf,
;; so this is a command we can call.
((or
(symbolp keymap)
(functionp keymap)
;; Strings or vectors mean a keyboard macro.
(stringp keymap)
(vectorp keymap))
`(([] ,keymap)))
((stringp (car keymap))
(helpful--keymap-keys (cdr keymap)))
;; Otherwise, recurse on the keys at this level of the keymap.
(t
(let (result)
(dolist (item (cdr keymap))
(cond
((and (consp item)
(eq (car item) 'menu-bar))
;; Skip menu bar items.
nil)
;; Sparse keymaps are lists.
((consp item)
(-let [(keycode . value) item]
(-each (helpful--keymap-keys value)
(-lambda ((keycodes command))
(push (list (vconcat (vector keycode) keycodes) command)
result)))))
;; Dense keymaps are char-tables.
((char-table-p item)
(map-char-table
(lambda (keycode value)
(-each (helpful--keymap-keys value)
(-lambda ((keycodes command))
(push (list (vconcat (vector keycode) keycodes) command)
result))))
item))))
;; For every command `new-func' mapped to a command `orig-func', show `new-func' with
;; the key sequence for `orig-func'.
(setq result
(-map-when
(-lambda ((keycodes _))
(and (> (length keycodes) 1)
(eq (elt keycodes 0) 'remap)))
(-lambda ((keycodes command))
(list
(where-is-internal (elt keycodes 1) global-map t)
command))
result))
;; Preserve the original order of the keymap.
(nreverse result)))))
(defun helpful--format-hook (hook-val)
"Given a list value assigned to a hook, format it with links to functions."
(let ((lines
(--map
(if (and (symbolp it) (fboundp it))
(helpful--button
(symbol-name it)
'helpful-describe-exactly-button
'symbol it
'callable-p t)
(helpful--syntax-highlight (helpful--pretty-print it)))
hook-val)))
(format "(%s)"
(s-join "\n " lines))))
;; TODO: unlike `substitute-command-keys', this shows keybindings
;; which are currently shadowed (e.g. a global minor mode map).
(defun helpful--format-keymap (keymap)
"Format KEYMAP."
(let* ((keys-and-commands (helpful--keymap-keys keymap))
;; Convert keycodes [27 i] to "C-M-i".
(keys (-map #'-first-item keys-and-commands))
;; Add padding so all our strings are the same length.
(formatted-keys (-map #'key-description keys))
(max-formatted-length (-max (cons 0 (-map #'length formatted-keys))))
(aligned-keys (--map (s-pad-right (1+ max-formatted-length)
" " it)
formatted-keys))
;; Format commands as buttons.
(commands (-map (-lambda ((_ command)) command)
keys-and-commands))
(formatted-commands
(--map
(cond
((symbolp it)
(helpful--button
(symbol-name it)
'helpful-describe-button
'symbol it))
((or (stringp it) (vectorp it))
"Keyboard Macro")
(t
"#<anonymous-function>"))
commands))
;; Build lines for display.
(lines
(-map (-lambda ((key . command)) (format "%s %s" key command))
(-zip-pair aligned-keys formatted-commands))))
;; The flattened keymap will have normal bindings first, and
;; inherited bindings last. Sort so that we group by prefix.
(s-join "\n" (-sort #'string< lines))))
(defun helpful--format-commands (str keymap)
"Replace all the \\[ references in STR with buttons."
(replace-regexp-in-string
;; Text of the form \\[foo-command]
(rx "\\[" (group (+ (not (in "]")))) "]")
(lambda (it)
(let* ((button-face (if (>= emacs-major-version 28) 'help-key-binding 'button))
(symbol-name (match-string 1 it))
(symbol (intern symbol-name))
(key (where-is-internal symbol keymap t))
(key-description
(if key
(key-description key)
(format "M-x %s" symbol-name))))
(helpful--button
key-description
'helpful-describe-exactly-button
'symbol symbol
'callable-p t
'face button-face)))
str
t
t))