-
Notifications
You must be signed in to change notification settings - Fork 62
/
fsharp-mode-structure.el
1793 lines (1571 loc) · 71.6 KB
/
fsharp-mode-structure.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
;;; fsharp-mode-indent.el --- Stucture Definition, Mark, and Motion for F#
;; Copyright (C) 2010 Laurent Le Brun
;; Author: 2010-2011 Laurent Le Brun <[email protected]>
;; Maintainer: Jürgen Hötzel <[email protected]>
;; Keywords: languages
;; This file is not part of GNU Emacs.
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This file 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 GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
;;; Commentary:
;; This module defines variables and functions related to the structure of F#
;; code, and motion around and through that code. SMIE is used to set certain
;; default configurations. In particular, `smie' expects to set
;; `forward-sexp-function' and `indent-line-function', the latter of which we
;; currently override.
;;
;; SMIE configs by m00nlight Wang <[email protected]>, 2015
;; Last major update by Ross Donaldson <@gastove>, 2019
;;; Code:
(require 'comint)
(require 'custom)
(require 'compile)
(require 'smie)
;;-------------------------- Customization Variables --------------------------;;
(defcustom fsharp-tab-always-indent t
"*Non-nil means TAB in Fsharp mode should always reindent the current line,
regardless of where in the line point is when the TAB command is used."
:type 'boolean
:group 'fsharp)
(defcustom fsharp-indent-offset 4
"*Amount of offset per level of indentation.
`\\[fsharp-guess-indent-offset]' can usually guess a good value when
you're editing someone else's Fsharp code."
:type 'integer
:group 'fsharp)
(defalias 'fsharp-indent-level 'fsharp-indent-offset
"Backwards-compatibility alias. `fsharp-indent-level' was
configuring the same thing as `fsharp-indent-offset', but less
clearly and in a different file, and free from update by
functions like offset-guessing.")
(defcustom fsharp-continuation-offset 4
"*Additional amount of offset to give for some continuation lines.
Continuation lines are those that immediately follow a backslash
terminated line. Only those continuation lines for a block opening
statement are given this extra offset."
:type 'integer
:group 'fsharp)
(defcustom fsharp-conservative-indentation-after-bracket nil
"Indent by fsharp-continuation-offset also after an opening bracket.
The default indentation depth on a new line after an opening
bracket is one column further from the opening bracket. Indenting much less is
allowed, because brackets reset the current offside column."
:type 'boolean
:group 'fsharp)
(defcustom fsharp-smart-indentation t
"*Should `fsharp-mode' try to automagically set some indentation variables?
When this variable is non-nil, two things happen when a buffer is set
to `fsharp-mode':
1. `fsharp-indent-offset' is guessed from existing code in the buffer.
Only guessed values between 2 and 8 are considered. If a valid
guess can't be made (perhaps because you are visiting a new
file), then the value in `fsharp-indent-offset' is used.
2. `indent-tabs-mode' is turned off if `fsharp-indent-offset' does not
equal `tab-width' (`indent-tabs-mode' is never turned on by
Fsharp mode). This means that for newly written code, tabs are
only inserted in indentation if one tab is one indentation
level, otherwise only spaces are used.
Note that both these settings occur *after* `fsharp-mode-hook' is run,
so if you want to defeat the automagic configuration, you must also
set `fsharp-smart-indentation' to nil in your `fsharp-mode-hook'."
:type 'boolean
:group 'fsharp)
(defcustom fsharp-honor-comment-indentation t
"*Controls how comment lines influence subsequent indentation.
When nil, all comment lines are skipped for indentation purposes, and
if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
When t, lines that begin with a single `//' are a hint to subsequent
line indentation. If the previous line is such a comment line (as
opposed to one that starts with `fsharp-block-comment-prefix'), then its
indentation is used as a hint for this line's indentation. Lines that
begin with `fsharp-block-comment-prefix' are ignored for indentation
purposes.
When not nil or t, comment lines that begin with a single `//' are used
as indentation hints, unless the comment character is in column zero."
:type '(choice
(const :tag "Skip all comment lines (fast)" nil)
(const :tag "Single // `sets' indentation for next line" t)
(const :tag "Single // `sets' indentation except at column zero"
other)
)
:group 'fsharp)
(defcustom fsharp-backspace-function 'backward-delete-char-untabify
"*Function called by `fsharp-electric-backspace' when deleting backwards."
:type 'function
:group 'fsharp)
(defcustom fsharp-delete-function 'delete-char
"*Function called by `fsharp-electric-delete' when deleting forwards."
:type 'function
:group 'fsharp)
;;--------------------------------- Constants ---------------------------------;;
;; TODO[gastove|2019-10-30] So much:
;; - No SQTQ in F#
;; - No raw strings either
;; - But there *are* verbatim strings that begin with @
;; - And can use \ to escape a newline
;; - But *can* contain newlines
;; It's a good thing this isn't called often, because it is a mess and wrong.
(defconst fsharp-stringlit-re
(concat
;; These fail if backslash-quote ends the string (not worth
;; fixing?). They precede the short versions so that the first two
;; quotes don't look like an empty short string.
;;
;; (maybe raw), long single quoted triple quoted strings (SQTQ),
;; with potential embedded single quotes
"[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
"\\|"
;; (maybe raw), long double quoted triple quoted strings (DQTQ),
;; with potential embedded double quotes
"[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
"\\|"
"[rR]?'\\([^'\n\\]\\|\\\\.\\)*'" ; single-quoted
"\\|" ; or
"[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\"" ; double-quoted
)
"Regular expression matching a Fsharp string literal.")
(defconst fsharp--hanging-operator-re
(concat ".*\\(" (mapconcat 'identity
'("+" "-" "*" "/")
"\\|")
"\\)$")
"Regular expression matching unterminated algebra expressions.")
;; TODO[gastove|2019-10-22] This doesn't match (* long comments *), but it *does* capture.
(defconst fsharp-blank-or-comment-re "[ \t]*\\(//.*\\)?"
"Regular expression matching a blank or comment line.")
(defconst fsharp-outdent-re
(concat "\\(" (mapconcat 'identity
'("else"
"with"
"finally"
"end"
"done"
"elif"
"}")
"\\|")
"\\)")
"Regular expression matching statements to be dedented one level.")
(defconst fsharp-block-closing-keywords-re
"\\(end\\|done\\|raise\\|failwith\\|failwithf\\|rethrow\\|exit\\)"
"Regular expression matching keywords which typically close a block.")
(defconst fsharp-no-outdent-re
(concat
"\\("
(mapconcat 'identity
(list "try"
"while\\s +.*"
"for\\s +.*"
"then"
(concat fsharp-block-closing-keywords-re "[ \t\n]")
)
"\\|")
"\\)")
"Regular expression matching lines not to dedent after.")
(defconst fsharp-block-opening-re
(concat "\\(" (mapconcat 'identity
'("then"
"else"
"with"
"finally"
"class"
"struct"
"=" ; for example: let f x =
"->"
"do"
"try"
"function")
"\\|")
"\\)")
"Regular expression matching expressions which begin a block")
;; TODO: this regexp looks transparently like a python regexp. That means it's almost certainly wrong.
(defvar fsharp-parse-state-re
(concat
"^[ \t]*\\(elif\\|else\\|while\\|def\\|class\\)\\>"
"\\|"
"^[^ /\t\n]"))
(defsubst fsharp-point (position)
"Returns the value of point at certain commonly referenced POSITIONs.
POSITION can be one of the following symbols:
bol -- beginning of line
eol -- end of line
bod -- beginning of def or class
eod -- end of def or class
bob -- beginning of buffer
eob -- end of buffer
boi -- back to indentation
bos -- beginning of statement
This function preserves point and mark."
(save-mark-and-excursion
(cond
((eq position 'bol) (beginning-of-line))
((eq position 'eol) (end-of-line))
((eq position 'bod) (fsharp-beginning-of-def-or-class 'either))
((eq position 'eod) (fsharp-end-of-def-or-class 'either))
((eq position 'bob) (point-min))
((eq position 'eob) (point-max))
((eq position 'boi) (back-to-indentation))
((eq position 'bos) (fsharp-goto-initial-line))
(t (error "Unknown buffer position requested: %s" position)))
(point)))
;;-------------------------------- Predicates --------------------------------;;
(defun fsharp-in-literal-p (&optional lim)
"Return non-nil if point is in a Fsharp literal (a comment or
string). The return value is specifically one of the symbols
\\='comment or \\='string. Optional argument LIM indicates the
beginning of the containing form, i.e. the limit on how far back
to scan."
;; NOTE: Watch out for infinite recursion between this function and
;; `fsharp-point'.
(let* ((lim (or lim (fsharp-point 'bod)))
(state (parse-partial-sexp lim (point))))
(cond
((nth 3 state) 'string)
((nth 4 state) 'comment)
(t nil))))
(defun fsharp-outdent-p ()
"Returns non-nil if the current line should dedent one level."
(save-excursion
(progn (back-to-indentation)
(looking-at fsharp-outdent-re))))
(defun fsharp--indenting-comment-p ()
"Returns non-nil if point is in an indenting comment line, otherwise nil.
Definition: Indenting comment line. A line containing only a
comment, but which is treated like a statement for indentation
calculation purposes. Such lines are only treated specially by
the mode; they are not treated specially by the Fsharp
interpreter.
The first non-blank line following an indenting comment line is
given the same amount of indentation as the indenting comment
line.
All other comment-only lines are ignored for indentation
purposes.
Are we looking at a comment-only line which is *not* an indenting
comment line? If so, we assume that it's been placed at the
desired indentation, so leave it alone. Indenting comment lines
are aligned as statements."
;; TODO[gastove|2019-10-22] this is a bug. The regular expression here matches
;; comments only if there is *no whites space* between the // and the first
;; characters in the comment.
(and (looking-at "[ \t]*//[^ \t\n]")
(fboundp 'forward-comment)
(<= (current-indentation)
(save-excursion
(forward-comment (- (point-max)))
(current-indentation)))))
(defun fsharp--hanging-operator-continuation-line-p ()
"Return t if point is on at least the *second* line of the
buffer, and the previous line matches `fsharp--hanging-operator-re' --
which is to say, it ends in +, -, /, or *."
(save-excursion
(beginning-of-line)
(and
(not (bobp))
;; make sure; since eq test passed, there is a preceding line
(forward-line -1) ; always true -- side effect
;; matches any line, so long as it ends with one of +, -, *, or /
(looking-at fsharp--hanging-operator-re))))
;; TODO[gastove|2019-10-31] This function doesn't do everything it needs to.
;; Currently, it only reports a continuation line if there's a hanging
;; arithmetic operator *or* if we're inside a delimited block (something like {}
;; or []). It _needs_ to also respect symbols that open a new whitespace block
;; -- things like -> at the end of a line, or |> at the beginning of one.
;;
;; The trick is: the other major place where |> and -> lines are considered is
;; in `fsharp-compute-indentation', which... catches "undelimited" blocks as a
;; default case. They aren't _explicitly_ detected.
;;
;; In all, this makes me think we need a cleaner distinction between a
;; "continuation line" and a "relative line" -- that is, a line that continues
;; an ongoing expression (a sequence of items in a list, the completion of an
;; arithmetic expression) and a new block scope opened by a single symbol and
;; terminated with whitespace.
;;
;; We do already have `fsharp-statement-opens-block-p', which we could make much
;; more active use of. However: `fsharp-statement-opens-block-p' calls
;; `fsharp-goto-beyond-final-line', which... relies on
;; `fsharp-continuation-line-p'. So that will need untangling.
(defun fsharp-continuation-line-p ()
"Return t if current line continues a line with a hanging
arithmetic operator *or* is inside a nesting construct (a list,
computation expression, etc)."
(save-excursion
(beginning-of-line)
(or (fsharp--hanging-operator-continuation-line-p)
(fsharp-nesting-level))))
(defun fsharp--previous-line-continuation-line-p ()
"Returns true if previous line is a continuation line"
(save-excursion
(forward-line -1)
(fsharp-continuation-line-p)))
(defun fsharp-statement-opens-block-p ()
"Return t if the current statement opens a block. For instance:
type Shape =
| Square
| Rectangle
or:
let computation = [ this; that ]
|> Array.someCalculation
Point should be at the start of a statement."
(save-excursion
(let ((start (point))
(finish (progn (fsharp-goto-beyond-final-line) (1- (point))))
(searching t)
(answer nil)
state)
(goto-char start)
;; Keep searching until we're finished.
(while searching
(if (re-search-forward fsharp-block-opening-re finish t)
(if (eq (point) finish)
;; sure looks like it opens a block -- but it might
;; be in a comment
(progn
(setq searching nil) ; search is done either way
(setq state (parse-partial-sexp start
(match-beginning 0)))
(setq answer (not (nth 4 state)))))
;; search failed: couldn't find a reason to believe we're opening a block.
(setq searching nil)))
answer)))
;; TODO[@gastove|2019-10-22]: the list of keywords this function claims to catch
;; does not at all match the keywords in the regexp it wraps.
(defun fsharp-statement-closes-block-p ()
"Return t iff the current statement closes a block.
I.e., if the line starts with `return', `raise', `break', `continue',
and `pass'. This doesn't catch embedded statements."
(let ((here (point)))
(fsharp-goto-initial-line)
(back-to-indentation)
(prog1
(looking-at (concat fsharp-block-closing-keywords-re "\\>"))
(goto-char here))))
;;---------------------------- Electric Keystrokes ----------------------------;;
(defun fsharp-electric-colon (arg)
"Insert a colon.
In certain cases the line is dedented appropriately. If a numeric
argument ARG is provided, that many colons are inserted
non-electrically. Electric behavior is inhibited inside a string or
comment."
(interactive "*P")
(self-insert-command (prefix-numeric-value arg))
;; are we in a string or comment?
(if (save-excursion
(let ((pps (parse-partial-sexp (save-excursion
(fsharp-beginning-of-def-or-class)
(point))
(point))))
(not (or (nth 3 pps) (nth 4 pps)))))
(save-excursion
(let ((here (point))
(outdent 0)
(indent (fsharp-compute-indentation t)))
(if (and (not arg)
(fsharp-outdent-p)
(= indent (save-excursion
(fsharp-next-statement -1)
(fsharp-compute-indentation t)))
)
(setq outdent fsharp-indent-offset))
;; Don't indent, only dedent. This assumes that any lines
;; that are already dedented relative to
;; fsharp-compute-indentation were put there on purpose. It's
;; highly annoying to have `:' indent for you. Use TAB, C-c
;; C-l or C-c C-r to adjust. TBD: Is there a better way to
;; determine this???
(if (< (current-indentation) indent) nil
(goto-char here)
(beginning-of-line)
(delete-horizontal-space)
(indent-to (- indent outdent)))))))
;; Electric deletion
(defun fsharp-electric-backspace (arg)
"Delete preceding character or levels of indentation.
Deletion is performed by calling the function in `fsharp-backspace-function'
with a single argument (the number of characters to delete).
If point is at the leftmost column, delete the preceding newline.
Otherwise, if point is at the leftmost non-whitespace character of a
line that is neither a continuation line nor a non-indenting comment
line, or if point is at the end of a blank line, this command reduces
the indentation to match that of the line that opened the current
block of code. The line that opened the block is displayed in the
echo area to help you keep track of where you are. With
\\[universal-argument] dedents that many blocks (but not past column
zero).
Otherwise the preceding character is deleted, converting a tab to
spaces if needed so that only a single column position is deleted.
\\[universal-argument] specifies how many characters to delete;
default is 1.
When used programmatically, argument ARG specifies the number of
blocks to dedent, or the number of characters to delete, as indicated
above."
(interactive "*p")
(if (or (/= (current-indentation) (current-column))
(bolp)
(fsharp-continuation-line-p))
(funcall fsharp-backspace-function arg)
;; else indent the same as the colon line that opened the block
;; force non-blank so fsharp-goto-block-up doesn't ignore it
(insert-char ?* 1)
(backward-char)
(let ((base-indent 0) ; indentation of base line
(base-text "") ; and text of base line
(base-found-p nil))
(save-excursion
(while (< 0 arg)
(condition-case nil ; in case no enclosing block
(progn
(fsharp-goto-block-up 'no-mark)
(setq base-indent (current-indentation)
base-text (fsharp-suck-up-leading-text)
base-found-p t))
(error nil))
(setq arg (1- arg))))
(delete-char 1) ; toss the dummy character
(delete-horizontal-space)
(indent-to base-indent)
(if base-found-p
(message "Closes block: %s" base-text)))))
(defun fsharp-electric-delete (arg)
"Delete preceding or following character or levels of whitespace.
The behavior of this function depends on the variable
`delete-key-deletes-forward'. If this variable is nil (or does not
exist, as in older Emacsen and non-XEmacs versions), then this
function behaves identically to \\[c-electric-backspace].
If `delete-key-deletes-forward' is non-nil and is supported in your
Emacs, then deletion occurs in the forward direction, by calling the
function in `fsharp-delete-function'.
\\[universal-argument] (programmatically, argument ARG) specifies the
number of characters to delete (default is 1)."
(interactive "*p")
(funcall fsharp-delete-function arg))
;; required for pending-del/delsel/delete-selection minor modes
(put 'fsharp-electric-colon 'delete-selection t) ;delsel
(put 'fsharp-electric-colon 'pending-delete t) ;pending-del
(put 'fsharp-electric-backspace 'delete-selection 'supersede) ;delsel
(put 'fsharp-electric-backspace 'pending-delete 'supersede) ;pending-del
(put 'fsharp-electric-delete 'delete-selection 'supersede) ;delsel
(put 'fsharp-electric-delete 'pending-delete 'supersede) ;pending-del
;;-------------------------------- Indentation --------------------------------;;
(defun fsharp-indent-line (&optional arg)
"Fix the indentation of the current line according to Fsharp rules.
With \\[universal-argument] (programmatically, the optional argument
ARG non-nil), ignore dedenting rules for block closing statements
(e.g. return, raise, break, continue, pass)
This function is normally bound to `indent-line-function' so
\\[indent-for-tab-command] will call it."
(interactive "P")
(let* ((ci (current-indentation))
(move-to-indentation-p (<= (current-column) ci))
(need (fsharp-compute-indentation (not arg)))
(cc (current-column)))
;; dedent out a level if previous command was the same unless we're in
;; column 1
(if (and (equal last-command this-command)
(/= cc 0))
(progn
(beginning-of-line)
(delete-horizontal-space)
(indent-to (* (/ (- cc 1) fsharp-indent-offset) fsharp-indent-offset)))
(progn
;; see if we need to dedent
(if (fsharp-outdent-p)
(setq need (- need fsharp-indent-offset)))
(if (or fsharp-tab-always-indent
move-to-indentation-p)
(progn (if (/= ci need)
(save-excursion
(beginning-of-line)
(delete-horizontal-space)
(indent-to need)))
(if move-to-indentation-p (back-to-indentation)))
(insert-tab))))))
;; NOTE[gastove|2019-10-25] An interesting point: this function is *only* ever
;; called if `open-bracket-pos' is non-nil; `open-bracket-pos' is generated by
;; `fsharp-nesting-level', which *only* returns non nil for non-string
;; characters. And yet: we don't just rely on `open-bracket-pos' as we compute
;; indentation, and I'm honestly not sure why.
(defun fsharp--compute-indentation-open-bracket (open-bracket-pos)
"Computes indentation for a line within an open bracket expression."
(save-excursion
(let ((startpos (point))
placeholder)
;; align with first item in list; else a normal
;; indent beyond the line with the open bracket
(goto-char (1+ open-bracket-pos)) ; just beyond bracket
;; NOTE[gastove|2019-10-25] -- consider switching to a forward regexp search
;; with a whitepsace character class.
;; is the first list item on the same line?
(skip-chars-forward " \t")
(if (and (null (memq (following-char) '(?\n ?# ?\\)))
(not fsharp-conservative-indentation-after-bracket))
; yes, so line up with it
(current-column)
;; here follows the else
;; first list item on another line, or doesn't exist yet
;; TODO[gastove|2019-10-25] this needs to skip past whitespace, newlines,
;; *and* comments. I'm not convinced it does.
(forward-line 1)
(while (and (< (point) startpos)
(looking-at "[ \t]*\\(//\\|[\n\\\\]\\)")) ; skip noise
(forward-line 1))
(if (and (< (point) startpos)
(/= startpos
(save-excursion
(goto-char (1+ open-bracket-pos))
(forward-comment (point-max))
(point))))
;; again mimic the first list item
(current-indentation)
;; else they're about to enter the first item
;; NOTE[gastove|2019-10-25] Okay, this is all really hard to follow, but
;; I *think* what's going on here is:
;; - We go to the position of the opening bracket we're trying to compute indentation against.
;; - We set placeholder to point (meaning we set `placeholder' to `open-bracket-pos')
;; - We call a function that claims to go to the first line of a statement
;; - We call a function that I *believe* tries to take us to the opening delimiter of a matched pair
;; - We return the current indentation of *that*, plus indent offset
;; ... holy moly.
(goto-char open-bracket-pos)
(setq placeholder (point))
(fsharp-goto-initial-line)
(fsharp-goto-beginning-of-tqs
(save-excursion (nth 3 (parse-partial-sexp
placeholder (point)))))
(+ (current-indentation) fsharp-indent-offset))))))
(defun fsharp--compute-indentation-continuation-line ()
"Computes the indentation for a line which continues the line
above, but only when the previous line is not itself a continuation line."
(save-excursion
(forward-line -11)
(let ((startpos (point))
(open-bracket-pos (fsharp-nesting-level))
endpos searching found state placeholder)
;; Started on 2nd line in block, so indent more. if base line is an
;; assignment with a start on a RHS, indent to 2 beyond the leftmost "=";
;; else skip first chunk of non-whitespace characters on base line, + 1 more
;; column
(end-of-line)
(setq endpos (point)
searching t)
(back-to-indentation)
(setq startpos (point))
;; look at all "=" from left to right, stopping at first one not nested in a
;; list or string
(while searching
(skip-chars-forward "^=" endpos)
(if (= (point) endpos)
(setq searching nil)
(forward-char 1)
(setq state (parse-partial-sexp startpos (point)))
(if (and (zerop (car state)) ; not in a bracket
(null (nth 3 state))) ; & not in a string
(progn
(setq searching nil) ; done searching in any case
(setq found
(not (or
(eq (following-char) ?=)
(memq (char-after (- (point) 2))
'(?< ?> ?!)))))))))
(if (or (not found) ; not an assignment
(looking-at "[ \t]*\\\\")) ; <=><spaces><backslash>
(progn
(goto-char startpos)
(skip-chars-forward "^ \t\n")))
;; if this is a continuation for a block opening
;; statement, add some extra offset.
(+ (current-column) (if (fsharp-statement-opens-block-p)
fsharp-continuation-offset 0)
1))))
(defun fsharp--compute-indentation-relative-to-previous (honor-block-close-p)
"Indentation based on that of the statement that precedes us;
use the first line of that statement to establish the base, in
case the user forced a non-std indentation for the continuation
lines (if any)"
;; skip back over blank & non-indenting comment lines note:
;; will skip a blank or non-indenting comment line that
;; happens to be a continuation line too. use fast Emacs 19
;; function if it's there.
(save-excursion
(let ((bod (fsharp-point 'bod))
placeholder)
(if (and (eq fsharp-honor-comment-indentation nil)
(fboundp 'forward-comment))
(forward-comment (- (point-max)))
(let ((prefix-re "//[ \t]*")
done)
(while (not done)
(re-search-backward "^[ \t]*\\([^ \t\n]\\|//\\)" nil 'move)
(setq done (or (bobp)
(and (eq fsharp-honor-comment-indentation t)
(save-excursion
(back-to-indentation)
(not (looking-at prefix-re))
))
(and (not (eq fsharp-honor-comment-indentation t))
(save-excursion
(back-to-indentation)
(and (not (looking-at prefix-re))
(or (looking-at "[^/]")
(not (zerop (current-column))))))))))))
;; if we landed inside a string, go to the beginning of that
;; string. this handles triple quoted, multi-line spanning
;; strings.
(fsharp-goto-beginning-of-tqs (nth 3 (parse-partial-sexp bod (point))))
;; now skip backward over continued lines
(setq placeholder (point))
(fsharp-goto-initial-line)
;; we may *now* have landed in a TQS, so find the beginning of
;; this string.
(fsharp-goto-beginning-of-tqs
(save-excursion (nth 3 (parse-partial-sexp
placeholder (point)))))
(+ (current-indentation)
(if (fsharp-statement-opens-block-p)
fsharp-indent-offset
(if (and honor-block-close-p (fsharp-statement-closes-block-p))
(- fsharp-indent-offset)
0))))))
(defun fsharp-newline-and-indent ()
"Strives to act like the Emacs `newline-and-indent'.
This is just `strives to' because correct indentation can't be computed
from scratch for Fsharp code. In general, deletes the whitespace before
point, inserts a newline, and takes an educated guess as to how you want
the new line indented."
(interactive)
(let ((ci (current-indentation)))
(if (< ci (current-column)) ; if point beyond indentation
(newline-and-indent)
;; else try to act like newline-and-indent "normally" acts
(beginning-of-line)
(insert-char ?\n 1)
(move-to-column ci))))
(defun fsharp-compute-indentation (honor-block-close-p)
"Compute Fsharp indentation.
When HONOR-BLOCK-CLOSE-P is non-nil, statements such as `return',
`raise', `break', `continue', and `pass' force one level of
dedenting."
(save-excursion
(beginning-of-line)
(let* ((bod (fsharp-point 'bod))
(pps (parse-partial-sexp bod (point)))
(boipps (parse-partial-sexp bod (fsharp-point 'boi)))
(open-bracket-pos (fsharp-nesting-level)))
(cond
;; Continuation Lines
((fsharp-continuation-line-p)
(if open-bracket-pos
(fsharp--compute-indentation-open-bracket open-bracket-pos)
(fsharp--compute-indentation-continuation-line)))
;; Previous line is a continuation line, use indentation of previous line
((fsharp--previous-line-continuation-line-p)
(forward-line -1)
(current-indentation))
((or
;; Beginning of Buffer; not on a continuation line
(bobp)
;; "Indenting Comment"
(fsharp--indenting-comment-p)) (current-indentation))
;; Final case includes things like pipe expressions (matches, left pipe)
;; and if/else blocks.
;;
;; else indentation based on that of the statement that
;; precedes us; use the first line of that statement to
;; establish the base, in case the user forced a non-std
;; indentation for the continuation lines (if any)
(t (fsharp--compute-indentation-relative-to-previous honor-block-close-p))))))
(defun fsharp-guess-indent-offset (&optional global)
"Guess a good value for, and change, `fsharp-indent-offset'.
By default, make a buffer-local copy of `fsharp-indent-offset' with the
new value, so that other Fsharp buffers are not affected. With
\\[universal-argument] (programmatically, optional argument GLOBAL),
change the global value of `fsharp-indent-offset'. This affects all
Fsharp buffers (that don't have their own buffer-local copy), both
those currently existing and those created later in the Emacs session.
Some people use a different value for `fsharp-indent-offset' than you use.
There's no excuse for such foolishness, but sometimes you have to deal
with their ugly code anyway. This function examines the file and sets
`fsharp-indent-offset' to what it thinks it was when they created the
mess.
Specifically, it searches forward from the statement containing point,
looking for a line that opens a block of code. `fsharp-indent-offset' is
set to the difference in indentation between that line and the Fsharp
statement following it. If the search doesn't succeed going forward,
it's tried again going backward."
(interactive "P") ; raw prefix arg
(let (new-value
(start (point))
(restart (point))
(found nil)
colon-indent)
(fsharp-goto-initial-line)
(while (not (or found (eobp)))
(when (and (re-search-forward fsharp-block-opening-re nil 'move)
(not (fsharp-in-literal-p restart)))
(setq restart (point))
(fsharp-goto-initial-line)
(if (fsharp-statement-opens-block-p)
(setq found t)
(goto-char restart))))
(unless found
(goto-char start)
(fsharp-goto-initial-line)
(while (not (or found (bobp)))
(setq found (and
(re-search-backward fsharp-block-opening-re nil 'move)
(or (fsharp-goto-initial-line) t) ; always true -- side effect
(fsharp-statement-opens-block-p)))))
(setq colon-indent (current-indentation)
found (and found (zerop (fsharp-next-statement 1)))
new-value (- (current-indentation) colon-indent))
(goto-char start)
(if (not found)
(message "Unable to determine default value for fsharp-indent-offset")
(funcall (if global 'kill-local-variable 'make-local-variable)
'fsharp-indent-offset)
(setq fsharp-indent-offset new-value)
(or noninteractive
(message "%s value of fsharp-indent-offset set to %d"
(if global "Global" "Local")
fsharp-indent-offset)))))
(defun fsharp-comment-indent-function ()
"Fsharp version of `comment-indent-function'."
;; This is required when filladapt is turned off. Without it, when
;; filladapt is not used, comments which start in column zero
;; cascade one character to the right
(save-excursion
(beginning-of-line)
(let ((eol (fsharp-point 'eol)))
(and comment-start-skip
(re-search-forward comment-start-skip eol t)
(setq eol (match-beginning 0)))
(goto-char eol)
(skip-chars-backward " \t")
(max comment-column (+ (current-column) (if (bolp) 0 1))))))
(defun fsharp-narrow-to-defun (&optional class)
"Make text outside current defun invisible.
The defun visible is the one that contains point or follows point.
Optional CLASS is passed directly to `fsharp-beginning-of-def-or-class'."
(interactive "P")
(save-excursion
(widen)
(fsharp-end-of-def-or-class class)
(let ((end (point)))
(fsharp-beginning-of-def-or-class class)
(narrow-to-region (point) end))))
(defun fsharp-shift-region (start end count)
"Indent lines from START to END by COUNT spaces."
(save-excursion
(goto-char end)
(beginning-of-line)
(setq end (point))
(goto-char start)
(beginning-of-line)
(setq start (point))
(indent-rigidly start end count)))
(defun fsharp-shift-region-left (start end &optional count)
"Shift region of Fsharp code to the left.
The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
shifted to the left, by `fsharp-indent-offset' columns.
If a prefix argument is given, the region is instead shifted by that
many columns. With no active region, dedent only the current line.
You cannot dedent the region if any line is already at column zero."
(interactive
(let ((p (point))
(m (mark))
(arg current-prefix-arg))
(if m
(list (min p m) (max p m) arg)
(list p (save-excursion (forward-line 1) (point)) arg))))
;; if any line is at column zero, don't shift the region
(save-excursion
(goto-char start)
(while (< (point) end)
(back-to-indentation)
(if (and (zerop (current-column))
(not (looking-at "\\s *$")))
(error "Region is at left edge"))
(forward-line 1)))
(fsharp-shift-region start end (- (prefix-numeric-value
(or count fsharp-indent-offset)))))
(defun fsharp-shift-region-right (start end &optional count)
"Shift region of Fsharp code to the right.
The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
shifted to the right, by `fsharp-indent-offset' columns.
If a prefix argument is given, the region is instead shifted by that
many columns. With no active region, indent only the current line."
(interactive
(let ((p (point))
(m (mark))
(arg current-prefix-arg))
(if m
(list (min p m) (max p m) arg)
(list p (save-excursion (forward-line 1) (point)) arg))))
(fsharp-shift-region start end (prefix-numeric-value
(or count fsharp-indent-offset))))
(defun fsharp-indent-region (start end &optional indent-offset)
"Reindent a region of Fsharp code.
The lines from the line containing the start of the current region up
to (but not including) the line containing the end of the region are
reindented. If the first line of the region has a non-whitespace
character in the first column, the first line is left alone and the
rest of the region is reindented with respect to it. Else the entire
region is reindented with respect to the (closest code or indenting
comment) statement immediately preceding the region.
This is useful when code blocks are moved or yanked, when enclosing
control structures are introduced or removed, or to reformat code
using a new value for the indentation offset.
If a numeric prefix argument is given, it will be used as the value of
the indentation offset. Else the value of `fsharp-indent-offset' will be
used.
Warning: The region must be consistently indented before this function
is called! This function does not compute proper indentation from
scratch (that's impossible in Fsharp), it merely adjusts the existing
indentation to be correct in context.
Warning: This function really has no idea what to do with
non-indenting comment lines, and shifts them as if they were indenting
comment lines. Fixing this appears to require telepathy.
Special cases: whitespace is deleted from blank lines; continuation
lines are shifted by the same amount their initial line was shifted,
in order to preserve their relative indentation with respect to their
initial line; and comment lines beginning in column 1 are ignored."
(interactive "*r\nP") ; region; raw prefix arg
(save-excursion
(goto-char end) (beginning-of-line) (setq end (point-marker))
(goto-char start) (beginning-of-line)
(let ((fsharp-indent-offset (prefix-numeric-value
(or indent-offset fsharp-indent-offset)))
(indents '(-1)) ; stack of active indent levels
(target-column 0) ; column to which to indent
(base-shifted-by 0) ; amount last base line was shifted
(indent-base (if (looking-at "[ \t\n]")
(fsharp-compute-indentation t)
0))
ci)
(while (< (point) end)
(setq ci (current-indentation))
;; figure out appropriate target column
(cond
((or (looking-at "//") ; comment in column 1
(looking-at "[ \t]*$")) ; entirely blank
(setq target-column 0))
((fsharp-continuation-line-p) ; shift relative to base line
(setq target-column (+ ci base-shifted-by)))
(t ; new base line
(if (> ci (car indents)) ; going deeper; push it
(setq indents (cons ci indents))
;; else we should have seen this indent before
(setq indents (memq ci indents)) ; pop deeper indents
(if (null indents)
(error "Bad indentation in region, at line %d"