-
Notifications
You must be signed in to change notification settings - Fork 0
/
doctest-mode.el
2062 lines (1851 loc) · 83.4 KB
/
doctest-mode.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
;;; doctest-mode.el --- Major mode for editing Python doctest files
;; Copyright (C) 2004-2007 Edward Loper
;; Author: Edward Loper
;; Maintainer: edloper@alum.mit.edu
;; Created: Aug 2004
;; Keywords: python doctest unittest test docstring
(defconst doctest-version "0.5 alpha"
"`doctest-mode' version number.")
;; This software is provided as-is, without express or implied
;; warranty. Permission to use, copy, modify, distribute or sell this
;; software, without fee, for any purpose and by any individual or
;; organization, is hereby granted, provided that the above copyright
;; notice and this paragraph appear in all copies.
;; This is a major mode for editing text files that contain Python
;; doctest examples. Doctest is a testing framework for Python that
;; emulates an interactive session, and checks the result of each
;; command. For more information, see the Python library reference:
;; <http://docs.python.org/lib/module-doctest.html>
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Table of Contents
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 1. Customization: use-editable variables to customize
;; doctest-mode.
;;
;; 2. Fonts: defines new font-lock faces.
;;
;; 3. Constants: various consts (mainly regexps) used by the rest
;; of the code.
;;
;; 4. Syntax Highlighting: defines variables and functions used by
;; font-lock-mode to perform syntax highlighting.
;;
;; 5. Source code editing & indentation: commands used to
;; automatically indent, dedent, & handle prompts.
;;
;; 6. Code Execution: commands used to start doctest processes,
;; and handle their output.
;;
;; 7. Markers: functions used to insert markers at the start of
;; doctest examples. These are used to keep track of the
;; correspondence between examples in the source buffer and
;; results in the output buffer.
;;
;; 8. Navigation: commands used to navigate between failed examples.
;;
;; 9. Replace Output: command used to replace a doctest example's
;; expected output with its actual output.
;;
;; 10. Helper functions: various helper functions used by the rest
;; of the code.
;;
;; 11. Emacs compatibility functions: defines compatible versions of
;; functions that are defined for some versions of emacs but not
;; others.
;;
;; 12. Doctest Results Mode: defines doctest-results-mode, which is
;; used for the output generated by doctest.
;;
;; 13. Doctest Mode: defines doctest-mode itself.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Customizable Constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defgroup doctest nil
"Support for the Python doctest framework"
:group 'languages
:prefix "doctest-")
(defcustom doctest-default-margin 4
"The default pre-prompt margin for doctest examples."
:type 'integer
:group 'doctest)
(defcustom doctest-avoid-trailing-whitespace t
"If true, then delete trailing whitespace when inserting a newline."
:type 'boolean
:group 'doctest)
(defcustom doctest-temp-directory
(let ((ok '(lambda (x)
(and x
(setq x (expand-file-name x)) ; always true
(file-directory-p x)
(file-writable-p x)
x))))
(or (funcall ok (getenv "TMPDIR"))
(funcall ok "/usr/tmp")
(funcall ok "/tmp")
(funcall ok "/var/tmp")
(funcall ok ".")
(error (concat "Couldn't find a usable temp directory -- "
"set `doctest-temp-directory'"))))
"Directory used for temporary files created when running doctest.
By default, the first directory from this list that exists and that you
can write into: the value (if any) of the environment variable TMPDIR,
/usr/tmp, /tmp, /var/tmp, or the current directory."
:type 'string
:group 'doctest)
(defcustom doctest-hide-example-source nil
"If true, then don't display the example source code for each
failure in the results buffer."
:type 'boolean
:group 'doctest)
(defcustom doctest-python-command "python"
"Shell command used to start the python interpreter"
:type 'string
:group 'doctest)
(defcustom doctest-results-buffer-name "*doctest-output (%N)*"
"The name of the buffer used to store the output of the doctest
command. This name can contain the following special sequences:
%n -- replaced by the doctest buffer's name.
%N -- replaced by the doctest buffer's name, with '.doctest'
stripped off.
%f -- replaced by the doctest buffer's filename."
:type 'string
:group 'doctest)
(defcustom doctest-optionflags '()
"Option flags for doctest"
:group 'doctest
:type '(repeat (choice (const :tag "Select an option..." "")
(const :tag "Normalize whitespace"
"NORMALIZE_WHITESPACE")
(const :tag "Ellipsis"
"ELLIPSIS")
(const :tag "Don't accept True for 1"
"DONT_ACCEPT_TRUE_FOR_1")
(const :tag "Don't accept <BLANKLINE>"
"DONT_ACCEPT_BLANKLINE")
(const :tag "Ignore Exception detail"
"IGNORE_EXCEPTION_DETAIL")
(const :tag "Report only first failure"
"REPORT_ONLY_FIRST_FAILURE")
)))
(defcustom doctest-async t
"If true, then doctest will be run asynchronously."
:type 'boolean
:group 'doctest)
(defcustom doctest-trim-exceptions t
"If true, then any exceptions inserted by doctest-replace-output
will have the stack trace lines trimmed."
:type 'boolean
:group 'doctest)
(defcustom doctest-highlight-strings t
"If true, then highlight strings. If you find that doctest-mode
is responding slowly when you type, turning this off might help."
:type 'boolean
:group 'doctest)
(defcustom doctest-follow-output t
"If true, then when doctest is run asynchronously, the output buffer
will scroll to display its output as it is generated. If false, then
the output buffer not scroll."
:type 'boolean
:group 'doctest)
(defvar doctest-mode-hook nil
"Hook called by `doctest-mode'.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Fonts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defface doctest-prompt-face
'((((class color) (background dark))
(:foreground "#68f"))
(t (:foreground "#226")))
"Face for Python prompts in doctest examples."
:group 'doctest)
(defface doctest-output-face
'((((class color) (background dark))
(:foreground "#afd"))
(t (:foreground "#262")))
"Face for the output of doctest examples."
:group 'doctest)
(defface doctest-output-marker-face
'((((class color) (background dark))
(:foreground "#0f0"))
(t (:foreground "#080")))
"Face for markers in the output of doctest examples."
:group 'doctest)
(defface doctest-output-traceback-face
'((((class color) (background dark))
(:foreground "#f88"))
(t (:foreground "#622")))
"Face for traceback headers in the output of doctest examples."
:group 'doctest)
(defface doctest-results-divider-face
'((((class color) (background dark))
(:foreground "#08f"))
(t (:foreground "#00f")))
"Face for dividers in the doctest results window."
:group 'doctest)
(defface doctest-results-loc-face
'((((class color) (background dark))
(:foreground "#0f8"))
(t (:foreground "#084")))
"Face for location headers in the doctest results window."
:group 'doctest)
(defface doctest-results-header-face
'((((class color) (background dark))
(:foreground "#8ff"))
(t (:foreground "#088")))
"Face for sub-headers in the doctest results window."
:group 'doctest)
(defface doctest-results-selection-face
'((((class color) (background dark))
(:foreground "#ff0" :background "#008"))
(t (:background "#088" :foreground "#fff")))
"Face for selected failure's location header in the results window."
:group 'doctest)
(defface doctest-selection-face
'((((class color) (background dark))
(:foreground "#ff0" :background "#00f" :bold t))
(t (:foreground "#f00")))
"Face for selected example's prompt"
:group 'doctest)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defconst doctest-prompt-re
"^\\(?:\\([ \t]*\\)\\(>>> ?\\|[.][.][.] ?\\)\\([ \t]*\\)\\)"
"Regular expression for doctest prompts. It defines three groups:
the pre-prompt margin; the prompt; and the post-prompt indentation.")
(defconst doctest-open-block-re
"[^\n]+:[ \t]*\\(#.*\\)?$"
"Regular expression for a line that opens a block")
(defconst doctest-close-block-re
"\\(return\\|raise\\|break\\|continue\\|pass\\)\\b"
"Regular expression for a line that closes a block")
(defconst doctest-example-source-re
"^Failed example:\n\\(\n\\| [^\n]*\n\\)+"
"Regular expression for example source in doctest's output.")
(defconst doctest-results-divider-re
"^\\([*]\\{60,\\}\\)$"
"Regular expression for example dividers in doctest's output.")
(defconst doctest-py24-results-loc-re
"^File \"[^\"]+\", line \\([0-9]+\\), in [^\n]+"
"Regular expression for example location markers in doctest's output.")
(defconst doctest-py21-results-loc-re
"^from line #\\([0-9]+\\) of [^\n]*"
"Regular expression for example location markers in doctest's output,
when the output was generated by an old version of doctest.")
(defconst doctest-results-header-re
"^\\([^ \n\t].+:\\|Expected nothing\\|Got nothing\\)$"
"Regular expression for example headers in doctest's output.")
(defconst doctest-traceback-header-re
"^[ \t]*Traceback (\\(most recent call last\\|innermost last\\)):"
"Regular expression for Python traceback headers.")
(defconst doctest-py21-results-re
"^from line #"
"Regular expression used to test which version of doctest was used.")
;; nb: There's a bug in Python's traceback.print_exception function
;; which causes SyntaxError exceptions to be displayed incorrectly;
;; which prevents this regexp from matching. But there shouldn't be
;; too many people testing for SyntaxErrors, so I won't worry about
;; it.
(defconst doctest-traceback-re
(let ((nonprompt
;; This matches any non-blank line that doesn't start with
;; a prompt (... or >>>).
(concat
"\\(?:[.][.][^.\n]\\|[>][>][^>\n]\\|"
"[.][^.\n]\\|[>][^>\n]\\|[^.>\n \t]\\)[^\n]*")))
(concat
"^\\(\\([ \t]*\\)Traceback "
"(\\(?:most recent call last\\|innermost last\\)):\n\\)"
"\\(?:\\2[ \t]+[^ \t\n][^\n]*\n\\)*"
"\\(\\(?:\\2" nonprompt "\n\\)"
"\\(?:\\2[ \t]*" nonprompt "\n\\)*\\)"))
"Regular expression that matches a complete exception traceback.
It contains three groups: group 1 is the header line; group 2 is
the indentation; and group 3 is the exception message.")
(defconst doctest-blankline-re
"^[ \t]*<BLANKLINE>"
"Regular expression that matches blank line markers in doctest
output.")
(defconst doctest-outdent-re
(concat "\\(" (mapconcat 'identity
'("else:"
"except\\(\\s +.*\\)?:"
"finally:"
"elif\\s +.*:")
"\\|")
"\\)")
"Regular expression for a line that should be outdented. Any line
that matches `doctest-outdent-re', but does not follow a line matching
`doctest-no-outdent-re', will be outdented.")
;; It's not clear to me *why* the behavior given by this definition of
;; doctest-no-outdent-re is desirable; but it's basically just copied
;; from python-mode.
(defconst doctest-no-outdent-re
(concat
"\\("
(mapconcat 'identity
(list "try:"
"except\\(\\s +.*\\)?:"
"while\\s +.*:"
"for\\s +.*:"
"if\\s +.*:"
"elif\\s +.*:"
"\\(return\\|raise\\|break\\|continue\\|pass\\)[ \t\n]"
)
"\\|")
"\\)")
"Regular expression matching lines not to outdent after. Any line
that matches `doctest-outdent-re', but does not follow a line matching
`doctest-no-outdent-re', will be outdented.")
(defconst doctest-script
"\
from doctest import *
import sys
if '%m':
import imp
try:
m = imp.load_source('__imported__', '%m')
globs = m.__dict__
except Exception, e:
print ('doctest-mode encountered an error while importing '
'the current buffer:\\n\\n %s' % e)
sys.exit(1)
else:
globs = {}
doc = open('%t').read()
if sys.version_info[:2] >= (2,4):
test = DocTestParser().get_doctest(doc, globs, '%n', '%f', 0)
r = DocTestRunner(optionflags=%l)
r.run(test)
else:
Tester(globs=globs).runstring(doc, '%f')"
;; Docstring:
"Python script used to run doctest.
The following special sequences are defined:
%n -- replaced by the doctest buffer's name.
%f -- replaced by the doctest buffer's filename.
%l -- replaced by the doctest flags string.
%t -- replaced by the name of the tempfile containing the doctests."
)
(defconst doctest-keyword-re
(let* ((kw1 (mapconcat 'identity
'("and" "assert" "break" "class"
"continue" "def" "del" "elif"
"else" "except" "exec" "for"
"from" "global" "if" "import"
"in" "is" "lambda" "not"
"or" "pass" "print" "raise"
"return" "while" "yield"
)
"\\|"))
(kw2 (mapconcat 'identity
'("else:" "except:" "finally:" "try:")
"\\|"))
(kw3 (mapconcat 'identity
'("ArithmeticError" "AssertionError"
"AttributeError" "DeprecationWarning" "EOFError"
"Ellipsis" "EnvironmentError" "Exception" "False"
"FloatingPointError" "FutureWarning" "IOError"
"ImportError" "IndentationError" "IndexError"
"KeyError" "KeyboardInterrupt" "LookupError"
"MemoryError" "NameError" "None" "NotImplemented"
"NotImplementedError" "OSError" "OverflowError"
"OverflowWarning" "PendingDeprecationWarning"
"ReferenceError" "RuntimeError" "RuntimeWarning"
"StandardError" "StopIteration" "SyntaxError"
"SyntaxWarning" "SystemError" "SystemExit"
"TabError" "True" "TypeError" "UnboundLocalError"
"UnicodeDecodeError" "UnicodeEncodeError"
"UnicodeError" "UnicodeTranslateError"
"UserWarning" "ValueError" "Warning"
"ZeroDivisionError" "__debug__"
"__import__" "__name__" "abs" "apply" "basestring"
"bool" "buffer" "callable" "chr" "classmethod"
"cmp" "coerce" "compile" "complex" "copyright"
"delattr" "dict" "dir" "divmod"
"enumerate" "eval" "execfile" "exit" "file"
"filter" "float" "getattr" "globals" "hasattr"
"hash" "hex" "id" "input" "int" "intern"
"isinstance" "issubclass" "iter" "len" "license"
"list" "locals" "long" "map" "max" "min" "object"
"oct" "open" "ord" "pow" "property" "range"
"raw_input" "reduce" "reload" "repr" "round"
"setattr" "slice" "staticmethod" "str" "sum"
"super" "tuple" "type" "unichr" "unicode" "vars"
"xrange" "zip")
"\\|"))
(pseudokw (mapconcat 'identity
'("self" "None" "True" "False" "Ellipsis")
"\\|"))
(string (concat "'\\(?:\\\\[^\n]\\|[^\n']*\\)'" "\\|"
"\"\\(?:\\\\[^\n]\\|[^\n\"]*\\)\""))
(brk "\\(?:[ \t(]\\|$\\)"))
(concat
;; Comments (group 1)
"\\(#.*\\)"
;; Function & Class Definitions (groups 2-3)
"\\|\\b\\(class\\|def\\)"
"[ \t]+\\([a-zA-Z_][a-zA-Z0-9_]*\\)"
;; Builtins preceeded by '.'(group 4)
"\\|[.][\t ]*\\(" kw3 "\\)"
;; Keywords & builtins (group 5)
"\\|\\b\\(" kw1 "\\|" kw2 "\\|"
kw3 "\\|" pseudokw "\\)" brk
;; Decorators (group 6)
"\\|\\(@[a-zA-Z_][a-zA-Z0-9_]*\\)"
))
"A regular expression used for syntax highlighting of Python
source code.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Syntax Highlighting (font-lock mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Define the font-lock keyword table.
(defconst doctest-font-lock-keywords
`(
;; The following pattern colorizes source lines. In particular,
;; it first matches prompts, and then looks for any of the
;; following matches *on the same line* as the prompt. It uses
;; the form:
;;
;; (MATCHER MATCH-HIGHLIGHT
;; (ANCHOR-MATCHER nil nil MATCH-HIGHLIGHT))
;;
;; See the variable documentation for font-lock-keywords for a
;; description of what each of those means.
("^[ \t]*\\(>>>\\|\\.\\.\\.\\)"
(1 'doctest-prompt-face)
(doctest-source-matcher
nil nil
(1 'font-lock-comment-face t t) ; comments
(2 'font-lock-keyword-face t t) ; def/class
(3 'font-lock-type-face t t) ; func/class name
;; group 4 (builtins preceeded by '.') gets no colorization.
(5 'font-lock-keyword-face t t) ; keywords & builtins
(6 'font-lock-preprocessor-face t t) ; decorators
(7 'font-lock-string-face t t) ; strings
))
;; The following pattern colorizes output lines. In particular,
;; it uses doctest-output-line-matcher to check if this is an
;; output line, and if so, it colorizes it, and any special
;; markers it contains.
(doctest-output-line-matcher
(0 'doctest-output-face t)
("\\.\\.\\." (beginning-of-line) (end-of-line)
(0 'doctest-output-marker-face t))
(,doctest-blankline-re (beginning-of-line) (end-of-line)
(0 'doctest-output-marker-face t))
(doctest-traceback-line-matcher (beginning-of-line) (end-of-line)
(0 'doctest-output-traceback-face t))
(,doctest-traceback-header-re (beginning-of-line) (end-of-line)
(0 'doctest-output-traceback-face t))
)
;; A PS1 prompt followed by a non-space is an error.
("^[ \t]*\\(>>>[^ \t\n][^\n]*\\)" (1 'font-lock-warning-face t))
)
"Expressions to highlight in doctest-mode.")
(defconst doctest-results-font-lock-keywords
`((,doctest-results-divider-re
(0 'doctest-results-divider-face))
(,doctest-py24-results-loc-re
(0 'doctest-results-loc-face))
(,doctest-results-header-re
(0 'doctest-results-header-face))
(doctest-results-selection-matcher
(0 'doctest-results-selection-face t)))
"Expressions to highlight in doctest-results-mode.")
(defun doctest-output-line-matcher (limit)
"A `font-lock-keyword' MATCHER that returns t if the current
line is the expected output for a doctest example, and if so,
sets `match-data' so that group 0 spans the current line."
;; The real work is done by doctest-find-output-line.
(when (doctest-find-output-line limit)
;; If we found one, then mark the entire line.
(beginning-of-line)
(re-search-forward "[^\n]*" limit)))
(defun doctest-traceback-line-matcher (limit)
"A `font-lock-keyword' MATCHER that returns t if the current line is
the beginning of a traceback, and if so, sets `match-data' so that
group 0 spans the entire traceback. n.b.: limit is ignored."
(beginning-of-line)
(when (looking-at doctest-traceback-re)
(goto-char (match-end 0))
t))
(defun doctest-source-matcher (limit)
"A `font-lock-keyword' MATCHER that returns t if the current line
contains a Python source expression that should be highlighted
after the point. If so, it sets `match-data' to cover the string
literal. The groups in `match-data' should be interpreted as follows:
Group 1: comments
Group 2: def/class
Group 3: function/class name
Group 4: builtins preceeded by '.'
Group 5: keywords & builtins
Group 6: decorators
Group 7: strings
"
(let ((matchdata nil))
;; First, look for string literals.
(when doctest-highlight-strings
(save-excursion
(when (doctest-string-literal-matcher limit)
(setq matchdata
(list (match-beginning 0) (match-end 0)
nil nil nil nil nil nil nil nil nil nil nil nil
(match-beginning 0) (match-end 0))))))
;; Then, look for other keywords. If they occur before the
;; string literal, then they take precedence.
(save-excursion
(when (and (re-search-forward doctest-keyword-re limit t)
(or (null matchdata)
(< (match-beginning 0) (car matchdata))))
(setq matchdata (match-data))))
(when matchdata
(set-match-data matchdata)
(goto-char (match-end 0))
t)))
(defun doctest-string-literal-matcher (limit &optional debug)
"A `font-lock-keyword' MATCHER that returns t if the current line
contains a string literal starting at or after the point. If so, it
expands `match-data' to cover the string literal. This matcher uses
`doctest-statement-info' to collect information about strings that
continue over multiple lines. It therefore might be a little slow for
very large statements."
(let* ((stmt-info (doctest-statement-info))
(quotes (reverse (nth 5 stmt-info)))
(result nil))
(if debug (doctest-debug "quotes %s" quotes))
(while (and quotes (null result))
(let* ((quote (pop quotes))
(start (car quote))
(end (min limit (or (cdr quote) limit))))
(if debug (doctest-debug "quote %s-%s pt=%s lim=%s"
start end (point) limit))
(when (or (and (<= (point) start) (< start limit))
(and (< start (point)) (< (point) end)))
(setq start (max start (point)))
(set-match-data (list start end))
(if debug (doctest-debug "marking string %s" (match-data)))
(goto-char end)
(setq result t))))
result))
(defun doctest-results-selection-matcher (limit)
"Matches from `doctest-selected-failure' to the end of the
line. This is used to highlight the currently selected failure."
(when (and doctest-selected-failure
(<= (point) doctest-selected-failure)
(< doctest-selected-failure limit))
(goto-char doctest-selected-failure)
(re-search-forward "[^\n]+" limit)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Source code editing & indentation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun doctest-indent-source-line (&optional dedent-only)
"Re-indent the current line, as doctest source code. I.e., add a
prompt to the current line if it doesn't have one, and re-indent the
source code (to the right of the prompt). If `dedent-only' is true,
then don't increase the indentation level any."
(interactive "*")
(let ((indent-end nil))
(save-excursion
(beginning-of-line)
(let ((new-indent (doctest-current-source-line-indentation dedent-only))
(new-margin (doctest-current-source-line-margin))
(line-had-prompt (looking-at doctest-prompt-re)))
;; Delete the old prompt (if any).
(when line-had-prompt
(goto-char (match-beginning 2))
(delete-char (- (match-end 2) (match-beginning 2))))
;; Delete the old indentation.
(delete-backward-char (skip-chars-forward " \t"))
;; If it's a continuation line, or a new PS1 prompt,
;; then copy the margin.
(when (or new-indent (not line-had-prompt))
(beginning-of-line)
(delete-backward-char (skip-chars-forward " \t"))
(insert-char ?\ new-margin))
;; Add the new prompt.
(insert-string (if new-indent "... " ">>> "))
;; Add the new indentation
(if new-indent (insert-char ?\ new-indent))
(setq indent-end (point))))
;; If we're left of the indentation end, then move up to the
;; indentation end.
(if (< (point) indent-end) (goto-char indent-end))))
(defun doctest-current-source-line-indentation (&optional dedent-only)
"Return the post-prompt indent to use for this line. This is an
integer for a continuation lines, and nil for non-continuation lines."
(save-excursion
;; Examine the previous doctest line (if present).
(let* ((prev-stmt-info (doctest-prev-statement-info))
(prev-stmt-indent (nth 0 prev-stmt-info))
(continuation-indent (nth 1 prev-stmt-info))
(prev-stmt-opens-block (nth 2 prev-stmt-info))
(prev-stmt-closes-block (nth 3 prev-stmt-info))
(prev-stmt-blocks-outdent (nth 4 prev-stmt-info))
)
;; Examine this doctest line.
(let* ((curr-line-indent 0)
(curr-line-outdented nil))
(beginning-of-line)
(when (looking-at doctest-prompt-re)
(setq curr-line-indent (- (match-end 3) (match-beginning 3)))
(goto-char (match-end 3)))
(setq curr-line-outdented (and (looking-at doctest-outdent-re)
(not prev-stmt-blocks-outdent)))
;; Compute the overall indent.
(let ((indent (or continuation-indent
(+ prev-stmt-indent
(if curr-line-outdented -4 0)
(if prev-stmt-opens-block 4 0)
(if prev-stmt-closes-block -4 0)))))
;; If dedent-only is true, then make sure we don't indent.
(when dedent-only
(setq indent (min indent curr-line-indent)))
;; If indent=0 and we're not outdented, then set indent to
;; nil (to signify the start of a new source example).
(when (and (= indent 0)
(not (or curr-line-outdented continuation-indent)))
(setq indent nil))
;; Return the indentation.
indent)))))
(defun doctest-prev-statement-info (&optional debug)
(save-excursion
(forward-line -1)
(doctest-statement-info debug)))
(defun doctest-statement-info (&optional debug)
"Collect info about the previous statement, and return it as a list:
(INDENT, CONTINUATION, OPENS-BLOCK, CLOSES-BLOCK, BLOCKS-OUTDENT,
QUOTES)
INDENT -- The indentation of the previous statement (after the prompt)
CONTINUATION -- If the previous statement is incomplete (e.g., has an
open paren or quote), then this is the appropriate indentation
level; otherwise, it's nil.
OPENS-BLOCK -- True if the previous statement opens a Python control
block.
CLOSES-BLOCK -- True if the previous statement closes a Python control
block.
BLOCKS-OUTDENT -- True if the previous statement should 'block the
next statement from being considered an outdent.
QUOTES -- A list of (START . END) pairs for all quotation strings.
"
(save-excursion
(end-of-line)
(let ((end (point)))
(while (and (doctest-on-source-line-p "...") (= (forward-line -1) 0)))
(cond
;; If there's no previous >>> line, then give up.
((not (doctest-on-source-line-p ">>>"))
'(0 nil nil nil nil))
;; If there is a previous statement, walk through the source
;; code, checking for operators that may be of interest.
(t
(beginning-of-line)
(let* ((quote-mark nil) (nesting 0) (indent-stack '())
(stmt-indent 0)
(stmt-opens-block nil)
(stmt-closes-block nil)
(stmt-blocks-outdent nil)
(quotes '())
(elt-re (concat "\\\\[^\n]\\|"
"(\\|)\\|\\[\\|\\]\\|{\\|}\\|"
"\"\"\"\\|\'\'\'\\|\"\\|\'\\|"
"#[^\n]*\\|" doctest-prompt-re)))
(while (re-search-forward elt-re end t)
(let* ((elt (match-string 0))
(elt-first-char (substring elt 0 1)))
(if debug (doctest-debug "Debug: %s" elt))
(cond
;; Close quote -- set quote-mark back to nil. The
;; second case is for cases like: ' '''
(quote-mark
(cond
((equal quote-mark elt)
(setq quote-mark nil)
(setcdr (car quotes) (point)))
((equal quote-mark elt-first-char)
(setq quote-mark nil)
(setcdr (car quotes) (point))
(backward-char 2))))
;; Prompt -- check if we're starting a new stmt. If so,
;; then collect various info about it.
((string-match doctest-prompt-re elt)
(when (and (null quote-mark) (= nesting 0))
(let ((indent (- (match-end 3) (match-end 2))))
(unless (looking-at "[ \t]*\n")
(setq stmt-indent indent)
(setq stmt-opens-block
(looking-at doctest-open-block-re))
(setq stmt-closes-block
(looking-at doctest-close-block-re))
(setq stmt-blocks-outdent
(looking-at doctest-no-outdent-re))))))
;; Open paren -- increment nesting, and update indent-stack.
((string-match "(\\|\\[\\|{" elt-first-char)
(let ((elt-pos (point))
(at-eol (looking-at "[ \t]*\n"))
(indent 0))
(save-excursion
(re-search-backward doctest-prompt-re)
(if at-eol
(setq indent (+ 4 (- (match-end 3) (match-end 2))))
(setq indent (- elt-pos (match-end 2))))
(push indent indent-stack)))
(setq nesting (+ nesting 1)))
;; Close paren -- decrement nesting, and pop indent-stack.
((string-match ")\\|\\]\\|}" elt-first-char)
(setq indent-stack (cdr indent-stack))
(setq nesting (max 0 (- nesting 1))))
;; Open quote -- set quote-mark.
((string-match "\"\\|\'" elt-first-char)
(push (cons (- (point) (length elt)) nil) quotes)
(setq quote-mark elt)))))
(let* ((continuation-indent
(cond
(quote-mark 0)
((> nesting 0) (if (null indent-stack) 0 (car indent-stack)))
(t nil)))
(result
(list stmt-indent continuation-indent
stmt-opens-block stmt-closes-block
stmt-blocks-outdent quotes)))
(if debug (doctest-debug "Debug: %s" result))
result)))))))
(defun doctest-current-source-line-margin ()
"Return the pre-prompt margin to use for this source line. This is
copied from the most recent source line, or set to
`doctest-default-margin' if there are no preceeding source lines."
(save-excursion
(save-restriction
(when (doctest-in-mmm-docstring-overlay)
(doctest-narrow-to-mmm-overlay))
(beginning-of-line)
(forward-line -1)
(while (and (not (doctest-on-source-line-p))
(re-search-backward doctest-prompt-re nil t))))
(cond ((looking-at doctest-prompt-re)
(- (match-end 1) (match-beginning 1)))
((doctest-in-mmm-docstring-overlay)
(doctest-default-margin-in-mmm-docstring-overlay))
(t
doctest-default-margin))))
(defun doctest-electric-backspace ()
"Delete the preceeding character, level of indentation, or
prompt.
If point is at the leftmost column, delete the preceding newline.
Otherwise, if point is at the first non-whitespace character
following an indented source line's prompt, then reduce the
indentation to the next multiple of 4; and update the source line's
prompt, when necessary.
Otherwise, if point is at the first non-whitespace character
following an unindented source line's prompt, then remove the
prompt (converting the line to an output line or text line).
Otherwise, if point is at the first non-whitespace character of a
line, the delete the line's indentation.
Otherwise, delete the preceeding character.
"
(interactive "*")
(cond
;; Beginning of line: delete preceeding newline.
((bolp) (backward-delete-char 1))
;; First non-ws char following prompt: dedent or remove prompt.
((and (looking-at "[^ \t\n]\\|$") (doctest-looking-back doctest-prompt-re))
(let* ((prompt-beg (match-beginning 2))
(indent-beg (match-beginning 3)) (indent-end (match-end 3))
(old-indent (- indent-end indent-beg))
(new-indent (* (/ (- old-indent 1) 4) 4)))
(cond
;; Indented source line: dedent it.
((> old-indent 0)
(goto-char indent-beg)
(delete-region indent-beg indent-end)
(insert-char ?\ new-indent)
;; Change prompt to PS1, when appropriate.
(when (and (= new-indent 0) (not (looking-at doctest-outdent-re)))
(delete-backward-char 4)
(insert-string ">>> ")))
;; Non-indented source line: remove prompt.
(t
(goto-char indent-end)
(delete-region prompt-beg indent-end)))))
;; First non-ws char of a line: delete all indentation.
((and (looking-at "[^ \n\t]\\|$") (doctest-looking-back "^[ \t]+"))
(delete-region (match-beginning 0) (match-end 0)))
;; Otherwise: delete a character.
(t
(backward-delete-char 1))))
(defun doctest-newline-and-indent ()
"Insert a newline, and indent the new line appropriately.
If the current line is a source line containing a bare prompt,
then clear the current line, and insert a newline.
Otherwise, if the current line is a source line, then insert a
newline, and add an appropriately indented prompt to the new
line.
Otherwise, if the current line is an output line, then insert a
newline and indent the new line to match the example's margin.
Otherwise, insert a newline.
If `doctest-avoid-trailing-whitespace' is true, then clear any
whitespace to the left of the point before inserting a newline.
"
(interactive "*")
;; If we're avoiding trailing spaces, then delete WS before point.
(if doctest-avoid-trailing-whitespace
(delete-char (- (skip-chars-backward " \t"))))
(cond
;; If we're on an empty prompt, delete it.
((doctest-on-empty-source-line-p)
(delete-region (match-beginning 0) (match-end 0))
(insert-char ?\n 1))
;; If we're on a doctest line, add a new prompt.
((doctest-on-source-line-p)
(insert-char ?\n 1)
(doctest-indent-source-line))
;; If we're in doctest output, indent to the margin.
((doctest-on-output-line-p)
(insert-char ?\n 1)
(insert-char ?\ (doctest-current-source-line-margin)))
;; Otherwise, just add a newline.
(t (insert-char ?\n 1))))
(defun doctest-electric-colon ()
"Insert a colon, and dedent the line when appropriate."
(interactive "*")
(insert-char ?: 1)
(when (doctest-on-source-line-p)
(doctest-indent-source-line t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code Execution
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun doctest-execute ()
"Run doctest on the current buffer, or on the current docstring
if the point is inside an `mmm-mode' `doctest-docstring' region.
Display the results in the *doctest-output* buffer."
(interactive)
(doctest-execute-region (point-min) (point-max) nil t))
(defun doctest-execute-with-diff ()
"Run doctest on the current buffer, or on the current docstring
if the point is inside an `mmm-mode' `doctest-docstring' region.
Display the results in the *doctest-output* buffer, using diff format."
(interactive)
(doctest-execute-region (point-min) (point-max) t t))
(defun doctest-execute-buffer-with-diff ()
"Run doctest on the current buffer, and display the results in the
*doctest-output* buffer, using the diff format."
(interactive)
(doctest-execute-region (point-min) (point-max) t nil))
(defun doctest-execute-buffer ()
"Run doctest on the current buffer, and display the results in the
*doctest-output* buffer."
(interactive)
(doctest-execute-region (point-min) (point-max) nil nil))
(defun doctest-execute-region (start end &optional diff
check-for-mmm-docstring-overlay)
"Run doctest on the current buffer, and display the results in the
*doctest-output* buffer."
(interactive "r")
;; If it's already running, give the user a chance to restart it.
(when (doctest-process-live-p doctest-async-process)
(when (y-or-n-p "Doctest is already running. Restart it? ")
(doctest-cancel-async-process)
(message "Killing doctest...")))
(cond
((and doctest-async (doctest-process-live-p doctest-async-process))
(message "Can't run two doctest processes at once!"))
(t
(let* ((results-buf-name (doctest-results-buffer-name))
(in-docstring (and check-for-mmm-docstring-overlay
(doctest-in-mmm-docstring-overlay)))
(temp (doctest-temp-name)) (dir doctest-temp-directory)
(input-file (expand-file-name (concat temp ".py") dir))
(globs-file (when in-docstring
(expand-file-name (concat temp "-globs.py") dir)))
(cur-buf (current-buffer))
(in-buf (get-buffer-create "*doctest-input*"))
(script (doctest-script input-file globs-file diff)))
;; If we're in a docstring, narrow start & end.
(when in-docstring
(let ((bounds (doctest-mmm-overlay-bounds)))
(setq start (max start (car bounds))
end (min end (cdr bounds)))))
;; Write the doctests to a file.
(save-excursion
(goto-char (min start end))
(let ((lineno (doctest-line-number)))
(set-buffer in-buf)
;; Add blank lines, to keep line numbers the same:
(dotimes (n (- lineno 1)) (insert-string "\n"))
;; Add the selected region
(insert-buffer-substring cur-buf start end)
;; Write it to a file
(write-file input-file)))
;; If requested, write the buffer to a file for use as globs.
(when globs-file
(let ((cur-buf-start (point-min)) (cur-buf-end (point-max)))
(save-excursion
(set-buffer in-buf)
(delete-region (point-min) (point-max))
(insert-buffer-substring cur-buf cur-buf-start cur-buf-end)
(write-file globs-file))))
;; Dispose of in-buf (we're done with it now.
(kill-buffer in-buf)
;; Prepare the results buffer. Clear it, if it contains
;; anything, and set its mode.
(setq doctest-results-buffer (get-buffer-create results-buf-name))
(save-excursion
(set-buffer doctest-results-buffer)
(toggle-read-only 0)
(delete-region (point-min) (point-max))
(doctest-results-mode)
(setq doctest-source-buffer cur-buf)
)
;; Add markers to examples, and record what line number each one
;; starts at. That way, if the input buffer is edited, we can
;; still find corresponding examples in the output.
(doctest-mark-examples)