-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathink-mode.el
1248 lines (1091 loc) · 43.9 KB
/
ink-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
;;; ink-mode.el --- Major mode for writing interactive fiction in Ink -*- lexical-binding: t -*-
;; Copyright (C) 2016-2020 Erik Sjöstrand, Damien Picard, and
;; ink-mode contributors (see the commit log for details).
;; Author: Erik Sjöstrand
;; Damien Picard
;; Maintainer: Damien Picard
;; URL: https://github.com/Kungsgeten/ink-mode
;; Version: 0.3.2
;; Keywords: languages, wp, hypermedia
;; Package-Requires: ((emacs "26.1"))
;; 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 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:
;; `ink-mode' provides syntax highlighting and indentation for
;; the Ink scripting language, developed by Inkle Studios.
;; Other features are: divert autocompletion and links to headers and
;; labels; an `ink-play' command to playtest your story from Emacs
;; (bound to C-c C-c by default); an outline similar to org-mode's;
;; error reporting using flymake; a collection of YASnippet snippets.
;;; Code:
(require 'rx)
(require 'comint)
(require 'thingatpt)
(require 'outline)
(require 'subr-x)
(require 'easymenu)
(require 'flymake)
(require 'seq)
(defgroup ink nil
"Major mode for writing interactive fiction in Ink."
:link '(url-link :tag "GitHub" "https://github.com/Kungsgeten/ink-mode")
:link '(info-link "(WritingWithInk)")
:group 'languages)
(defgroup ink-faces nil
"Faces for the Ink interactive fiction language."
:link '(custom-group-link "ink")
:group 'ink
:group 'faces)
(defvar ink-mode-hook nil)
(defvar ink-mode-map
(let ((map (make-keymap)))
(define-key map (kbd "C-c C-c") 'ink-play)
(define-key map (kbd "C-c C-p") 'ink-play-knot)
(define-key map (kbd "C-c C-o") 'ink-follow-link-at-point)
(define-key map (kbd "C-c C-h") 'ink-display-manual)
;; Visibility cycling
(define-key map (kbd "TAB") 'ink-cycle)
(define-key map (kbd "<S-iso-lefttab>") 'ink-shifttab)
(define-key map (kbd "<S-tab>") 'ink-shifttab)
(define-key map (kbd "<backtab>") 'ink-shifttab)
map)
"Keymap for ink major mode.")
(defvar ink-mode-mouse-map
(let ((map (make-sparse-keymap)))
(define-key map [follow-link] 'mouse-face)
(define-key map [mouse-2] #'ink-follow-link-at-point)
map)
"Keymap for following links with mouse.")
(easy-menu-define ink-mode-menu ink-mode-map
"Menu for `ink-mode'."
'("Ink"
["Run game from start" ink-play]
["Run game from knot or stitch" ink-play-knot]
"---"
["Follow link at point" ink-follow-link-at-point]))
(defconst ink-mode-syntax-table
(let ((st (make-syntax-table)))
;; // starts a comment
(modify-syntax-entry ?/ ". 124b" st)
(modify-syntax-entry ?* ". 23" st)
;; End of line ends a comment
(modify-syntax-entry ?\n "> b" st)
(modify-syntax-entry ?\" ". " st)
(modify-syntax-entry ?\( ". " st)
(modify-syntax-entry ?\) ". " st)
(modify-syntax-entry ?\[ ". " st)
(modify-syntax-entry ?\] ". " st)
(modify-syntax-entry ?0 ". " st)
(modify-syntax-entry ?1 ". " st)
(modify-syntax-entry ?2 ". " st)
(modify-syntax-entry ?3 ". " st)
(modify-syntax-entry ?4 ". " st)
(modify-syntax-entry ?5 ". " st)
(modify-syntax-entry ?6 ". " st)
(modify-syntax-entry ?7 ". " st)
(modify-syntax-entry ?8 ". " st)
(modify-syntax-entry ?9 ". " st)
st)
"Syntax table used while in `ink-mode'.")
;;; Regular Expressions
(defconst ink-regex-header
"^\\s-*\\(?1:=+\\)\\s-*\\(?2:\\(?:function\\)?\\)\\s-*\\(?3:[[:alnum:]_]+\\)\\s-*\\(?4:\\(?:([^)]*)\\)?\\)\\s-*\\(?5:=*\\)"
"Regexp identifying Ink headers.
Group 1 matches the equal signs preceding the title.
Group 2 matches the function keyword.
Group 3 matches the header title.
Group 4 matches the function arguments.
Group 5 matches the optional equal signs following the header.")
(defconst ink-regex-label
"^\\(?:\\s-*[*+\\-]\\)+\\s-*\\(?1:(\\(?2:[[:alnum:]_]+\\))\\)"
"Regexp identifying Ink labels.
Group 1 matches a label including parentheses.
Group 2 matches a label excluding parentheses.")
(defconst ink-regex-divert
"\\(?1:->\\|<-\\)\\(?3:\\s-*\\)\\(?2:[[:alnum:]_.]*\\)"
"Regexp identifying Ink diverts.
Group 1 matches an left or right arrow.
Group 2 matches a link text.
Group 3 matches the spaces inbetween.")
(defconst ink-regex-include
"^\\s-*\\(?1:INCLUDE\\)\\s-*\\(?2:.*?\\)\\s-*$"
"Regexp identifying Ink includes.
Group 1 matches an INCLUDE keyword
Group 2 matches a link text")
(defconst ink-regex-comment
;; "^\\s-*\\(TODO\\|//\\|.*?/\\*\\|.*?\\*/\\)"
"^\\s-*\\(TODO\\|//\\)"
"Regexp identifying Ink comments.")
;;; Link following
(defun ink-follow-link-at-point ()
"Open the current link.
Determine whether it leads to a header or to an included file by
matching regexps."
(interactive "@")
(let ((found-link nil))
(cond ((thing-at-point-looking-at ink-regex-divert)
(ink-follow-header-or-label-link)
(setq found-link t))
((thing-at-point-looking-at ink-regex-include)
(ink-follow-file-link)
(setq found-link t))
((not found-link)
(user-error "No links")))))
(defun ink-find-header (title)
"Find a header (knot or stitch) matching TITLE in the buffer.
Return its position."
(let (position)
(save-excursion
(goto-char (point-min))
(while (and (not position)
(re-search-forward ink-regex-header (buffer-end 1) t))
(when (string-equal (ink-get-knot-name) title)
(setq position (point))))
position)))
(defun ink-find-label (title-list &optional start end)
"Find a label matching TITLE-LIST in the buffer.
Return its position.
TITLE-LIST consists of one to three elements, giving four possibilities:
\(label stitch knot\)
\(label stitch\)
\(label knot\)
\(label\)
START and END can specify the range in which
to search."
;; reverse title list to get label first
(setq title-list (reverse title-list))
(let (position
(start (if start start (point-min)))
(end (if end end (point-max))))
(save-excursion
(goto-char start)
(while (and (not position)
(re-search-forward ink-regex-label end t))
;; do different checks depending on title list length
(cond ((and (not position)
(= 3 (length title-list))
;; three elements: compare all three
(equal (ink-get-label-name) title-list))
(setq position (point)))
((and (not position)
(= 2 (length title-list))
;; two elements: compare first and (second or third) elements
(and
(equal (nth 0 (ink-get-label-name)) (nth 0 title-list))
(or
(equal (nth 1 (ink-get-label-name)) (nth 1 title-list))
(equal (nth 2 (ink-get-label-name)) (nth 1 title-list)))))
(setq position (point)))
((and (not position)
(= 1 (length title-list))
;; one element: compare only label
(equal (nth 0 (ink-get-label-name)) (nth 0 title-list)))
(setq position (point))))))
position))
(defun ink-follow-header-or-label-link ()
"Go to the header or label matching the link at point."
(let (position
title title-list
knot-name
stitch-start stitch-end
knot-start knot-end)
(font-lock-ensure)
(setq title (string-trim-right (match-string-no-properties 2) "\\."))
(if (string-match-p "^\\(\\END\\|DONE\\)" title)
(user-error "%s is not a real link" title)
(progn
(save-excursion
;; get knot and stitch names and start / end positions
(when (ignore-errors (outline-back-to-heading t))
(if (= (ink-outline-level) 2)
;; In stitch
(progn
(setq stitch-start (point))
(save-excursion
(ink-end-of-subtree t)
(setq stitch-end (point)))
(ignore-errors (outline-up-heading 1))
(setq knot-name (ink-get-knot-name))
(setq knot-start (point))
(save-excursion
(ink-end-of-subtree t)
(setq knot-end (point))))
;; In knot
(setq knot-name (ink-get-knot-name))
(setq knot-start (point))
(save-excursion
(ink-end-of-subtree t)
(setq knot-end (point))))))
;; Look for header
(setq position (ink-find-header title))
;; Look for stitch with that name in current knot:
(if (not position)
(setq position (ink-find-header (concat knot-name "." title))))
;; Look for labels:
(setq title-list (split-string title "\\."))
(unless position
(cond ((or (= 1 (length title-list))
(= 2 (length title-list)))
;; Title has one or two element;
;; look in order in stitch, knot and outside
(if (and (not position)
stitch-start)
(setq position
(ink-find-label title-list stitch-start stitch-end)))
(if (and (not position)
knot-start)
(setq position
(ink-find-label title-list knot-start knot-end)))
(if (not position)
(setq position
(ink-find-label title-list))))
;; Title has three elements;
;; look as knot.stitch.label in whole buffer
((and (not position)
(= 3 (length title-list)))
(setq position (ink-find-label title-list)))))
(if position (progn
(message "Jumping to %s" title)
(goto-char position)
(ignore-errors (outline-show-subtree)))
(user-error "Link `%s' not found. Is it in another file?" title))))))
(defun ink-follow-file-link ()
"Find file matching the link at point."
(let (file-name)
(setq file-name (match-string-no-properties 2))
(setq file-name (concat (file-name-directory
(buffer-file-name))
file-name))
(find-file file-name)
(message "Visiting %s" file-name)))
;;; Faces
(defface ink-shadow-face
'((t (:inherit shadow)))
"Face for Ink headers and glue."
:group 'ink-faces)
(defface ink-knot-face
'((t (:inherit font-lock-function-name-face)))
"Face for Ink knots: == * ==."
:group 'ink-faces)
(defface ink-stitch-face
'((t (:inherit 'ink-knot-face)))
"Face for Ink stitches: = *."
:group 'ink-faces)
(defface ink-link-face
'((t (:inherit link)))
"Face for Ink divert links."
:group 'ink-faces)
(defface ink-arrow-face
'((t (:inherit font-lock-builtin-face)))
"Face for Ink divert arrows."
:group 'ink-faces)
(defface ink-tag-face
'((t (:inherit font-lock-doc-face)))
"Face for Ink tags: ()."
:group 'ink-faces)
(defface ink-bracket-face
'((t (:inherit italic)))
"Face for Ink brackets: []."
:group 'ink-faces)
;;; Highlighting
(defun ink-fontify-diverts (last)
"Add text properties to next divert from point to LAST."
(when (re-search-forward ink-regex-divert last t)
(ink-fontify-links
;; Arrow part
(list 'face 'ink-arrow-face
'rear-nonsticky t
'font-lock-multiline t))
t))
(defun ink-fontify-includes (last)
"Add text properties to next include from point to LAST."
(when (re-search-forward ink-regex-include last t)
(ink-fontify-links
;; INCLUDE part
(list 'face 'font-lock-keyword-face
'rear-nonsticky t
'font-lock-multiline t))
t))
(defun ink-fontify-links (pre-part)
"Add text properties to link.
Use the PRE-PART list as properties to fontify the part preceding
the link, whether it be an arrow for diverts, or the INCLUDE
keyword."
(let* ((link-start (match-beginning 2))
(link-end (match-end 2))
(title (string-trim-right (match-string-no-properties 2) "\\."))
;; Link part (without face)
(lp (list 'keymap ink-mode-mouse-map
'mouse-face 'highlight
'font-lock-multiline t
'help-echo (if title title ""))))
(when (match-end 1)
(add-text-properties (match-beginning 1) (match-end 1) pre-part))
(when link-start
(add-text-properties link-start link-end lp)
(add-face-text-property link-start link-end
'ink-link-face 'append))
t))
(defvar ink-font-lock-keywords
`(
;; TODO-style comments
("^\\s-*\\(TODO.*\\)" . font-lock-comment-face)
;; Knots
(,ink-regex-header
(1 'ink-shadow-face)
(2 font-lock-keyword-face)
(3 'ink-knot-face)
(4 font-lock-variable-name-face)
(5 'ink-shadow-face))
;; Diverts, threads and tunnels
(ink-fontify-diverts)
;; Labels
(,ink-regex-label 1 font-lock-variable-name-face)
;; Choices
("^\\s-*\\([*+]\\s-*\\)+" . font-lock-type-face)
;; Gathers
("^\\s-*\\(\\(?:\\s-*-\\)+\\)\\(?:[^>]\\|$\\)" 1 font-lock-type-face)
;; Keywords at beginning of line
("^\\s-*\\(VAR\\|CONST\\|LIST\\)" . font-lock-keyword-face)
;; Includes
(ink-fontify-includes)
;; Vars, constants and lists
("^\\s-*\\(?:VAR\\|CONST\\|LIST\\)\\s-+\\([[:word:]_]+\\)" 1
font-lock-variable-name-face)
;; Conditions
("{.*?\\(:\\).*?}" 1 font-lock-constant-face)
;; Alternatives
("\\(?:^\\|[^\\\\]\\)\\([{|}]+\\)" 1 font-lock-constant-face)
;; Code lines
("\\(^\\s-*~\\)" (0 font-lock-type-face)
("\\_<\\(?:return\\|temp\\|ref\\)\\_>" nil nil (0 font-lock-keyword-face))
("\\(\".*?\"\\)" nil nil (0 font-lock-string-face))
("\\([[:word:]_]+\\)(.*)" nil nil (1 font-lock-function-name-face))
("\\_<\\(?1:.*?\\)\\s-*\\(?2:=\\)\\_>" nil nil
(1 font-lock-variable-name-face))
("\\_<\\(SEED_RANDOM\\|RANDOM\\|CHOICE_COUNT\\|TURNS\\|TURNS_SINCE\\|INT\\|FLOOR\\|FLOAT\\)\\_>" nil nil (0 font-lock-builtin-face)))
;; Tags
("\\(?:^\\|[^\\\\]\\)\\(#.*\\)$" 1 'ink-tag-face)
;; Glue
("\\(^\\s-*<>\\|<>\\s-*$\\)" . 'ink-shadow-face)
;; Brackets
("^\\(?:\\s-*[*+]\\).*\\(\\[.*\\]\\)" 1 'ink-bracket-face)))
;;; Indentation
(defcustom ink-indent-choices-with-spaces nil
"If non-nil, force using spaces between choices and gathers.
You'd get something like:
- I looked at Monsieur Fogg
* ... and I could contain myself no longer.
'What is the purpose of our journey, Monsieur?'
'A wager,' he replied.
* * 'A wager!'[] I returned.
He nodded.
* * * 'But surely that is foolishness!'
Otherwise, use the setting of `indent-tabs-mode', which may give:
- I looked at Monsieur Fogg
* ... and I could contain myself no longer.
'What is the purpose of our journey, Monsieur?'
'A wager,' he replied.
* * 'A wager!'[] I returned.
He nodded.
* * * 'But surely that is foolishness!'"
:group 'ink
:type 'boolean)
(defun ink-indent-line ()
"Indent current line of Ink code."
(save-excursion
(indent-line-to (max 0 (ink-calculate-indentation)))
(ink-indent-choices))
(let* ((actual-indentation
(save-excursion
(goto-char (line-beginning-position))
(search-forward-regexp "[^[:space:]]")
(- (point) 1)))
(follow-indentation-p
;; Check if point is within indentation.
(>= actual-indentation
(point))))
(when follow-indentation-p (back-to-indentation))))
(defun ink-count-choices ()
"Return number of choices or gathers in line."
(interactive)
(let ((choices 0))
(save-excursion
(beginning-of-line)
(re-search-forward
"\\(?1:\\(?:[*+-]\\s-*\\)+?\\)\\s-*\\(?:->\\)?\\s-*\\([^*+-]\\|$\\)"
(line-end-position) t)
(if (match-beginning 0)
(setq choices (count-matches "\\([*+-]\\)" (line-beginning-position) (match-end 1)))))
choices))
(defun ink-get-tab-string ()
"Get the string to insert as tabs depending on `indent-tabs-mode'."
(if indent-tabs-mode
"\t"
(make-string (max 0 (- tab-width 1)) ? )))
(defun ink-indent-choices ()
"Indent choices and gathers: add indentations between symbols."
(interactive)
(save-excursion
(beginning-of-line)
(when (and (looking-at "^\\s-*[*+\\-]")
;; (not (looking-at "^\\s-*-.*:")) ;; Conditions
(not (looking-at ".*\\*/"))) ;; Comments
(let (found-not-choice found-divert replacement-string)
(while (and (not found-not-choice)
(re-search-forward
"\\(?1:[*+\\-]\\)\\(?2:\\s-*\\)"
(line-end-position) t))
(save-match-data
(cond ((looking-at ">")
(setq found-divert t)
(setq found-not-choice t))
((looking-at "[^*+\\-]")
(setq found-not-choice t))))
(unless found-divert
(setq replacement-string
(cond (ink-indent-choices-with-spaces
(if found-not-choice
(ink-get-tab-string)
" "))
(indent-tabs-mode
"\t")
(t
(ink-get-tab-string))))
;; Compare string to be replaced with replacement, and do
;; it only if different. This avoid making changes which
;; disable auto-complete.
(when (not (equal replacement-string (match-string-no-properties 2)))
(replace-match replacement-string nil nil nil 2))))))))
(defun ink-calculate-bracket-difference ()
"Count the difference between opening and closing brackets."
(-
(count-matches
"\\({\\)"
(line-beginning-position)
(line-end-position))
(count-matches
"\\(}\\)"
(line-beginning-position)
(line-end-position))))
(defun ink-calculate-indentation ()
"Find indent level at point."
(let (indented
(bracket-difference 0)
(indentation-list (list))
(indentation 0)
start-pos on-last-line
comment-start comment-end)
(save-excursion
;; Indent comments as the first non-comment line below
(beginning-of-line)
;; Don't indent empty lines
(if (looking-at "^\\s-*$")
(setq indented t))
(while (and (not indented)
(or
(looking-at "^\\s-*$")
(looking-at "^\\s-*//")
(looking-at "^\\s-*TODO")))
(forward-line 1)
(re-search-forward "^\\s-*[^[:space:]]+.*$")
(beginning-of-line))
(setq start-pos (point))
;; Multiline comments
(save-excursion
(cond ((looking-at ".*\\(?1:/\\*\\)")
;; Comment starting at line
(setq comment-start (line-beginning-position))
(setq start-pos (line-beginning-position)))
((re-search-backward "/\\*" nil t)
;; Comment before
(setq comment-start (line-beginning-position))))
(when (and comment-start
(re-search-forward "\\*/" nil t))
;; Find end of comment
(setq comment-end (point))
(when (and (> comment-end start-pos)
(= comment-start
(progn (re-search-backward "/\\*" nil t)
(line-beginning-position))))
;; Inside comment: the end we found is not that of a
;; later comment. Advance to next non-empty, non-comment
;; line.
(goto-char comment-end)
(forward-line 1)
(while (or (looking-at "^\\s-*$")
(looking-at "^\\s-*//")
(looking-at "^\\s-*TODO"))
(forward-line 1)
(re-search-forward "^\\s-*[^[:space:]]+.*$")
(beginning-of-line))
(setq start-pos (point)))))
;; Go back to header or buffer start
(or
(ignore-errors (outline-back-to-heading t))
(goto-char (point-min)))
(while (and (not indented)
(not on-last-line))
;; Go forward one line until exit condition: on starting line
(when (= (point)
start-pos)
(setq on-last-line t))
;; Calculate the difference betweeen the numbers of opening
;; and closing brackets
(when (looking-at ".*[{}]")
(setq bracket-difference (ink-calculate-bracket-difference)))
(cond
;; At header; only useful for multiline comments,
;; which look down
((looking-at ink-regex-header)
(setq indentation-list '()))
;; Conditions inside brackets - ...:
((and (looking-at "^\\s-*-.*:\\s-*")
(or
(seq-contains indentation-list 'bracket)
(seq-contains indentation-list 'bracket-cond)))
;; Pop until previous bracket
(while (not (or (eq 'bracket (nth 0 indentation-list))
(eq 'bracket-cond (nth 0 indentation-list))))
(pop indentation-list))
(cond
;; If inside bracket with condition, keep same indentation
((eq 'bracket-cond (nth 0 indentation-list))
(pop indentation-list)
(unless on-last-line
(push 'bracket-cond indentation-list)))
;; If inside simple bracket, add one indentation
((eq 'bracket (nth 0 indentation-list))
(unless on-last-line
(push 'cond indentation-list)))))
;; Choices * +
((looking-at "^\\s-*[*+]")
;; (not (looking-at ".*?\\*/"))) ;; comments
(while (or (eq 'choice (nth 0 indentation-list))
(eq 'gather (nth 0 indentation-list)))
(pop indentation-list))
(setq indentation-list (nconc (make-list (ink-count-choices) 'choice)
indentation-list)))
;; Gathers -
((and (looking-at "^\\s-*\\(-[^>]\\|-$\\)")
(not (looking-at ".*?\\*/"))) ;; comments
(while (or (eq 'choice (nth 0 indentation-list))
(eq 'gather (nth 0 indentation-list)))
(pop indentation-list))
(setq indentation-list (nconc (make-list (ink-count-choices) 'gather)
indentation-list)))
;; Increase indent on opening bracket with condition
((and
(> bracket-difference 0)
(looking-at "^\\s-*{\\s-*.*?:"))
(unless on-last-line
(push 'bracket-cond indentation-list)))
;; Decrease indent on closing bracket
((and (looking-at ".*[{}]")
(< bracket-difference 0))
(while (and (not (or (eq 'bracket (nth 0 indentation-list))
(eq 'bracket-cond (nth 0 indentation-list))))
(> (length indentation-list) 0))
(pop indentation-list))
(when (> (length indentation-list) 0)
(pop indentation-list))))
;; Increase indent on opening bracket
(when (and
(looking-at ".*{")
(> bracket-difference 0)
(not (looking-at "^\\s-*{.*?:")) ;; already addressed
(not on-last-line))
(push 'bracket indentation-list))
(forward-line 1))
;; Add up indentations from list
(goto-char start-pos)
;; Reverse list, because each level may depend on the
;; previous ones
(setq indentation-list (reverse indentation-list))
(let (element value)
;; pop each level in turn, then accumulate the indentation
;; depending on element type
(while (> (length indentation-list) 0)
(setq element (pop indentation-list))
(cond
((eq element 'choice)
(if (looking-at "^\\s-*[*+]") ;; on choice line
(setq value tab-width)
(if ink-indent-choices-with-spaces
(setq value (ink-calculate-choice-indentation
element indentation-list indentation))
(setq value (* 2 tab-width)))))
((eq element 'gather)
(if (looking-at "^\\s-*\\(-[^>]\\|-$\\)") ;; on gather line
(setq value tab-width)
(if ink-indent-choices-with-spaces
(setq value (ink-calculate-choice-indentation
element indentation-list indentation))
(setq value (* 2 tab-width))))
;; Cancel last gather, to unindent once
(when (not (eq element
(nth 0 indentation-list)))
(setq value (- value tab-width))))
((eq element 'bracket)
(setq value tab-width))
((eq element 'bracket-cond)
(setq value tab-width))
((eq element 'cond)
(setq value tab-width)))
(when value
(setq indentation (+ indentation value))))))
indentation))
(defun ink-calculate-choice-indentation (element indentation-list indentation)
"Get the number of columns to indent choices and gathers.
This depends on previous indentation, and settings. ELEMENT is
the current element in the INDENTATION-LIST for the lign to
indent. INDENTATION is the current sum."
(let (value)
(if ink-indent-choices-with-spaces
(if (eq element (nth 0 indentation-list))
;; all but last elements
(setq value (+ 2 tab-width))
;; last element
(if indent-tabs-mode
;; find the closest tab, depending on current
;; indentation
(setq value
(- (* tab-width
(ceiling (/ (+ 2.0 tab-width
indentation)
tab-width)))
indentation))
(setq value (* 2 tab-width))))
(setq value (* 2 tab-width)))
value))
;;; Ink-play
(defvar ink-play-mode-hook nil)
(defvar ink-play-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-c C-h") 'ink-display-manual)
(define-key map (kbd "C-c C-c") 'ink-play)
(define-key map (kbd "C-c C-p") 'ink-play-knot)
map)
"Keymap for ink-play mode.
`ink-play' and `ink-play-knot' in this mode will re-run the last
ink-play and ink-play-knot commands in the same buffer.")
(define-derived-mode ink-play-mode comint-mode "Ink-Play"
"Major mode for `ink-play'.
Derives from comint-mode, adds a few ink bindings.")
(defcustom ink-inklecate-path (executable-find "inklecate")
"The path to the Inklecate executable."
:group 'ink
:type '(file))
(defvar-local ink-comint-do-filter nil)
(defun ink-play-knot ()
"Play the current ink buffer from the knot or stitch at point."
(interactive)
(ink-play t))
;; last file-name and knot to support replaying
(setq ink-last-played-file-name nil)
(setq ink-last-played-knot nil)
(defun ink-play (&optional go-to-knot)
"Play the current ink buffer.
If the GO-TO-KNOT optional argument is non-nil, start at the knot
or stitch at point. In that case we issue \"-> knot.stitch\" to
the process, and suppress the beginning output using the comint
output filter."
(interactive "P")
(let* (;; check this ahead of (set-buffer)
(in-ink-play-buffer (equal major-mode 'ink-play-mode))
;; if our buffer isn't referring to a real file (eg. *Ink*),
;; use the cached last-file-name
(file-name (if in-ink-play-buffer ink-last-played-file-name
(buffer-file-name)))
;; needs to run before set-buffer call
(knot-name (when go-to-knot
(if in-ink-play-buffer
;; return the last played knot
ink-last-played-knot
;; return a knot name if found, nil otherwise
(let ((kn (ink-get-knot-name)))
(unless (string-empty-p kn) kn)))))
(ink-buffer
(if (or
;; our process is already running, so this ink-play
;; should just execute inklecate
(comint-check-proc "*Ink*")
;; OR we are already in the *Ink* buffer, but the process
;; has finished, so kick it off again
in-ink-play-buffer)
(progn
(comint-exec "*Ink*" "Ink" ink-inklecate-path
nil `("-p" ,file-name))
"*Ink*")
;; no *Ink* buffer yet, need to create it
(progn
(let ((new-buffer
(make-comint "Ink" ink-inklecate-path nil
"-p" (buffer-file-name))))
(set-buffer new-buffer)
(ink-play-mode)
new-buffer)))))
;; update the last ink-file/knot attempted (to support 'replaying')
(setq ink-last-played-file-name file-name)
;; conditionally update to preserve knot-name across 'full' replays,
;; which would otherwise clear it
(when knot-name
(setq ink-last-played-knot knot-name))
;; only switch window if we're not already focused
(unless in-ink-play-buffer
(switch-to-buffer-other-window ink-buffer))
(comint-clear-buffer)
(if (and go-to-knot knot-name)
(progn
(setq ink-comint-do-filter t)
(message (concat "Running " knot-name "..."))
(comint-send-string (get-process "Ink")
(concat "-> " knot-name "\n"))
(comint-delete-output)
(comint-clear-buffer))
(setq ink-comint-do-filter nil))
(message "Running Ink...")))
(defun ink-filter-output-line (line)
"Filter single line of text from Inklecate's output.
The filter is active only on starting play. It outputs all
errors, warnings and infos appearing in LINE, and discards the
rest."
(let ((result ""))
(if ink-comint-do-filter
(cond ((string-match-p "^\\(ERROR:\\|WARNING:\\|TODO\\)" line)
(setq result (concat line "\n")))
((string-match-p "\\?>" line)
(setq result (concat (substring line 3) "\n"))
(setq ink-comint-do-filter nil))
((not result)
(setq result "")))
(setq result (concat line "\n")))
result))
(defun ink-comint-filter-output (output)
"Comint output filter for `ink-play'.
This whole filter is just so that the first output of comint
doesn't print before the first important line when starting
directly at a knot... OUTPUT is the output to be filtered."
(if ink-comint-do-filter
(setq output (mapconcat #'ink-filter-output-line (split-string output "\n") "")))
output)
(add-hook 'comint-preoutput-filter-functions #'ink-comint-filter-output)
;;; Error checking with flymake
(defvar-local ink--flymake-proc nil)
(defun ink-flymake (report-fn &rest _args)
"Ink backend for Flymake.
Creates temporary files and passes their names as arguments to
`ink-inklecate-path' (which see). The output of this command is
analyzed for error and warning messages."
(unless (executable-find ink-inklecate-path)
(error "Cannot find a suitable checker"))
;; If a live process launched in an earlier check was found, that
;; process is killed. When that process's sentinel eventually runs,
;; it will notice its obsoletion, since it have since reset
;; `ink-flymake-proc' to a different value
;;
(when (process-live-p ink--flymake-proc)
(kill-process ink--flymake-proc))
;; From ‘flymake-proc-init-create-temp-buffer-copy’.
;;
(let* ((source (current-buffer))
(temp-file (flymake-proc-init-create-temp-buffer-copy
'flymake-proc-create-temp-inplace))
(local-file (file-relative-name
temp-file
(file-name-directory buffer-file-name)))
(json-file (concat local-file ".json")))
;; Save the current buffer, the narrowing restriction, remove any
;; narrowing restriction.
;;
(save-restriction
(widen)
;; Reset the `ink--flymake-proc' process to a new process
;; calling the ink tool.
;;
(setq ink--flymake-proc
(make-process
:name "ink-flymake" :noquery t :connection-type 'pipe
;; Make output go to a temporary buffer.
;;
:buffer (generate-new-buffer " *ink-flymake*")
:command (list ink-inklecate-path "-o" json-file local-file)
:sentinel
(lambda (proc _event)
;; Check that the process has indeed exited, as it might
;; be simply suspended.
;;
(when (eq 'exit (process-status proc))
(unwind-protect
;; Only proceed if `proc' is the same as
;; `ink--flymake-proc', which indicates that
;; `proc' is not an obsolete process.
;;
(if (with-current-buffer source (eq proc ink--flymake-proc))
(with-current-buffer (process-buffer proc)
(goto-char (point-min))
;; Parse the output buffer for diagnostic's
;; messages and locations, collect them in a list
;; of objects, and call `report-fn'.
;;
(cl-loop
while (search-forward-regexp
"^\\(.*?\\): '.*?' line \\([0-9]+\\): \\(.*\\)$"
nil t)
for msg = (match-string 3)
for (beg . end) = (flymake-diag-region
source
(string-to-number (match-string 2)))
for type = (cond
((string-match "ERROR" (match-string 1)) :error)
((string-match "WARNING" (match-string 1)) :warning)
((string-match "TODO" (match-string 1)) :note)
(t :warning))
collect (flymake-make-diagnostic source
beg
end
type
msg)
into diags
finally (funcall report-fn diags)))
;; Cleanup the temporary buffer used to hold the
;; check's output.
;;
(kill-buffer (process-buffer proc)))
;; Delete temporary files
(flymake-proc--safe-delete-file local-file)
(flymake-proc--safe-delete-file json-file))))))
;; Send the buffer contents to the process's stdin, followed by
;; an EOF.
;;
(process-send-region ink--flymake-proc (point-min) (point-max))
(process-send-eof ink--flymake-proc))))
;;; Outline
;; Outline functions were derived from markdown-mode.el, in turn
;; originally derived from from org.el.