-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysml-mode.el
More file actions
1192 lines (1031 loc) · 45.7 KB
/
sysml-mode.el
File metadata and controls
1192 lines (1031 loc) · 45.7 KB
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
;;; sysml-mode.el --- Major mode for SysML v2 (Systems Modeling Language) -*- lexical-binding: t; -*-
;; Copyright (C) 2025 DeciSym, LLC
;; Author: Donald Anthony Pellegrino Jr., Ph.D.
;; Keywords: languages, modeling, systems engineering
;; Version: 1.1.0
;; Package-Requires: ((emacs "24.3"))
;; URL: https://github.com/decisym/sysml-mode
;; Homepage: https://github.com/decisym/sysml-mode
;;; Commentary:
;; This package provides a major mode for editing SysML v2 (Systems Modeling Language)
;; files with syntax highlighting based on the OMG SysML v2 normative specification.
;;
;; SysML v2 specification: https://www.omg.org/spec/SysML/2.0/
;; Normative example: https://www.omg.org/cgi-bin/doc?ptc/25-04-31.sysml
;;
;; Features:
;; - Syntax highlighting for keywords, operators, types
;; - Comment support (single-line // and multi-line /* */)
;; - Documentation blocks (doc /* ... */)
;; - Indentation support
;; - Integration with validate-sysml.sh for on-save validation
;;
;; Installation:
;; Add to your .emacs or init.el:
;; (load-file "/path/to/sysml-mode.el")
;; (add-to-list 'auto-mode-alist '("\\.sysml\\'" . sysml-mode))
;;; Code:
(require 'cl-lib)
;; Autoload for better performance - load only when needed
(autoload 'electric-pair-local-mode "elec-pair" nil t)
(autoload 'hs-minor-mode "hideshow" nil t)
(autoload 'prettify-symbols-mode "prog-mode" nil t)
(defgroup sysml nil
"Major mode for editing SysML v2 files."
:prefix "sysml-"
:group 'languages)
(defcustom sysml-validator-script nil
"Path to the validate-sysml.sh script.
If nil, auto-detect from buffer's directory."
:type '(choice (const :tag "Auto-detect" nil)
(file :tag "Script path"))
:group 'sysml)
(defcustom sysml-validate-on-save nil
"Whether to validate SysML files on save."
:type 'boolean
:group 'sysml)
;; Syntax highlighting
(defconst sysml-font-lock-keywords
(eval-when-compile
(let* (
;; Keyword categories based on OMG SysML v2 specification
;; Package and namespace keywords
(package-keywords '("package" "import" "private" "public" "standard" "library"))
;; Definition keywords (def constructs)
(definition-keywords '("def" "part" "attribute" "item" "port" "action" "state"
"requirement" "constraint" "connection" "interface" "allocation"
"verification" "use" "case" "calc" "analysis" "concern"
"viewpoint" "view" "metadata" "individual" "snapshot" "timeslice"
"enum" "variation" "variant" "stream" "message" "flow"
"succession" "feature" "abstract" "readonly" "derived" "end"
"binding" "succession"))
;; Keywords that can precede "def" for type definitions
(def-types '("part" "attribute" "item" "port" "action" "state"
"requirement" "constraint" "connection" "interface" "allocation"
"verification" "use" "case" "calc" "analysis" "concern"
"viewpoint" "view" "metadata" "individual" "enum"))
;; Behavioral and structural keywords
(behavioral-keywords '("exhibit" "perform" "then" "first" "accept" "send" "via"
"entry" "exit" "do" "transition" "if" "else" "while" "for"
"return" "assert" "assume" "require" "fork" "join" "merge"
"decide" "loop" "parallel" "when" "at" "new"))
;; Relationship and constraint keywords
(relationship-keywords '("specializes" "subsets" "redefines" "references" "conjugate"
"chains" "inverse" "readonly" "derived" "composite"
"bind" "connect" "satisfy" "verify" "subject" "objective"
"from" "to" "about" "actor" "stakeholder"))
;; Directional keywords
(direction-keywords '("in" "out" "inout"))
;; Special declaration keywords
(declaration-keywords '("doc" "comment" "language" "inv" "pre" "post" "body" "result"
"filter" "rendering" "expose" "ref" "all" "that" "self"
"featured" "by" "typing" "chaining" "inverting" "owned"
"member" "multiplicity" "ordered" "nonunique" "sequence"
"alias" "for" "occurrence" "meta"))
;; Logical operators
(logical-operators '("and" "or" "xor" "not" "implies"))
;; Built-in types - NONE, SysML v2 has no built-in types
;; All types (String, Boolean, Integer, Real, etc.) are defined in standard library
(builtin-types '())
;; Generate regexp patterns
(package-keywords-regexp (regexp-opt package-keywords 'words))
(definition-keywords-regexp (regexp-opt definition-keywords 'words))
(def-types-regexp (regexp-opt def-types 'words))
(behavioral-keywords-regexp (regexp-opt behavioral-keywords 'words))
(relationship-keywords-regexp (regexp-opt relationship-keywords 'words))
(direction-keywords-regexp (regexp-opt direction-keywords 'words))
(declaration-keywords-regexp (regexp-opt declaration-keywords 'words))
(logical-operators-regexp (regexp-opt logical-operators 'words))
(builtin-types-regexp (regexp-opt builtin-types 'words)))
`(
;; Documentation blocks: doc /* ... */
("\\<doc\\>\\s-*\\(/\\*\\(?:.\\|\n\\)*?\\*/\\)"
(0 font-lock-doc-face))
;; Multi-line comments /* ... */
("/\\*\\(?:.\\|\n\\)*?\\*/" . font-lock-comment-face)
;; Single-line comments //
("//.*$" . font-lock-comment-face)
;; Package and namespace keywords
(,package-keywords-regexp . font-lock-keyword-face)
;; Definition keywords
(,definition-keywords-regexp . font-lock-keyword-face)
;; Behavioral keywords
(,behavioral-keywords-regexp . font-lock-keyword-face)
;; Relationship keywords
(,relationship-keywords-regexp . font-lock-keyword-face)
;; Direction keywords
(,direction-keywords-regexp . font-lock-builtin-face)
;; Declaration keywords
(,declaration-keywords-regexp . font-lock-constant-face)
;; Logical operators
(,logical-operators-regexp . font-lock-builtin-face)
;; Built-in types
(,builtin-types-regexp . font-lock-type-face)
;; Definition type names: "part def Vehicle" - Vehicle is colored
;; Optimized: Use pre-compiled regexp
(,(concat def-types-regexp "\\s-+def\\s-+\\([A-Za-z_<][A-Za-z0-9_>]*\\)")
(2 font-lock-function-name-face))
;; Package names: "package SimpleVehicleModel" - SimpleVehicleModel is colored
("\\<package\\s-+\\([A-Za-z][A-Za-z0-9_]*\\)" 1 font-lock-function-name-face)
;; Instance/property names with typing: "attribute mass :", "port x :"
("\\<\\(part\\|attribute\\|ref\\|port\\|item\\)\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)\\s-*:"
(2 font-lock-variable-name-face))
;; State usages: "state normal;", "state healthStates {"
("\\<state\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)\\s-*[{;]"
(1 font-lock-variable-name-face))
;; Transition definitions: "transition normal_To_maintenance"
("\\<transition\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)"
(1 font-lock-variable-name-face))
;; Action usages after entry/exit: "entry action initial"
("\\<\\(entry\\|exit\\)\\s-+action\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)"
(2 font-lock-variable-name-face))
;; Parameters with item: "in item ignitionCmd"
("\\<\\(in\\|out\\|inout\\)\\s-+item\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)"
(2 font-lock-variable-name-face))
;; Parameters without item: "out temp;"
("\\<\\(in\\|out\\|inout\\)\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)\\s-*[;:]"
(2 font-lock-variable-name-face))
;; Type references after : (not :> or :>>): ": Real", ": Time::DateTime"
;; Optimized: Simpler pattern without complex lookbehind
("\\(?:^\\|\\s-\\):\\s-*\\([A-Z][A-Za-z0-9_:]*\\)" 1 font-lock-type-face)
;; Operators: :> (specializes), :>> (redefines), :: (qualified name), ~ (conjugate)
(":\\(>>\\|>\\)" . font-lock-keyword-face)
("::" . font-lock-keyword-face)
("~" . font-lock-keyword-face)
;; Multiplicity: [0..1], [0..*], [1], etc.
("\\[\\([0-9]+\\)\\.\\.\\([0-9*]+\\)\\]" . font-lock-constant-face)
("\\[\\([0-9*]+\\)\\]" . font-lock-constant-face)
;; Single-quoted identifiers (SysML v2 quoted names)
("'[^']*'" . font-lock-constant-face)
;; String literals
("\"[^\"]*\"" . font-lock-string-face)
;; Numeric literals (not part of identifiers like Wheel_1)
;; Use Emacs word boundaries for more efficient matching
("\\<\\([0-9]+\\(?:\\.[0-9]+\\)?\\)\\>" 1 font-lock-constant-face)
;; Boolean literals
("\\<\\(true\\|false\\)\\>" . font-lock-constant-face)
;; Metadata tags: #logical, #physical
("#\\(logical\\|physical\\)" . font-lock-preprocessor-face)
;; Annotations: @MetadataName
("@\\([A-Za-z][A-Za-z0-9_]*\\)" 1 font-lock-preprocessor-face))))
"Keyword highlighting for SysML mode.")
;; Syntax table
(defvar sysml-mode-syntax-table
(let ((st (make-syntax-table)))
;; C-style comments
(modify-syntax-entry ?/ ". 124b" st)
(modify-syntax-entry ?* ". 23" st)
(modify-syntax-entry ?\n "> b" st)
;; Strings - only double quotes
;; Single quotes are used for quoted names in SysML, not strings
(modify-syntax-entry ?\" "\"" st)
(modify-syntax-entry ?' "w" st) ; Word constituent for quoted names
;; Operators
(modify-syntax-entry ?: "." st)
(modify-syntax-entry ?> "." st)
(modify-syntax-entry ?< "." st)
(modify-syntax-entry ?= "." st)
;; Parentheses and brackets
(modify-syntax-entry ?\( "()" st)
(modify-syntax-entry ?\) ")(" st)
(modify-syntax-entry ?\[ "(]" st)
(modify-syntax-entry ?\] ")[" st)
(modify-syntax-entry ?\{ "(}" st)
(modify-syntax-entry ?\} "){" st)
st)
"Syntax table for SysML mode.")
;; Indentation
(defun sysml-indent-line ()
"Indent current line as SysML code.
Handles brace-based indentation, attribute declarations, and
continuation lines."
(interactive)
(let ((indent-level 0)
(pos (- (point-max) (point))))
(save-excursion
(beginning-of-line)
(let* ((ppss (syntax-ppss))
(depth (nth 0 ppss)) ; Get paren/brace depth
(in-string (nth 3 ppss)) ; Check if in string
(in-comment (nth 4 ppss)) ; Check if in comment
(current-line-empty (looking-at "^[ \t]*$")))
(unless (or in-string in-comment)
;; Calculate base indentation from nesting depth
(setq indent-level (* (or depth 0) tab-width))
;; Handle special cases
(cond
;; Closing brace on current line
((looking-at "^[ \t]*}")
(setq indent-level (max 0 (- indent-level tab-width))))
;; After attribute/port/part declaration with colon
((and (not (bobp))
(save-excursion
(forward-line -1)
(looking-at ".*\\(attribute\\|port\\|part\\|ref\\|item\\).*:[ \t]*$")))
(setq indent-level (+ indent-level tab-width)))
;; After state/transition/action keywords
((and (not (bobp))
(save-excursion
(forward-line -1)
(looking-at ".*\\(state\\|transition\\|action\\|constraint\\).*{[ \t]*$")))
nil) ; Keep calculated indent
;; Continuation after semicolon or comma
((and (not (bobp))
(not current-line-empty)
(save-excursion
(forward-line -1)
(not (looking-at ".*[{};][ \t]*$"))))
;; Check if this looks like a continuation
(save-excursion
(forward-line -1)
(when (looking-at ".*[,:=][ \t]*$")
(setq indent-level (+ indent-level tab-width)))))))))
;; Apply the indentation
(indent-line-to indent-level)
;; Restore point position relative to end of buffer
(when (> (- (point-max) pos) (point))
(goto-char (- (point-max) pos)))))
;; Imenu support for code navigation
(defconst sysml-imenu-generic-expression
'(("Packages" "^\\s-*package\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Parts" "^\\s-*part\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Attributes" "^\\s-*attribute\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Items" "^\\s-*item\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Ports" "^\\s-*port\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Actions" "^\\s-*action\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("States" "^\\s-*state\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Requirements" "^\\s-*requirement\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Constraints" "^\\s-*constraint\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Connections" "^\\s-*connection\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Interfaces" "^\\s-*interface\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Allocations" "^\\s-*allocation\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Use Cases" "^\\s-*use\\s-+case\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Calculations" "^\\s-*calc\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Analyses" "^\\s-*analysis\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Views" "^\\s-*view\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Viewpoints" "^\\s-*viewpoint\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1)
("Enumerations" "^\\s-*enum\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)" 1))
"Imenu expressions for SysML mode.
Provides menu-based navigation to all major definition types.")
;; Which-function support
(defun sysml-which-function ()
"Return current function name for which-function-mode.
Returns the name of the current SysML definition (part, action, state, etc.)."
(save-excursion
(let ((case-fold-search nil))
;; Search backward for any definition
(when (re-search-backward
(concat "^\\s-*"
"\\(" ; Group 1: the type
"\\(?:part\\|attribute\\|item\\|port\\|action\\|state\\|"
"requirement\\|constraint\\|connection\\|interface\\|"
"allocation\\|verification\\|use case\\|calc\\|analysis\\|"
"concern\\|viewpoint\\|view\\|metadata\\|enum\\)\\s-+def\\|"
"package"
"\\)"
"\\s-+"
"\\([A-Za-z_][A-Za-z0-9_]*\\)") ; Group 2: the name
nil t)
(let ((type (match-string 1))
(name (match-string 2)))
;; Ensure name is not nil before formatting
(when name
(if (and type (string-match "def$" type))
(format "%s %s" (replace-regexp-in-string "\\s-+def$" "" type) name)
name)))))))
;; Electric pairs configuration
(defvar sysml-mode-electric-pairs
'((?{ . ?}) ; Braces for blocks
(?\[ . ?\]) ; Brackets for multiplicity
(?\( . ?\)) ; Parentheses for expressions
(?\" . ?\") ; Double quotes for strings
(?< . ?>)) ; Angle brackets for generics
"Electric pairs for SysML mode.
Automatically inserts matching closing delimiters.")
;; Fill paragraph function - only handle comments
(defun sysml-fill-paragraph (&optional justify)
"Fill paragraph in SysML mode.
Only handles filling when inside comments.
Returns nil for non-comments to use default behavior.
Optional argument JUSTIFY controls text justification."
(interactive "*P")
(let* ((ppss (syntax-ppss))
(in-comment (nth 4 ppss))
(comment-start-pos (nth 8 ppss)))
(cond
;; Handle /* */ comments specially
((and in-comment comment-start-pos
(save-excursion
(goto-char comment-start-pos)
(looking-at "/\\*")))
;; Let Emacs handle the filling with proper settings
(let ((fill-prefix
(save-excursion
(goto-char comment-start-pos)
(beginning-of-line)
(skip-chars-forward " \t")
(make-string (current-column) ?\s))))
(save-excursion
(goto-char comment-start-pos)
(search-forward "*/" nil t)
(let ((comment-end (point)))
;; Use the standard fill-region-as-paragraph
(fill-region-as-paragraph comment-start-pos comment-end justify))))
t)
;; Handle // comments
((and in-comment comment-start-pos
(save-excursion
(goto-char comment-start-pos)
(looking-at "//")))
(fill-comment-paragraph justify)
t)
;; Not in a comment - don't do anything
(t nil))))
;; Prettify symbols configuration
(defcustom sysml-prettify-symbols-alist
'(;; Operators
(":>" . ?⊃) ; Specialization (subset/superset symbol)
(":>>" . ?⊇) ; Redefinition (subset-or-equal symbol)
("::" . ?∷) ; Qualified name separator (proportion symbol)
("<=" . ?≤) ; Less than or equal
(">=" . ?≥) ; Greater than or equal
("!=" . ?≠) ; Not equal
("->" . ?→) ; Arrow (for flows/transitions)
("=>" . ?⇒) ; Implies
("<->" . ?↔) ; Bidirectional
("and" . ?∧) ; Logical AND
("or" . ?∨) ; Logical OR
("not" . ?¬) ; Logical NOT
("xor" . ?⊕) ; Logical XOR
("[*]" . ?∞)) ; Unbounded multiplicity
"Alist of symbol prettifications for SysML mode.
Each element is a cons cell (STRING . CHAR) where STRING is the text
to replace and CHAR is the Unicode character to display instead.
Set to nil to disable prettification."
:type '(alist :key-type string :value-type character)
:group 'sysml)
(defcustom sysml-enable-prettify-symbols t
"Whether to enable prettify-symbols-mode in SysML buffers."
:type 'boolean
:group 'sysml)
;; Validation integration
;; Buffer-local cache for validator script location
(defvar-local sysml--cached-validator nil
"Cached path to the validator script for this buffer.")
(defun sysml-find-validator (&optional force-refresh)
"Find the validate-sysml.sh script in the current directory tree or system PATH.
First checks the custom sysml-validator-script variable, then searches
the project directory tree, and finally checks the system PATH.
The result is cached per buffer to improve performance.
Optional argument FORCE-REFRESH forces a fresh search, ignoring the cache."
(when force-refresh
(setq sysml--cached-validator nil))
(or sysml--cached-validator
(setq sysml--cached-validator
(or sysml-validator-script
(when buffer-file-name
(let ((script (locate-dominating-file
(file-name-directory buffer-file-name)
"validate-sysml.sh")))
(when script
(expand-file-name "validate-sysml.sh" script))))
(executable-find "validate-sysml.sh")))))
(defun sysml-clear-validator-cache ()
"Clear the cached validator script location for the current buffer.
Useful if the validator script has been moved or added."
(interactive)
(setq sysml--cached-validator nil)
(message "Validator cache cleared. Next validation will search for the script."))
(defun sysml-validate-buffer ()
"Validate the current SysML buffer using validate-sysml.sh.
The validator can validate either a single file or a directory.
Prompts to save the buffer if it has unsaved changes."
(interactive)
(unless buffer-file-name
(error "Buffer must be visiting a file to validate"))
(when (buffer-modified-p)
(when (y-or-n-p (format "Save %s before validation? " (buffer-name)))
(save-buffer)))
(let ((validator-script (sysml-find-validator)))
(cond
((not validator-script)
(message "SysML validator script not found. Set sysml-validator-script or ensure validate-sysml.sh is in project or PATH."))
((not (file-exists-p validator-script))
(error "Validator script does not exist: %s" validator-script))
((not (file-executable-p validator-script))
(error "Validator script is not executable: %s" validator-script))
(t
(let ((default-directory (file-name-directory validator-script)))
(compile (format "%s %s" validator-script
(shell-quote-argument buffer-file-name))))))))
(defun sysml-validate-on-save ()
"Validate SysML file on save if enabled."
(when (and sysml-validate-on-save
(eq major-mode 'sysml-mode))
(sysml-validate-buffer)))
;; Project-wide symbol search
(defun sysml-find-definition-at-point ()
"Find the definition of the symbol at point across the project.
Searches for package, def, or usage declarations of the symbol."
(interactive)
(let ((symbol (thing-at-point 'symbol t)))
(unless symbol
(error "No symbol at point"))
(let ((search-pattern (format "\\b(package|def|%s)\\s+%s\\b"
(regexp-opt '("part" "attribute" "item" "port"
"action" "state" "requirement" "constraint"))
(regexp-quote symbol))))
(grep-find (format "find . -name '*.sysml' -o -name '*.sysmli' | xargs grep -n -E '%s'"
search-pattern)))))
(defun sysml-find-references ()
"Find all references to the symbol at point across the project.
Searches for any usage of the symbol name."
(interactive)
(let ((symbol (thing-at-point 'symbol t)))
(unless symbol
(error "No symbol at point"))
(grep-find (format "find . -name '*.sysml' -o -name '*.sysmli' | xargs grep -n -w '%s'"
(regexp-quote symbol)))))
(defun sysml-list-definitions ()
"List all definitions in the current project.
Shows packages, parts, attributes, and other definition types."
(interactive)
(let ((pattern "^\\s-*(package|.*\\s+def)\\s+\\w+"))
(grep-find (format "find . -name '*.sysml' -o -name '*.sysmli' | xargs grep -n -E '%s'"
pattern))))
;; Completion support
(defvar sysml-all-keywords nil
"List of all SysML keywords for completion.
This is populated when the mode is loaded.")
(defun sysml-build-keyword-list ()
"Build the complete list of SysML keywords for completion."
(append
;; All keyword categories
'("package" "import" "private" "public" "standard" "library"
"def" "part" "attribute" "item" "port" "action" "state"
"requirement" "constraint" "connection" "interface" "allocation"
"verification" "use" "case" "calc" "analysis" "concern"
"viewpoint" "view" "metadata" "individual" "snapshot" "timeslice"
"enum" "variation" "variant" "stream" "message" "flow"
"succession" "feature" "abstract" "readonly" "derived" "end"
"binding" "exhibit" "perform" "then" "first" "accept" "send" "via"
"entry" "exit" "do" "transition" "if" "else" "while" "for"
"return" "assert" "assume" "require" "fork" "join" "merge"
"decide" "loop" "parallel" "when" "at" "new"
"specializes" "subsets" "redefines" "references" "conjugate"
"chains" "inverse" "composite" "bind" "connect" "satisfy" "verify"
"subject" "objective" "from" "to" "about" "actor" "stakeholder"
"in" "out" "inout" "and" "or" "xor" "not" "implies"
"doc" "comment" "language" "inv" "pre" "post" "body" "result"
"filter" "rendering" "expose" "ref" "all" "that" "self"
"featured" "by" "typing" "chaining" "inverting" "owned"
"member" "multiplicity" "ordered" "nonunique" "sequence"
"alias" "occurrence" "meta" "true" "false")))
;; Initialize the keyword list
(setq sysml-all-keywords (sysml-build-keyword-list))
(defun sysml-collect-buffer-symbols ()
"Collect all defined symbols in the current buffer for completion."
(let ((symbols '()))
(save-excursion
(goto-char (point-min))
;; Find all definitions
(while (re-search-forward
(concat "\\(?:"
"package\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)\\|"
"\\(?:part\\|attribute\\|item\\|port\\|action\\|state\\|"
"requirement\\|constraint\\|enum\\)\\s-+def\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)\\|"
"\\(?:part\\|attribute\\|ref\\|port\\|item\\)\\s-+\\([A-Za-z_][A-Za-z0-9_]*\\)\\s-*:"
"\\)")
nil t)
(let ((match (or (match-string 1) (match-string 2) (match-string 3))))
(when (and match (not (member match symbols)))
(push match symbols)))))
symbols))
(defun sysml-completion-at-point ()
"Completion function for `completion-at-point-functions'.
Provides completion for SysML keywords and defined symbols."
(let ((bounds (bounds-of-thing-at-point 'symbol)))
(when bounds
(let* ((start (car bounds))
(end (cdr bounds))
(prefix (buffer-substring-no-properties start end))
;; Combine keywords and buffer symbols
(candidates (append sysml-all-keywords
(sysml-collect-buffer-symbols))))
(list start end
(completion-table-dynamic
(lambda (_)
(cl-remove-if-not
(lambda (c) (string-prefix-p prefix c t))
candidates)))
:exclusive 'no
:annotation-function
(lambda (s)
(cond
((member s sysml-all-keywords) " <keyword>")
(t " <symbol>"))))))))
;; Documentation support
(defconst sysml-eldoc-keywords
'(;; Operators
(":>" . "specialization operator - inherit from supertype")
(":>>" . "redefinition operator - redefine inherited feature")
("::" . "qualified name separator - Package::Type")
;; Package keywords
("package" . "declares a namespace container")
("import" . "imports elements from another package")
("private" . "visibility modifier - accessible only within package")
("public" . "visibility modifier - accessible from outside package")
("standard" . "marks as part of standard library")
("library" . "marks as library package")
;; Definition keywords
("part" . "structural element definition or usage")
("def" . "defines a type")
("attribute" . "data value definition or usage")
("ref" . "reference to another element (not composition)")
("abstract" . "cannot be instantiated directly")
;; Documentation
("doc" . "documentation comment block")
;; Common patterns
("part def" . "defines a structural component type (specializes Parts::Part)")
("attribute def" . "defines a data type (specializes Base::DataValue)")
("ref system" . "reference to external system (not composition)"))
"ElDoc documentation for SysML keywords and operators.")
(defun sysml-eldoc-function ()
"Provide ElDoc documentation for SysML keywords at point."
(let* ((word (thing-at-point 'symbol t))
;; Also check for operators
(operator (save-excursion
(skip-syntax-backward "^w")
(buffer-substring-no-properties
(point)
(min (+ (point) 3) (point-max)))))
(preceding (save-excursion
(ignore-errors
(backward-word)
(thing-at-point 'symbol t))))
(two-word (when (and preceding word)
(concat preceding " " word)))
(doc nil))
;; Try different lookups
(setq doc (or
;; Try two-word combination
(and two-word (cdr (assoc two-word sysml-eldoc-keywords)))
;; Try word
(and word (cdr (assoc word sysml-eldoc-keywords)))
;; Try operator
(cdr (assoc operator sysml-eldoc-keywords))
;; Try shorter operator
(cdr (assoc (substring operator 0 (min 2 (length operator)))
sysml-eldoc-keywords))))
doc))
(defun sysml-quick-reference ()
"Display a quick reference guide for SysML v2 syntax."
(interactive)
(let ((buf (get-buffer-create "*SysML Quick Reference*")))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(insert "SysML v2 Quick Reference\n")
(insert "========================\n\n")
(insert "Operators\n")
(insert "---------\n")
(insert " :> - Specialization (inheritance)\n")
(insert " Example: part def Car :> Vehicle\n\n")
(insert " :>> - Redefinition (override inherited feature)\n")
(insert " Example: attribute :>> name = \"MyName\"\n\n")
(insert " :: - Qualified name separator\n")
(insert " Example: ScalarValues::String\n\n")
(insert "Common Patterns\n")
(insert "---------------\n")
(insert "Package declaration:\n")
(insert " package MyPackage {\n")
(insert " private import ScalarValues::*;\n")
(insert " }\n\n")
(insert "Part definition:\n")
(insert " part def MyComponent {\n")
(insert " attribute name : String;\n")
(insert " ref system : System[0..1];\n")
(insert " }\n\n")
(insert "Part usage (instance):\n")
(insert " part myInstance : MyComponent {\n")
(insert " attribute :>> name = \"Instance1\";\n")
(insert " }\n\n")
(insert "Attribute definition:\n")
(insert " attribute def Region :> String;\n\n")
(insert "Multi-valued features:\n")
(insert " ref :>> tools = (tool1, tool2, tool3);\n\n")
(insert "Documentation\n")
(insert "-------------\n")
(insert " doc\n")
(insert " /*\n")
(insert " * Documentation comment\n")
(insert " */\n\n")
(insert "Multiplicity\n")
(insert "------------\n")
(insert " [0..1] - Zero or one\n")
(insert " [1] - Exactly one\n")
(insert " [0..*] - Zero or more\n")
(insert " [1..*] - One or more\n\n")
(insert "Key Bindings\n")
(insert "------------\n")
(insert " C-c C-v - Validate current file\n")
(insert " C-c C-h - Show this quick reference\n\n")
(insert "Authoritative Documentation\n")
(insert "---------------------------\n")
(insert "OMG SysML v2 Specification:\n")
(insert " https://www.omg.org/spec/SysML/2.0/\n\n")
(insert "Normative Example Model:\n")
(insert " https://www.omg.org/cgi-bin/doc?ptc/25-04-31.sysml\n\n")
(insert "SysML v2 Release (specifications and examples):\n")
(insert " https://github.com/Systems-Modeling/SysML-v2-Release\n\n"))
(help-mode)
(goto-char (point-min)))
(display-buffer buf)))
;; Spell checking support
(defun sysml-flyspell-verify ()
"Function to verify if flyspell should check word at point.
Only spell-check strings and comments, not code."
(let ((face (get-text-property (point) 'face)))
(or
;; Check strings
(eq face 'font-lock-string-face)
;; Check comments
(eq face 'font-lock-comment-face)
;; Check documentation blocks
(eq face 'font-lock-doc-face)
;; Also handle when face is a list
(and (listp face)
(or (memq 'font-lock-string-face face)
(memq 'font-lock-comment-face face)
(memq 'font-lock-doc-face face))))))
(defun sysml-spell-check-buffer ()
"Spell check comments and strings in SysML buffer.
This is a SysML-specific wrapper around ispell-comments-and-strings
that ensures only comments and strings are checked, not code."
(interactive)
(cond
;; First check if spell checking executables are available
((not (or (executable-find "ispell")
(executable-find "aspell")
(executable-find "hunspell")))
(error "No spell checker found. Please install ispell, aspell, or hunspell"))
;; Then check if the Emacs ispell library is loaded
((not (fboundp 'ispell-comments-and-strings))
(error "ispell.el is not loaded. Try M-x load-library RET ispell RET"))
;; All checks passed, proceed with spell checking
(t
(condition-case err
(ispell-comments-and-strings)
(error
(error "Spell checking failed: %s" (error-message-string err)))))))
;; Template insertion skeletons
;; Following html-mode convention with C-c C-c prefix for structured insertions
;; Helper functions for context-aware templates
(defun sysml-guess-package-name ()
"Guess package name from directory structure or file name.
Returns the directory name if it starts with a capital letter,
otherwise returns the base name of the current file."
(when buffer-file-name
(let* ((dir-name (file-name-nondirectory
(directory-file-name
(file-name-directory buffer-file-name))))
(file-base (file-name-sans-extension
(file-name-nondirectory buffer-file-name))))
(cond
;; Use directory name if it looks like a package name
((and dir-name (string-match "^[A-Z]" dir-name))
dir-name)
;; Otherwise use file name
((and file-base (string-match "^[A-Z]" file-base))
file-base)
;; Default to nil to prompt user
(t nil)))))
(defun sysml-capitalize-first (str)
"Capitalize the first letter of STR."
(if (and str (> (length str) 0))
(concat (upcase (substring str 0 1))
(substring str 1))
str))
(define-skeleton sysml-insert-package
"Insert a SysML package declaration with smart defaults."
(or (sysml-guess-package-name) "Package name: ")
"package " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-part-def
"Insert a SysML part definition."
"Part name: "
"part def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-attribute-def
"Insert a SysML attribute definition with common base types."
"Attribute name: "
"attribute def " str " :> "
(completing-read "Base type: "
'("String" "Real" "Integer" "Boolean" "Natural"
"Time::DateTime" "ISQ::length" "ISQ::mass"
"ISQ::time" "ISQ::temperature" "ISQ::speed"
"ISQ::acceleration" "ISQ::power" "ISQ::energy")
nil nil "String") ";")
(define-skeleton sysml-insert-item-def
"Insert a SysML item definition."
"Item name: "
"item def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-port-def
"Insert a SysML port definition."
"Port name: "
"port def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-action-def
"Insert a SysML action definition."
"Action name: "
"action def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-state-def
"Insert a SysML state definition."
"State name: "
"state def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-requirement-def
"Insert a SysML requirement definition with documentation."
"Requirement name: "
"requirement def " str " {" \n
> "doc /* " (read-string "Description: ") " */" \n
> "attribute id : String = \""
(read-string "Requirement ID (e.g., REQ-001): "
(format "REQ-%03d" (random 1000))) "\";" \n
> "attribute text : String = \"" (read-string "Requirement text: ") "\";" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-constraint-def
"Insert a SysML constraint definition."
"Constraint name: "
"constraint def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-connection-def
"Insert a SysML connection definition."
"Connection name: "
"connection def " str " {" \n
> "end source : " (skeleton-read "Source type: ") ";" \n
> "end target : " (skeleton-read "Target type: ") ";" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-interface-def
"Insert a SysML interface definition."
"Interface name: "
"interface def " str " {" \n
> "end p1 : " (skeleton-read "Port 1 type: ") ";" \n
> "end p2 : " (skeleton-read "Port 2 type: ") ";" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-allocation-def
"Insert a SysML allocation definition."
"Allocation name: "
"allocation def " str " {" \n
> "end source;" \n
> "end target;" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-verification-def
"Insert a SysML verification definition."
"Verification name: "
"verification def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-use-case-def
"Insert a SysML use case definition."
"Use case name: "
"use case def " str " {" \n
> "doc /* " (skeleton-read "Description: ") " */" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-calc-def
"Insert a SysML calculation definition."
"Calculation name: "
"calc def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-analysis-def
"Insert a SysML analysis definition."
"Analysis name: "
"analysis def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-concern-def
"Insert a SysML concern definition."
"Concern name: "
"concern def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-viewpoint-def
"Insert a SysML viewpoint definition."
"Viewpoint name: "
"viewpoint def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-view-def
"Insert a SysML view definition."
"View name: "
"view def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-metadata-def
"Insert a SysML metadata definition."
"Metadata name: "
"metadata def " str " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-individual-def
"Insert a SysML individual definition."
"Individual name: "
"individual def " str " :> "
(skeleton-read "Type: ") ";")
(define-skeleton sysml-insert-enum-def
"Insert a SysML enumeration definition."
"Enum name: "
"enum def " str " {" \n
> (skeleton-read "First value: ") ";" \n
> _ \n
"}" >)
;; Instance templates (usages)
(define-skeleton sysml-insert-part-usage
"Insert a SysML part usage (instance)."
"Part name: "
"part " str " : "
(skeleton-read "Type: ") " {" \n
> _ \n
"}" >)
(define-skeleton sysml-insert-attribute-usage
"Insert a SysML attribute usage (instance)."
"Attribute name: "
"attribute " str " : "
(skeleton-read "Type: ") ";")
;; Mode map with template insertion keybindings
(defvar sysml-mode-map
(let ((map (make-sparse-keymap))
(prefix-map (make-sparse-keymap)))
;; Core commands
(define-key map (kbd "C-c C-v") 'sysml-validate-buffer)