-
Notifications
You must be signed in to change notification settings - Fork 0
/
csharp-mode.el
5911 lines (4872 loc) · 220 KB
/
csharp-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
;;; csharp-mode.el --- C# mode derived mode
;; Author : Dylan R. E. Moonfire (original)
;; Maintainer : Dino Chiesa <[email protected]>
;; Created : Feburary 2005
;; Modified : May 2011
;; Version : 0.8.6
;; Keywords : c# languages oop mode
;; X-URL : http://code.google.com/p/csharpmode/
;; Last-saved : <2011-May-22 10:48:26>
;;
;; 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 2 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;;
;; This is a major mode for editing C# code. It performs automatic
;; indentation of C# syntax; font locking; and integration with compile.el;
;; flymake.el; yasnippet.el; and imenu.el.
;;
;; csharp-mode requires CC Mode 5.30 or later. It works with
;; cc-mode 5.31.3, which is current at this time.
;;
;; Features:
;;
;; - font-lock and indent of C# syntax including:
;; all c# keywords and major syntax
;; attributes that decorate methods, classes, fields, properties
;; enum types
;; #if/#endif #region/#endregion
;; instance initializers
;; anonymous functions and methods
;; verbatim literal strings (those that begin with @)
;; generics
;;
;; - automagic code-doc generation when you type three slashes.
;;
;; - intelligent insertion of matched pairs of curly braces.
;;
;; - compile tweaks. Infers the compile command from special comments
;; in the file header. Also, sets the regex for next-error, so that
;; compile.el can handle csc.exe output.
;;
;; - flymake integration
;; - select flymake command from code comments
;; - infer flymake command otherwise (presence of makefile, etc)
;; - Turn off query-on-exit-flag for the flymake process.
;; - define advice to flymake-goto-line , to allow it to goto the
;; appropriate column for the error on a given line. This works
;; with `flymake-goto-next-error' etc.
;;
;; - yasnippet integration
;; - preloaded snippets
;;
;; - imenu integration - generates an index of namespaces, classes,
;; interfaces, methods, and properties for easy navigation within
;; the buffer.
;;
;; Installation instructions
;; --------------------------------
;;
;; Put csharp-mode.el somewhere in your load path, optionally byte-compile
;; it, and add the following to your .emacs file:
;;
;; (autoload 'csharp-mode "csharp-mode" "Major mode for editing C# code." t)
;; (setq auto-mode-alist
;; (append '(("\\.cs$" . csharp-mode)) auto-mode-alist))
;;
;;
;; Optionally, define and register a mode-hook function. To do so, use
;; something like this in your .emacs file:
;;
;; (defun my-csharp-mode-fn ()
;; "function that runs when csharp-mode is initialized for a buffer."
;; (turn-on-auto-revert-mode)
;; (setq indent-tabs-mode nil)
;; (require 'flymake)
;; (flymake-mode 1)
;; (require 'yasnippet)
;; (yas/minor-mode-on)
;; (require 'rfringe)
;; ...insert more code here...
;; ...including any custom key bindings you might want ...
;; )
;; (add-hook 'csharp-mode-hook 'my-csharp-mode-fn t)
;;
;;
;; General
;; ----------------------------
;;
;; Mostly C# mode will "just work." Use `describe-mode' to see the
;; default keybindings and the highlights of the mode.
;;
;;
;; Flymake Integration
;; ----------------------------
;;
;; You can use flymake with csharp mode to automatically check the
;; syntax of your csharp code, and highlight errors. To do so, add a
;; comment line like this to each .cs file that you use flymake with:
;;
;; // flymake: c:\.net3.5\csc.exe /t:module /nologo /R:Foo.dll @@FILE@@
;;
;; That lines specifies a command "stub". Flymake appends the name of
;; the file to compile, and then runs the command to check
;; syntax. Flymake assumes that syntax errors will be noted in the
;; output of the command in a form that fits one of the regexs in the
;; `compilation-error-regexp-alist-alist'. Check the flymake module for
;; more information on that.
;;
;; Some rules for the command:
;;
;; 1. it must appear all on a single line.
;;
;; 2. csharp-mode generally looks for the marker line in the first N
;; lines of the file, where N is set in
;; `csharp-cmd-line-limit'. See the documentation on that
;; variable for more information.
;;
;; 3. the command SHOULD use @@FILE@@ in place of the name of the
;; source file to be compiled, normally the file being edited.
;; This is because normally flymake saves a copy of the buffer
;; into a temporary file with a unique name, and then compiles
;; that temporary file. The token @@FILE@@ is replaced by
;; csharp-mode with the name of the temporary file created by
;; flymake, before invoking the command.
;;
;; 4. The command should include /R options specifying external
;; libraries that the code depends on.
;;
;; If you have no external dependencies, then you need not specify any
;; flymake command at all. csharp-mode will implicitly act as if you had
;; specified the command:
;;
;; // flymake: c:\.net3.5\csc.exe /t:module /nologo @@FILE@@
;;
;;
;; If you use csc.exe as the syntax check tool (as almost everyone
;; will), the /t:module is important. csharp-mode assumes that the
;; syntax-check compile command will produce a file named
;; NAME.netmodule, which is the default when using /t:module. (Remember
;; than NAME is dynamically generated). csharp-mode will remove the
;; generated netmodule file after the syntax check is complete. If you
;; don't specify /t:module, then csharp-mode won't know what file to
;; delete.
;;
;; csharp-mode also fiddles with some other flymake things. In
;; particular it: adds .cs to the flymake "allowed filename masks";
;; adds parsing for csc error messages; and adds advice to the error
;; parsing logic. This all should be pretty benign for all other
;; flymake buffers. But it might not be.
;;
;; You can explicitly turn the flymake integration for C# off by
;; setting `csharp-want-flymake-fixup' to nil.
;;
;;
;; Compile Integration
;; ----------------------------
;;
;; csharp-mode binds the function `csharp-invoke-compile-interactively'
;; to "\C-x\C-e" . This function attempts to intellgently guess the
;; format of the compile command to use for a buffer. It looks in the
;; comments at the head of the buffer for a line that begins with
;; compile: . If found, csharp-mode suggests the text that follows as
;; the compilation command when running `compile' . If such a line is
;; not found, csharp-mode falls back to a msbuild or nmake command.
;; See the documentation on `csharp-cmd-line-limit' for further
;; information.
;;
;; Also, csharp-mode installs an error regexp for csc.exe into
;; `compilation-error-regexp-alist-alist', which allows `next-error'
;; and `previous-error' (defined in compile.el) to navigate to the next
;; and previous compile errors in the cs buffer, after you've run `compile'.
;;
;;
;; YASnippet integration
;; -----------------------------
;;
;; csharp-mode defines some built-in snippets for
;; convenience. For example, if statements, for, foreach, and
;; so on. You can see them on the YASnippet menu that is displayed
;; when a csharp-mode buffer is opened. csharp-mode defines this
;; snippets happens only if ya-snippet is available. (It is done in an
;; `eval-after-load' clause.) The builtin snippets will not overwrite
;; snippets that use the same name, if they are defined in the normal
;; way (in a compiled bundle) with ya-snippet.
;;
;; You can explicitly turn off ya-snippet integration. See the var,
;; `csharp-want-yasnippet-fixup'.
;;
;;
;; imenu integration
;; -----------------------------
;;
;; This should just work. For those who don't know what imenu is, it
;; allows navigation to different points within the file from an
;; "Index" menu, in the window's menubar. csharp-mode computes the
;; menu containing the namespaces, classes, methods, and so on, in the
;; buffer. This happens at the time the file is loaded; for large
;; files it takes a bit of time to complete the scan. If you don't
;; want this capability, set `csharp-want-imenu' to nil.
;;
;;
;;; Known Bugs:
;;
;; The imenu scan is text-based and naive. For example, if you
;; intersperse comments between the name of a class/method/namespace,
;; and the curly brace, the scan will not recognize the thing being
;; declared. This is fixable - would need to extract the buffer
;; substring then remove comments before doing the regexp checks - but
;; it would make the scan much slower. Also, the scan doesn't deal
;; with preproc symbol definitions and #if/#else. Those things are
;; invisible to the scanner csharp-mode uses to build the imenu menu.
;;
;; Leading identifiers are no longer being fontified, for some reason.
;; See matchers-before. (Not sure this is still a problem - 19 may
;; 2011 DPC)
;;
;; Method names with a preceding attribute are not fontified.
;;
;; The symbol followng #if is not fontified. It should be treated like
;; define and get font-lock-variable-name-face .
;;
;; This code doesn't seem to work when you compile it, then
;; load/require in the emacs file. You will get an error (error
;; "`c-lang-defconst' must be used in a file") which happens because
;; cc-mode doesn't think it is in a buffer while loading directly
;; from the init. However, if you call it based on a file extension,
;; it works properly. Interestingly enough, this doesn't happen if
;; you don't byte-compile cc-mode.
;;
;;
;;
;; Todo:
;;
;; imenu should scan for and find delegates and events, in addition
;; to the classes, structs, properties and methods it does currently.
;;
;; Get csharp-mode.el accepted as part of the emacs standard distribution.
;; Must contact monnier at iro.umontreal.ca to make this happen.
;;
;; Add refactoring capabilities?
;; - extract as method - extract a block of code into a method
;; - extract as Func<> - extract a block of code into an Action<T>
;;
;; More code-gen power:
;; - interface implementation - I think would require csharp-shell
;;
;;
;; Acknowledgements:
;;
;; Thanks to Alan Mackenzie and Stefan Monnier for answering questions
;; and making suggestions. And to Trey Jackson for sharing his
;; knowledge of emacs lisp.
;;
;;
;;; Versions:
;;
;; 0.1.0 - Initial release.
;; 0.2.0 - Fixed the identification on the "enum" keyword.
;; - Fixed the font-lock on the "base" keyword
;; 0.3.0 - Added a regex to fontify attributes. It isn't the
;; the best method, but it handles single-like attributes
;; well.
;; - Got "super" not to fontify as a keyword.
;; - Got extending classes and interfaces to fontify as something.
;; 0.4.0 - Removed the attribute matching because it broke more than
;; it fixed.
;; - Corrected a bug with namespace not being properly identified
;; and treating the class level as an inner object, which screwed
;; up formatting.
;; - Added "partial" to the keywords.
;; 0.5.0 - Found bugs with compiled cc-mode and loading from init files.
;; - Updated the eval-when-compile to code to let the mode be
;; compiled.
;; 0.6.0 - Added the c-filter-ops patch for 5.31.1 which made that
;; function in cc-langs.el unavailable.
;; - Added a csharp-lineup-region for indention #region and
;; #endregion block differently.
;; 0.7.0 - Added autoload so update-directory-autoloads works
;; (Thank you, Nikolaj Schumacher)
;; - Fontified the entire #region and #endregion lines.
;; - Initial work to get get, set, add, remove font-locked.
;; 0.7.1 - Added option to indent #if/endif with code
;; - Fixed c-opt-cpp-prefix defn (it must not include the BOL
;; char (^).
;; - proper fontification and indent of classes that inherit
;; (previously the colon was confusing the parser)
;; - reclassified namespace as a block beginner
;; - removed $ as a legal symbol char - not legal in C#.
;; - added struct to c-class-decl-kwds so indent is correct
;; within a struct.
;; 0.7.2 - Added automatic codedoc insertion.
;; 0.7.3 - Instance initializers (new Type { ... } ) and
;; (new Type() { ...} ) are now indented properly.
;; - proper fontification and indent of enums as brace-list-*,
;; including special treatment for enums that explicitly
;; inherit from an int type. Previously the colon was
;; confusing the parser.
;; - proper fontification of verbatim literal strings,
;; including those that end in slash. This edge case was not
;; handled at all before; it is now handled correctly.
;; - code cleanup and organization; removed the formfeed.
;; - intelligent curly-brace insertion with
;; `csharp-insert-open-brace'
;; 0.7.4 - added a C# style
;; - using is now a keyword and gets fontified correctly
;; - fixed a bug that had crept into the codedoc insertion.
;; 0.7.5 - now fontify namespaces in the using statements. This is
;; done in the csharp value for c-basic-matchers-before .
;; - also fontify the name following namespace decl.
;; This is done in the csharp value for c-basic-matchers-after .
;; - turn on recognition of generic types. They are now
;; fontified correctly.
;; - <> are now treated as syntactic parens and can be jumped
;; over with c-forward-sexp.
;; - Constructors are now fontified.
;; - Field/Prop names inside object initializers are now fontified.
;;
;; 0.7.7 - relocate running c-run-mode-hooks to the end of
;; csharp-mode, to allow user to modify key bindings in a
;; hook if he doesn't like the defaults.
;;
;; 0.7.8 - redefine csharp-log to insert timestamp.
;; - Fix byte-compile errors on emacs 23.2 ? Why was
;; c-filter-ops duplicated here? What was the purpose of its
;; presence here, I am not clear.
;;
;; 0.8.0 - include flymake magic into this module.
;; - include yasnippet integration
;;
;; 0.8.2 2011 April DPC
;; - small tweaks; now set a one-time bool for flymake installation
;; - some doc updates on flymake
;;
;; 0.8.3 2011 May 17 DPC
;; - better help on csharp-mode
;; - csharp-move-* functions for manual navigation.
;; - imenu integration for menu-driven navigation - navigate to
;; named methods, classes, etc.
;; - adjusted the flymake regexp to handle output from fxcopcmd,
;; and extended the help to provide examples how to use this.
;;
;; 0.8.4 DPC 2011 May 18
;; - fix a basic bug in the `csharp-yasnippet-fixup' fn.
;;
;; 0.8.5 DPC 2011 May 21
;; - imenu: correctly parse Properties that are part of an
;; explicitly specified interface. Probably need to do this
;; for methods, too.
;; - fontify the optional alias before namespace in a using (import).
;; - Tweak open-curly magic insertion for object initializers.
;; - better fontification of variables and references
;; - "sealed" is now fontified as a keyword
;; - imenu: correctly index ctors that call this or base.
;; - imenu: correctly index Extension methods (this System.Enum e)
;; - imenu: correctly scan method params tagged with out, ref, params
;; - imenu scan: now handle curlies within strings.
;; - imenu: split menus now have better labels, are sorted correctly.
;;
;; 0.8.6 DPC 2011 May ??
;; - extern keyword
;;
(require 'cc-mode)
(message (concat "Loading " load-file-name))
;; ==================================================================
;; c# upfront stuff
;; ==================================================================
;; This is a copy of the function in cc-mode which is used to handle the
;; eval-when-compile which is needed during other times.
;;
;; NB: I think this is needed to satisfy requirements when this module
;; calls `c-lang-defconst'. (DPC)
;; (defun c-filter-ops (ops opgroup-filter op-filter &optional xlate)
;; ;; See cc-langs.el, a direct copy.
;; (unless (listp (car-safe ops))
;; (setq ops (list ops)))
;; (cond ((eq opgroup-filter t)
;; (setq opgroup-filter (lambda (opgroup) t)))
;; ((not (functionp opgroup-filter))
;; (setq opgroup-filter `(lambda (opgroup)
;; (memq opgroup ',opgroup-filter)))))
;; (cond ((eq op-filter t)
;; (setq op-filter (lambda (op) t)))
;; ((stringp op-filter)
;; (setq op-filter `(lambda (op)
;; (string-match ,op-filter op)))))
;; (unless xlate
;; (setq xlate 'identity))
;; (c-with-syntax-table (c-lang-const c-mode-syntax-table)
;; (delete-duplicates
;; (mapcan (lambda (opgroup)
;; (when (if (symbolp (car opgroup))
;; (when (funcall opgroup-filter (car opgroup))
;; (setq opgroup (cdr opgroup))
;; t)
;; t)
;; (mapcan (lambda (op)
;; (when (funcall op-filter op)
;; (let ((res (funcall xlate op)))
;; (if (listp res) res (list res)))))
;; opgroup)))
;; ops)
;; :test 'equal)))
;; These are only required at compile time to get the sources for the
;; language constants. (The load of cc-fonts and the font-lock
;; related constants could additionally be put inside an
;; (eval-after-load "font-lock" ...) but then some trickery is
;; necessary to get them compiled.)
(eval-when-compile
(let ((load-path
(if (and (boundp 'byte-compile-dest-file)
(stringp byte-compile-dest-file))
(cons (file-name-directory byte-compile-dest-file) load-path)
load-path)))
(load "cc-mode" nil t)
(load "cc-fonts" nil t)
(load "cc-langs" nil t)))
(eval-and-compile
;; Make our mode known to the language constant system. Use Java
;; mode as the fallback for the constants we don't change here.
;; This needs to be done also at compile time since the language
;; constants are evaluated then.
(c-add-language 'csharp-mode 'java-mode))
;; ==================================================================
;; end of c# upfront stuff
;; ==================================================================
;; ==================================================================
;; constants used in this module
;; ==================================================================
;;(error (byte-compile-dest-file))
;;(error (c-get-current-file))
(defconst csharp-aspnet-directive-re
"<%@.+?%>"
"Regex for matching directive blocks in ASP.NET files (.aspx, .ashx, .ascx)")
(defconst csharp-enum-decl-re
(concat
"\\<enum[ \t\n\r\f\v]+"
"\\([[:alpha:]_][[:alnum:]_]*\\)"
"[ \t\n\r\f\v]*"
"\\(:[ \t\n\r\f\v]*"
"\\("
(c-make-keywords-re nil
(list "sbyte" "byte" "short" "ushort" "int" "uint" "long" "ulong"))
"\\)"
"\\)?")
"Regex that captures an enum declaration in C#"
)
;; ==================================================================
;; ==================================================================
;; csharp-mode utility and feature defuns
;; ==================================================================
(defun csharp--at-vsemi-p (&optional pos)
"Determines if there is a virtual semicolon at POS or point.
It returns t if at a position where a virtual-semicolon is.
Otherwise nil.
This is the C# version of the function. It gets set into
the variable `c-at-vsemi-p-fn'.
A vsemi is a cc-mode concept implying the end of a statement,
where no actual end-of-statement signifier character ( semicolon,
close-brace) appears. The concept is used to allow proper
indenting of blocks of code: Where a vsemi appears, the following
line will not indent further.
A vsemi appears in 3 cases in C#:
- after an attribute that decorates a class, method, field, or
property.
- in an object initializer, before the open-curly?
- after an ASPNET directive, that appears in a aspx/ashx/ascx file
An example of the former is [WebMethod] or [XmlElement].
An example of the latter is something like this:
<%@ WebHandler Language=\"C#\" Class=\"Handler\" %>
Providing this function allows the indenting in csharp-mode
to work properly with code that includes attributes and ASPNET
directives.
"
(save-excursion
(let ((pos-or-point (progn (if pos (goto-char pos)) (point))))
(cond
;; before open curly in object initializer. new Foo* { }
((and (looking-back
(concat "\\<new[ \t\n\f\v\r]+"
"\\(?:[A-Za-z_][[:alnum:]]*\\.\\)*"
"[A-Za-z_][[:alnum:]]*[\ t\n\f\v\r]*"))
(looking-at "[ \t\n\f\v\r]*{"))
t)
;; put a vsemi after an ASPNET directive, like
;; <%@ WebHandler Language="C#" Class="Handler" %>
((looking-back (concat csharp-aspnet-directive-re "$") nil t)
t)
;; put a vsemi after an attribute, as with
;; [XmlElement]
;; Except when the attribute is used within a line of code, as
;; specifying something for a parameter.
((c-safe (backward-sexp) t)
(cond
((re-search-forward
(concat
"\\(\\["
"[ \t\n\r\f\v]*"
"\\("
"\\(?:[A-Za-z_][[:alnum:]]*\\.\\)*"
"[A-Za-z_][[:alnum:]]*"
"\\)"
"[^]]*\\]\\)"
)
(1+ pos-or-point) t)
(c-safe (backward-sexp))
(c-backward-syntactic-ws)
(cond
((eq (char-before) 93) ;; close sq brace (a previous attribute)
(csharp--at-vsemi-p (point))) ;; recurse
((or
(eq (char-before) 59) ;; semicolon
(eq (char-before) 123) ;; open curly
(eq (char-before) 125)) ;; close curly
t)
;; attr is used within a line of code
(t nil)))
(t nil)))
(t nil))
)))
(defun csharp-lineup-region (langelem)
"Indent all #region and #endregion blocks inline with code while
retaining normal column-zero indention for #if and the other
processing blocks.
To use this indenting just put the following in your emacs file:
(c-set-offset 'cpp-macro 'csharp-lineup-region)
An alternative is to use `csharp-lineup-if-and-region'.
"
(save-excursion
(back-to-indentation)
(if (re-search-forward "#\\(end\\)?region" (c-point 'eol) [0]) 0 [0])))
(defun csharp-lineup-if-and-region (langelem)
"Indent all #region/endregion blocks and #if/endif blocks inline
with code while retaining normal column-zero indention for any
other processing blocks.
To use this indenting just put the following in your emacs file:
(c-set-offset 'cpp-macro 'csharp-lineup-if-and-region)
Another option is to use `csharp-lineup-region'.
"
(save-excursion
(back-to-indentation)
(if (re-search-forward "#\\(\\(end\\)?\\(if\\|region\\)\\|else\\)" (c-point 'eol) [0]) 0 [0])))
(defun csharp-in-literal (&optional lim detect-cpp)
"Return the type of literal point is in, if any.
Basically this works like `c-in-literal' except it doesn't
use or fill the cache (`c-in-literal-cache').
The return value is a symbol: `c' if in a C-style comment, `c++'
if in a C++ style comment, `string' if in a string literal,
`pound' if DETECT-CPP is non-nil and in a preprocessor line, or
nil if somewhere else. Optional LIM is used as the backward
limit of the search. If omitted, or nil, `c-beginning-of-syntax'
is used.
Note that this function might do hidden buffer changes. See the
comment at the start of cc-engine.el for more info."
(let ((rtn
(save-excursion
(let* ((pos (point))
(lim (or lim (progn
(c-beginning-of-syntax)
(point))))
(state (parse-partial-sexp lim pos)))
(csharp-log 4 "parse lim(%d) state: %s" lim (prin1-to-string state))
(cond
((elt state 3)
(csharp-log 4 "in literal string (%d)" pos)
'string)
((elt state 4)
(csharp-log 4 "in literal comment (%d)" pos)
(if (elt state 7) 'c++ 'c))
((and detect-cpp (c-beginning-of-macro lim)) 'pound)
(t nil))))))
rtn))
(defun csharp-insert-open-brace ()
"Intelligently insert a pair of curly braces. This fn should be
bound to the open-curly brace, with
(local-set-key (kbd \"{\") 'csharp-insert-open-brace)
The default binding for an open curly brace in cc-modes is often
`c-electric-brace' or `skeleton-pair-insert-maybe'. The former
can be configured to insert newlines around braces in various
syntactic positions. The latter inserts a pair of braces and
then does not insert a newline, and does not indent.
This fn provides another option, with some additional
intelligence for csharp-mode. When you type an open curly, the
appropriate pair of braces appears, with spacing and indent set
in a context-sensitive manner:
- Within a string literal, you just get a pair of braces, and
point is set between them. This works for String.Format()
purposes.
- Following = or [], as in an array assignment, you get a pair
of braces, with two intervening spaces, with a semincolon
appended. Point is left between the braces.
- Following \"new Foo\", it's an object initializer. You get:
newline, open brace, newline, newline, close, semi. Point is
left on the blank line between the braces. Unless the object
initializer is within an array initializer, in which case, no
newlines, and the semi is replaced with a comma. (Try it to
see what this means).
- Following => , implying a lambda, you get an open/close pair,
with two intervening spaces, no semicolon, and point on the
2nd space.
- Otherwise, you get a newline, the open curly, followed by
an empty line and the closing curly on the line following,
with point on the empty line.
There may be another way to get this to happen appropriately just
within emacs, but I could not figure out how to do it. So I
wrote this alternative.
"
(interactive)
(let
(tpoint
(in-string (string= (csharp-in-literal) "string"))
(preceding3
(save-excursion
(and
(skip-chars-backward " \t")
(> (- (point) 2) (point-min))
(buffer-substring-no-properties (point) (- (point) 3)))))
(one-word-back
(save-excursion
(backward-word 2)
(thing-at-point 'word))))
(cond
;; Case 1: inside a string literal?
;; --------------------------------------------
;; If so, then just insert a pair of braces and put the point
;; between them. The most common case is a format string for
;; String.Format() or Console.WriteLine().
(in-string
(self-insert-command 1)
(insert "}")
(backward-char))
;; Case 2: the open brace starts an array initializer.
;; --------------------------------------------
;; When the last non-space was an equals sign or square brackets,
;; then it's an initializer.
((save-excursion
(and (c-safe (backward-sexp) t)
(looking-at "\\(\\w+\\b *=\\|[[]]+\\)")))
(self-insert-command 1)
(insert " };")
(backward-char 3))
;; Case 3: the open brace starts an instance initializer
;; --------------------------------------------
;; If one-word-back was "new", then it's an object initializer.
((string= one-word-back "new")
(csharp-log 2 "object initializer")
(setq tpoint (point)) ;; prepare to indent-region later
(backward-word 2)
(c-backward-syntactic-ws)
(if (or (eq (char-before) ?,) ;; comma
(and (eq (char-before) 123) ;; open curly
(progn (backward-char)
(c-backward-syntactic-ws)
(looking-back "\\[\\]"))))
(progn
;; within an array - emit no newlines
(goto-char tpoint)
(self-insert-command 1)
(insert " },")
(backward-char 3))
(progn
(goto-char tpoint)
(newline)
(self-insert-command 1)
(newline-and-indent)
(newline)
(insert "};")
(c-indent-region tpoint (point))
(forward-line -1)
(indent-according-to-mode)
(end-of-line))))
;; Case 4: a lambda initialier.
;; --------------------------------------------
;; If the open curly follows =>, then it's a lambda initializer.
((string= (substring preceding3 -2) "=>")
(csharp-log 2 "lambda init")
(self-insert-command 1)
(insert " }")
(backward-char 2))
;; else, it's a new scope. (if, while, class, etc)
(t
(save-excursion
(csharp-log 2 "new scope")
(set-mark (point)) ;; prepare to indent-region later
;; check if the prior sexp is on the same line
(if (save-excursion
(let ((curline (line-number-at-pos))
(aftline (progn
(if (c-safe (backward-sexp) t)
(line-number-at-pos)
-1))))
(= curline aftline)))
(newline-and-indent))
(self-insert-command 1)
(c-indent-line-or-region)
(end-of-line)
(newline)
(insert "}")
;;(c-indent-command) ;; not sure of the difference here
(c-indent-line-or-region)
(forward-line -1)
(end-of-line)
(newline-and-indent)
;; point ends up on an empty line, within the braces, properly indented
(setq tpoint (point)))
(goto-char tpoint)))))
;; ==================================================================
;; end of csharp-mode utility and feature defuns
;; ==================================================================
;; ==================================================================
;; c# values for "language constants" defined in cc-langs.el
;; ==================================================================
(c-lang-defconst c-at-vsemi-p-fn
csharp 'csharp--at-vsemi-p)
;; This c-opt-after-id-concat-key is a regexp that matches
;; dot. In other words: "\\(\\.\\)"
;; Not sure why this needs to be so complicated.
;; This const is now internal (obsolete); need to move to
;; c-after-id-concat-ops. I don't yet understand the meaning
;; of that variable, so for now. . . .
;; (c-lang-defconst c-opt-after-id-concat-key
;; csharp (if (c-lang-const c-opt-identifier-concat-key)
;; (c-lang-const c-symbol-start)))
(c-lang-defconst c-opt-after-id-concat-key
csharp "[[:alpha:]_]" )
;; The matchers elements can be of many forms. It gets pretty
;; complicated. Do a describe-variable on font-lock-keywords to get a
;; description. (Why on font-lock-keywords? I don't know, but that's
;; where you get the help.)
;;
;; Aside from the provided documentation, the other option of course, is
;; to look in the source code as an example for what to do. The source
;; in cc-fonts uses a defun c-make-font-lock-search-function to produce
;; most of the matchers. Called this way:
;;
;; (c-make-font-lock-search-function regexp '(A B c))
;;
;; The REGEXP is used in re-search-forward, and if there's a match, then
;; A is called within a save-match-data. If B and C are non-nil, they
;; are called as pre and post blocks, respecitvely.
;;
;; Anyway the c-make-font-lock-search-function works for a single regex,
;; but more complicated scenarios such as those intended to match and
;; fontify object initializers, call for a hand-crafted lambda.
;;
;; The object initializer is special because matching on it must
;; allow nesting.
;;
;; In c#, the object initializer block is used directly after a
;; constructor, like this:
;;
;; new MyType
;; {
;; Prop1 = "foo"
;; }
;;
;; csharp-mode needs to fontify the properties in the
;; initializer block in font-lock-variable-name-face. The key thing is
;; to set the text property on the open curly, using type c-type and
;; value c-decl-id-start. This apparently allows `parse-partial-sexp' to
;; do the right thing, later.
;;
;; This simple case is easy to handle in a regex, using the basic
;; `c-make-font-lock-search-function' form. But the general syntax for a
;; constructor + object initializer in C# is more complex:
;;
;; new MyType(..arglist..) {
;; Prop1 = "foo"
;; }
;;
;; A simple regex match won't satisfy here, because the ..arglist.. can
;; be anything, including calls to other constructors, potentially with
;; object initializer blocks. This may nest arbitrarily deeply, and the
;; regex in emacs doesn't support balanced matching. Therefore there's
;; no way to match on the "outside" pair of parens, to find the relevant
;; open curly. What's necessary is to do the match on "new MyType" then
;; skip over the sexp defined by the parens, then set the text property on
;; the appropriate open-curly.
;;
;; To make that happen, it's good to have insight into what the matcher
;; really does. The output of `c-make-font-lock-search-function' before
;; byte-compiling, is:
;;
;; (lambda (limit)
;; (let ((parse-sexp-lookup-properties
;; (cc-eval-when-compile
;; (boundp 'parse-sexp-lookup-properties))))
;; (while (re-search-forward REGEX limit t)
;; (unless
;; (progn
;; (goto-char (match-beginning 0))
;; (c-skip-comments-and-strings limit))
;; (goto-char (match-end 0))
;; (progn
;; B
;; (save-match-data A)
;; C ))))
;; nil)
;;
;; csharp-mode uses this hand-crafted form of a matcher to handle the
;; general case for constructor + object initializer, within
;; `c-basic-matchers-after' .
;;
;; (defun c-make-font-lock-search-function (regexp &rest highlights)
;; ;; This function makes a byte compiled function that works much like
;; ;; a matcher element in `font-lock-keywords'. It cuts out a little
;; ;; bit of the overhead compared to a real matcher. The main reason
;; ;; is however to pass the real search limit to the anchored
;; ;; matcher(s), since most (if not all) font-lock implementations
;; ;; arbitrarily limits anchored matchers to the same line, and also
;; ;; to insulate against various other irritating differences between
;; ;; the different (X)Emacs font-lock packages.
;; ;;
;; ;; REGEXP is the matcher, which must be a regexp. Only matches
;; ;; where the beginning is outside any comment or string literal are
;; ;; significant.
;; ;;
;; ;; HIGHLIGHTS is a list of highlight specs, just like in
;; ;; `font-lock-keywords', with these limitations: The face is always
;; ;; overridden (no big disadvantage, since hits in comments etc are
;; ;; filtered anyway), there is no "laxmatch", and an anchored matcher
;; ;; is always a form which must do all the fontification directly.
;; ;; `limit' is a variable bound to the real limit in the context of
;; ;; the anchored matcher forms.
;; ;;
;; ;; This function does not do any hidden buffer changes, but the
;; ;; generated functions will. (They are however used in places
;; ;; covered by the font-lock context.)
;;
;; ;; Note: Replace `byte-compile' with `eval' to debug the generated
;; ;; lambda easier.
;; (byte-compile
;; `(lambda (limit)
;; (let (;; The font-lock package in Emacs is known to clobber
;; ;; `parse-sexp-lookup-properties' (when it exists).
;; (parse-sexp-lookup-properties
;; (cc-eval-when-compile
;; (boundp 'parse-sexp-lookup-properties))))
;; (while (re-search-forward ,regexp limit t)
;; (unless (progn
;; (goto-char (match-beginning 0))
;; (c-skip-comments-and-strings limit))
;; (goto-char (match-end 0))
;; ,@(mapcar
;; (lambda (highlight)
;; (if (integerp (car highlight))
;; (progn
;; (unless (eq (nth 2 highlight) t)
;; (error
;; "The override flag must currently be t in %s"
;; highlight))
;; (when (nth 3 highlight)
;; (error
;; "The laxmatch flag may currently not be set in %s"
;; highlight))
;; `(save-match-data
;; (c-put-font-lock-face
;; (match-beginning ,(car highlight))
;; (match-end ,(car highlight))
;; ,(elt highlight 1))))
;; (when (nth 3 highlight)
;; (error "Match highlights currently not supported in %s"
;; highlight))
;; `(progn
;; ,(nth 1 highlight)
;; (save-match-data ,(car highlight))
;; ,(nth 2 highlight))))
;; highlights))))