summaryrefslogtreecommitdiff
path: root/lisp/progmodes/f90.el
blob: aa6de50b3aa04479a088b3b3ab0ce98ea12a2d67 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
;;; f90.el --- Fortran-90 mode (free format)

;; Copyright (C) 1995, 1996 Free Software Foundation, Inc.

;; Author: Torbj\"orn Einarsson <T.Einarsson@clab.ericsson.se>
;; Created: Sep. 21, 1995
;; Keywords: fortran, f90, languages

;; This file is part of GNU Emacs.

;; GNU Emacs 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, or (at your option)
;; any later version.

;; GNU Emacs 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., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

;; Smart mode for editing F90 programs in FREE FORMAT.
;; Knows about continuation lines, named structured statements, and other
;; new features in F90 including HPF (High Performance Fortran) structures.
;; The basic feature is to provide an accurate indentation of F90 programs.
;; In addition, there are many more features like automatic matching of all
;; end statements, an auto-fill function to break long lines, a join-lines
;; function which joins continued lines etc etc.
;;  To facilitate typing, a fairly complete list of abbreviations is provided.
;;    For example, `i is short-hand for integer (if abbrev-mode is on).

;; There are two separate features for highlighting the code.
;;   1) Upcasing or capitalizing of all keywords.
;;   2) Colors/fonts using font-lock-mode. (only when using X-windows)
;;  Automatic upcase of downcase of keywords is controlled by the parameter
;;  f90-auto-keyword-case.

;; The indentations of lines starting with ! is determined by the first of the
;; following matches (the values in the left column are the default values):

;; start-string/regexp  indent         variable holding start-string/regexp
;;    !!!                  0
;;    !hpf\\$ (re)         0              f90-directive-comment-re
;;    !!$                  0              f90-comment-region
;;    !      (re)        as code          f90-indented-comment-re
;;    default            comment-column

;; Ex: Here is the result of 3 different settings of f90-indented-comment-re
;;     f90-indented-comment-re  !-indentation      !!-indentation
;;          !                    as code             as code
;;          !!                   comment-column      as code
;;          ![^!]                as code             comment-column
;; Trailing comments are indented to comment-column with indent-for-comment M-;
;; f90-comment-region (C-c;) toggles insertion of f90-comment-region in region.

;; One common convention for free vs. fixed format is that free-format files
;; have the ending .f90 while the fixed format files have the ending .f. 
;; To make f90-mode work, put this file in, for example, your directory
;;  ~/lisp, and be sure that you have the following in your .emacs-file
;;     (setq load-path (append load-path '("~/lisp")))
;;     (autoload 'f90-mode "f90"
;;       "Major mode for editing Fortran 90 code in free format." t)
;;     (setq auto-mode-alist (append auto-mode-alist 
;;                           (list '("\\.f90$" . f90-mode))))
;; Once you have entered f90-mode, you may get more info by using
;; the command describe-mode (C-h m). For online help describing various
;; functions use  C-h f <Name of function you want described>

;; To customize the f90-mode for your taste, use, for example:
;;    (you don't have to specify values for all the parameters below)
;;(setq f90-mode-hook
;;      '(lambda () (setq f90-do-indent 3
;;                        f90-if-indent 3
;;                        f90-type-indent 3
;;                        f90-program-indent 2
;;                        f90-continuation-indent 5
;;                        f90-comment-region "!!$"
;;                        f90-directive-comment-re "!hpf\\$"
;;                        f90-indented-comment-re "!"
;;                        f90-break-delimiters "[-+\\*/,><=% \t]"
;;                        f90-break-before-delimiters t
;;                        f90-beginning-ampersand t
;;                        f90-smart-end 'blink
;;                        f90-auto-keyword-case nil
;;                        f90-leave-line-no  nil
;;                        f90-startup-message t
;;                        indent-tabs-mode nil
;;                  )
;;       ;;The rest is not default.
;;       (abbrev-mode 1)             ; turn on abbreviation mode
;;       (f90-auto-fill-mode 1)      ; turn on auto-filling
;;       (turn-on-font-lock)         ; for highlighting
;;       (if f90-auto-keyword-case   ; change case of all keywords on startup
;;           (f90-change-keywords f90-auto-keyword-case))
;;	 ))
;; in your .emacs file (the shown values are the defaults). You can also
;; change the values of the lists f90-keywords etc.
;; The auto-fill and abbreviation minor modes are accessible from the menu,
;; or by using M-x f90-auto-fill-mode and M-x abbrev-mode, respectively.

;; Remarks
;; 1) Line numbers are by default left-justified. If f90-leave-line-no is
;;    non-nil, the line numbers are never touched.
;; 2) Multi-; statements like > do i=1,20 ; j=j+i ; end do < are not handled
;;    correctly, but I imagine them to be rare.
;; 3) Regexps for hilit19 are no longer supported.
;; 4) For FIXED FORMAT code, use the ordinary fortran mode.
;; 5) This mode does not work under emacs-18.x.
;; 6) Preprocessor directives, i.e., lines starting with # are left-justified
;;    and are untouched by all case-changing commands. There is, at present, no
;;    mechanism for treating multi-line directives (continued by \ ).
;; 7) f77 do-loops do 10 i=.. ; ; 10 continue are not correctly indented.
;;    You are urged to use f90-do loops (with labels if you wish).

;; List of user commands
;;   f90-previous-statement         f90-next-statement
;;   f90-beginning-of-subprogram    f90-end-of-subprogram   f90-mark-subprogram
;;   f90-comment-region
;;   f90-indent-line                f90-indent-new-line
;;   f90-indent-region    (can be called by calling indent-region)
;;   f90-indent-subprogram
;;   f90-break-line                 f90-join-lines
;;   f90-auto-fill-mode
;;   f90-fill-region
;;   f90-insert-end
;;   f90-upcase-keywords            f90-upcase-region-keywords
;;   f90-downcase-keywords          f90-downcase-region-keywords
;;   f90-capitalize-keywords        f90-capitalize-region-keywords

;; Thanks to all the people who have tested the mode. Special thanks to Jens
;; Bloch Helmers for encouraging me to write this code, for creative
;; suggestions as well as for the lists of hpf-commands.
;; Also thanks to the authors of the fortran and pascal modes, on which some
;; of this code is built.

;;; Code:

(defconst bug-f90-mode "T.Einarsson@clab.ericsson.se"
  "Address of mailing list for F90 mode bugs.")

;; User options
(defvar f90-do-indent 3
  "*Extra indentation applied to DO blocks.")

(defvar f90-if-indent 3
  "*Extra indentation applied to IF, SELECT CASE, WHERE and FORALL blocks.")

(defvar f90-type-indent 3
  "*Extra indentation applied to TYPE, INTERFACE and BLOCK DATA blocks.")

(defvar f90-program-indent 2
  "*Extra indentation applied to PROGRAM/MODULE/SUBROUTINE/FUNCTION blocks.")

(defvar f90-continuation-indent 5
  "*Extra indentation applied to F90 continuation lines.")

(defvar f90-comment-region "!!$"
  "*String inserted by \\[f90-comment-region]\
 at start of each line in region.")

(defvar f90-indented-comment-re "!"
  "*Regexp saying which comments to be indented like code.")

(defvar f90-directive-comment-re "!hpf\\$"
  "*Regexp of comment-like directive like \"!HPF\\\\$\", not to be indented.")

(defvar f90-beginning-ampersand t
  "*t makes automatic insertion of \& at beginning of continuation line.")

(defvar f90-smart-end 'blink
  "*From an END statement, check and fill the end using matching block start.
Allowed values are 'blink, 'no-blink, and nil, which determine
whether to blink the matching beginning.")

(defvar f90-break-delimiters "[-+\\*/><=,% \t]"
  "*Regexp holding list of delimiters at which lines may be broken.")

(defvar f90-break-before-delimiters t
  "*Non-nil causes `f90-do-auto-fill' to break lines before delimiters.")

(defvar f90-auto-keyword-case nil
  "*Automatic case conversion of keywords.
  The options are 'downcase-word, 'upcase-word, 'capitalize-word and nil")

(defvar f90-auto-hilit19 t
  "*Automatic highlight of line at every indent or newline (for hilit19).")

(defvar f90-leave-line-no nil
  "*If nil, left-justify linenumbers.")

(defvar f90-startup-message t
  "*Non-nil displays a startup message when F90 mode is first called.")

(defconst f90-keywords-re
  ;;("allocate" "allocatable" "assign" "assignment" "backspace" "block"
  ;;"call" "case" "character" "close" "common" "complex" "contains"
  ;;"continue" "cycle" "data" "deallocate" "dimension" "do" "double" "else"
  ;;"elseif" "elsewhere" "end" "enddo" "endfile" "endif" "entry" "equivalence"
  ;;"exit" "external" "forall" "format" "function" "goto" "if" "implicit"
  ;;"include" "inquire" "integer" "intent" "interface" "intrinsic" "logical"
  ;;"module" "namelist" "none" "nullify" "only" "open" "optional" "parameter"
  ;;"pause" "pointer" "precision" "print" "private" "procedure" "program"
  ;;"public" "read" "real" "recursive" "return" "rewind" "save" "select"
  ;;"sequence" "stop" "subroutine" "target" "then" "type" "use" "where"
  ;;"while" "write")
  (concat
   "\\<\\(a\\(llocat\\(able\\|e\\)\\|ssign\\(\\|ment\\)\\)\\|b\\(ackspace\\|"
   "lock\\)\\|c\\(a\\(ll\\|se\\)\\|haracter\\|lose\\|o\\(m\\(mon\\|plex\\)\\|"
   "nt\\(ains\\|inue\\)\\)\\|ycle\\)\\|d\\(ata\\|eallocate\\|imension\\|"
   "o\\(\\|uble\\)\\)\\|e\\(lse\\(\\|if\\|where\\)\\|n\\(d\\(\\|do\\|file\\|"
   "if\\)\\|try\\)\\|quivalence\\|x\\(it\\|ternal\\)\\)\\|f\\(or\\(all\\|"
   "mat\\)\\|unction\\)\\|goto\\|i\\(f\\|mplicit\\|n\\(clude\\|quire\\|t\\("
   "e\\(ger\\|nt\\|rface\\)\\|rinsic\\)\\)\\)\\|logical\\|module\\|n\\("
   "amelist\\|one\\|ullify\\)\\|o\\(nly\\|p\\(en\\|tional\\)\\)\\|p\\(a\\("
   "rameter\\|use\\)\\|ointer\\|r\\(ecision\\|i\\(nt\\|vate\\)\\|o\\("
   "cedure\\|gram\\)\\)\\|ublic\\)\\|re\\(a[dl]\\|cursive\\|turn\\|wind\\)\\|"
   "s\\(ave\\|e\\(lect\\|quence\\)\\|top\\|ubroutine\\)\\|t\\(arget\\|hen\\|"
   "ype\\)\\|use\\|w\\(h\\(ere\\|ile\\)\\|rite\\)\\)\\>")
  "Regexp for F90 keywords.")

(defconst f90-keywords-level-3-re
 ;; ("allocate" "allocatable" "assign" "assignment" "backspace" "close"
 ;; "deallocate" "endfile" "entry" "equivalence" "external" "inquire" "intent"
 ;; "intrinsic" "only" "open" "optional" "parameter" "pause" "pointer" "print"
 ;; "private" "public" "read" "recursive" "rewind" "save" "select" "sequence"
 ;; "target"  "write")
  (concat
   "\\<\\(a\\(llocat\\(able\\|e\\)\\|ssign\\(\\|ment\\)\\)\\|backspace\\|"
   "close\\|deallocate\\|e\\(n\\(dfile\\|try\\)\\|quivalence\\|xternal\\)\\|"
   "in\\(quire\\|t\\(ent\\|rinsic\\)\\)\\|o\\(nly\\|p\\(en\\|tional\\)\\)\\|"
   "p\\(a\\(rameter\\|use\\)\\|ointer\\|ri\\(nt\\|vate\\)\\|ublic\\)\\|re\\("
   "ad\\|cursive\\|wind\\)\\|s\\(ave\\|e\\(lect\\|quence\\)\\)\\|target\\|"
   "write\\)\\>")
"Keyword-regexp for font-lock level >= 3.")


(defconst f90-procedures-re
  ;; ("abs" "achar" "acos" "adjustl" "adjustr" "aimag" "aint" "all" "allocated"
  ;; "anint" "any" "asin" "associated" "atan" "atan2" "bit_size" "btest"
  ;; "ceiling" "char" "cmplx" "conjg" "cos" "cosh" "count" "cshift"
  ;; "date_and_time" "dble" "digits" "dim" "dot_product" "dprod" "eoshift"
  ;; "epsilon" "exp" "exponent" "floor" "fraction" "huge" "iachar" "iand"
  ;; "ibclr" "ibits" "ibset" "ichar" "ieor" "index" "int" "ior" "ishft"
  ;; "ishftc" "kind" "lbound" "len" "len_trim" "lge" "lgt" "lle" "llt" "log"
  ;; "logical" "log10" "matmul" "max" "maxexponent" "maxloc" "maxval" "merge"
  ;; "min" "minexponent" "minloc" "minval" "mod" "modulo" "mvbits" "nearest"
  ;; "nint" "not" "pack" "precision" "present" "product" "radix"
  ;; "random_number" "random_seed" "range" "real" "repeat" "reshape"
  ;; "rrspacing" "scale" "scan" "selected_int_kind" "selected_real_kind"
  ;; "set_exponent" "shape" "sign" "sin" "sinh" "size" "spacing" "spread"
  ;; "sqrt" "sum" "system_clock" "tan" "tanh" "tiny" "transfer" "transpose"
  ;; "trim" "ubound" "unpack" "verify")
  ;; A left parenthesis to avoid highlighting non-procedures.
  ;; Real is taken out here to avoid highlighting declarations.
  (concat
   "\\<\\(a\\(bs\\|c\\(har\\|os\\)\\|djust[lr]\\|i\\(mag\\|nt\\)\\|ll\\(\\|"
   "ocated\\)\\|n\\(int\\|y\\)\\|s\\(in\\|sociated\\)\\|tan2?\\)\\|b\\("
   "it_size\\|test\\)\\|c\\(eiling\\|har\\|mplx\\|o\\(njg\\|sh?\\|unt\\)\\|"
   "shift\\)\\|d\\(ate_and_time\\|ble\\|i\\(gits\\|m\\)\\|ot_product\\|prod"
   "\\)\\|e\\(oshift\\|psilon\\|xp\\(\\|onent\\)\\)\\|f\\(loor\\|"
   "raction\\)\\|huge\\|i\\(a\\(char\\|nd\\)\\|b\\(clr\\|its\\|set\\)\\|"
   "char\\|eor\\|n\\(dex\\|t\\)\\|or\\|shftc?\\)\\|kind\\|l\\(bound\\|"
   "en\\(\\|_trim\\)\\|g[et]\\|l[et]\\|og\\(\\|10\\|ical\\)\\)\\|m\\(a\\("
   "tmul\\|x\\(\\|exponent\\|loc\\|val\\)\\)\\|erge\\|in\\(\\|exponent\\|"
   "loc\\|val\\)\\|od\\(\\|ulo\\)\\|vbits\\)\\|n\\(earest\\|int\\|ot\\)\\|"
   "p\\(ack\\|r\\(e\\(cision\\|sent\\)\\|oduct\\)\\)\\|r\\(a\\(dix\\|n\\("
   "dom_\\(number\\|seed\\)\\|ge\\)\\)\\|e\\(peat\\|shape\\)\\|rspacing\\)\\|"
   "s\\(ca\\(le\\|n\\)\\|e\\(lected_\\(int_kind\\|real_kind\\)\\|"
   "t_exponent\\)\\|hape\\|i\\(gn\\|nh?\\|ze\\)\\|p\\(acing\\|read\\)\\|"
   "qrt\\|um\\|ystem_clock\\)\\|t\\(anh?\\|iny\\|r\\(ans\\(fer\\|pose\\)\\|"
   "im\\)\\)\\|u\\(bound\\|npack\\)\\|verify\\)[ \t]*(")
  "Regexp whose first part matches F90 intrinsic procedures.")

(defconst f90-operators-re
;; "and" "or" "not" "eqv" "neqv" "eq" "ne" "lt" "le" "gt" "ge" "true" "false"
 (concat
   "\\.\\(and\\|eqv?\\|false\\|g[et]\\|l[et]\\|n\\(e\\(\\|qv\\)\\|"
   "ot\\)\\|or\\|true\\)\\.")
  "Regexp matching intrinsic operators.")

(defconst f90-hpf-keywords-re
  ;; Intrinsic procedures
  ;; ("all_prefix" "all_scatter" "all_suffix" "any_prefix" "any_scatter"
  ;; "any_suffix" "copy_prefix" "copy_scatter" "copy_suffix" "count_prefix"
  ;; "count_scatter" "count_suffix" "grade_down" "grade_up" "hpf_alignment"
  ;; "hpf_template" "hpf_distribution" "iall" "iall_prefix" "iall_scatter"
  ;; "iall_suffix" "iany" "iany_prefix" "iany_scatter" "iany_suffix" "iparity"
  ;; "iparity_prefix" "iparity_scatter" "iparity_suffix" "leadz"
  ;; "maxval_prefix" "maxval_scatter" "maxval_suffix" "minval_prefix"
  ;; "minval_scatter" "minval_suffix" "parity" "parity_prefix"
  ;; "parity_scatter" "parity_suffix" "popcnt" "poppar" "product_prefix"
  ;; "product_scatter" "product_suffix" "sum_prefix" "sum_scatter"
  ;; "sum_suffix" "ilen" "number_of_processors" "processors_shape")
  ;; Directives
  ;; ("align" "distribute" "dynamic" "inherit" "template" "processors"
  ;; "realign" "redistribute" "independent")
  ;; Keywords
  ;; ("pure" "extrinsic" "new" "with" "onto" "block" "cyclic")
  (concat
   "\\<\\(a\\(l\\(ign\\|l_\\(prefix\\|s\\(catter\\|uffix\\)\\)\\)\\|ny_\\("
   "prefix\\|s\\(catter\\|uffix\\)\\)\\)\\|block\\|c\\(o\\(py_\\(prefix\\|"
   "s\\(catter\\|uffix\\)\\)\\|unt_\\(prefix\\|s\\(catter\\|uffix\\)\\)\\)\\|"
   "yclic\\)\\|d\\(istribute\\|ynamic\\)\\|extrinsic\\|grade_\\(down\\|"
   "up\\)\\|hpf_\\(alignment\\|distribution\\|template\\)\\|i\\(a\\(ll\\(\\|"
   "_\\(prefix\\|s\\(catter\\|uffix\\)\\)\\)\\|ny\\(\\|_\\(prefix\\|s\\("
   "catter\\|uffix\\)\\)\\)\\)\\|len\\|n\\(dependent\\|herit\\)\\|parity\\(\\|"
   "_\\(prefix\\|s\\(catter\\|uffix\\)\\)\\)\\)\\|leadz\\|m\\(axval_\\("
   "prefix\\|s\\(catter\\|uffix\\)\\)\\|inval_\\(prefix\\|s\\(catter\\|"
   "uffix\\)\\)\\)\\|n\\(ew\\|umber_of_processors\\)\\|onto\\|p\\(arity\\(\\|"
   "_\\(prefix\\|s\\(catter\\|uffix\\)\\)\\)\\|op\\(cnt\\|par\\)\\|ro\\("
   "cessors\\(\\|_shape\\)\\|duct_\\(prefix\\|s\\(catter\\|uffix\\)\\)\\)\\|"
   "ure\\)\\|re\\(align\\|distribute\\)\\|sum_\\(prefix\\|s\\(catter\\|"
   "uffix\\)\\)\\|template\\|with\\)\\>")
  "Regexp for all HPF keywords, procedures and directives.")

;; Highlighting patterns

(defvar f90-font-lock-keywords-1
  (if (string-match "XEmacs" emacs-version)
      (list				; XEmacs
       '("\\<\\(end[ \t]*\\(program\\|module\\|function\\|subroutine\\|type\\)\\)\\>"
	 1 font-lock-keyword-face)
       '("\\<\\(end[ \t]*\\(program\\|module\\|function\\|subroutine\\|type\\)\\)\\>[ \t]*\\(\\sw+\\)"
	 3 font-lock-function-name-face)
       '("\\<\\(program\\|call\\|module\\|subroutine\\|function\\|use\\)\\>"
	 1 font-lock-keyword-face)
       '("\\<\\(program\\|call\\|module\\|subroutine\\|function\\|use\\)\\>[ \t]*\\(\\sw+\\)"
	 2 font-lock-function-name-face nil t)
       ;; Special highlighting of "module procedure foo-list"
       '("\\<\\(module[ \t]*procedure\\)\\>" 1 font-lock-keyword-face t)
       ;; Highlight definition of new type
       '("\\<\\(type\\)[ \t]*\\(,.*::[ \t]*\\|[ \t]+\\)\\(\\sw+\\)"
	 1 font-lock-keyword-face)
       '("\\<\\(type\\)[ \t]*\\(,.*::[ \t]*\\|[ \t]+\\)\\(\\sw+\\)"
	 3 font-lock-function-name-face)
       "\\<\\(\\(end[ \t]*\\)?\\(interface\\|block[ \t]*data\\)\\|contains\\)\\>")
    (list				; Emacs
     '("\\<\\(end[ \t]*\\(program\\|module\\|function\\|subroutine\\|type\\)\\)\\>[ \t]*\\(\\sw+\\)?"
       (1 font-lock-keyword-face) (3 font-lock-function-name-face nil t))
     '("\\<\\(program\\|call\\|module\\|subroutine\\|function\\|use\\)\\>[ \t]*\\(\\sw+\\)?"
       (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
     ;; Special highlighting of "module procedure foo-list"
     '("\\<\\(module[ \t]*procedure\\)\\>" (1 font-lock-keyword-face t))
     ;; Highlight definition of new type
     '("\\<\\(type\\)[ \t]*\\(,.*::[ \t]*\\|[ \t]+\\)\\(\\sw+\\)"
       (1 font-lock-keyword-face) (3 font-lock-function-name-face))
     "\\<\\(\\(end[ \t]*\\)?\\(interface\\|block[ \t]*data\\)\\|contains\\)\\>"))
  "This does fairly subdued highlighting of comments and function calls.")

(defvar f90-font-lock-keywords-2
  (append f90-font-lock-keywords-1
     (if (string-match "XEmacs" emacs-version)
      (list				; XEmacs
       ;; Variable declarations (avoid the real function call)
       '("^[ \t0-9]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|logical\\|type[ \t]*(\\sw+)\\)"
	 1 font-lock-type-face)
       '("^[ \t0-9]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|logical\\|type[ \t]*(\\sw+)\\)\\(.*::\\|[ \t]*(.*)\\)?\\(.*\\)"
	 4 font-lock-doc-string-face)
       ;; do, if and select constructs
       '("\\<\\(end[ \t]*\\(do\\|if\\|select\\)\\)\\>"
	 1 font-lock-keyword-face)
       '("\\<\\(end[ \t]*\\(do\\|if\\|select\\)\\)\\>\\([ \t]+\\(\\sw+\\)\\)"
	 3 font-lock-doc-string-face)
       '("^[ \t0-9]*\\(\\(\\sw+\\)[ \t]*:[ \t]*\\)\\(\\(if\\|do\\([ \t]*while\\)?\\|select[ \t]*case\\)\\)\\>"
	 2 font-lock-doc-string-face)
       '("^[ \t0-9]*\\(\\(\\sw+\\)[ \t]*:[ \t]*\\)?\\(\\(if\\|do\\([ \t]*while\\)?\\|select[ \t]*case\\)\\)\\>"
	 3 font-lock-keyword-face)
      ;; implicit declaration
       '("\\<\\(implicit\\)[ \t]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|logical\\|type[ \t]*(\\sw+)\\|none\\)\\>"
	 1 font-lock-keyword-face)
       '("\\<\\(implicit\\)[ \t]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|logical\\|type[ \t]*(\\sw+)\\|none\\)\\>"
	 2 font-lock-type-face)
       '("\\<\\(namelist\\|common\\)[ \t]*\/\\(\\sw+\\)?\/"
	 1 font-lock-keyword-face)
       '("\\<\\(namelist\\|common\\)[ \t]*\/\\(\\sw+\\)\/"
	 2 font-lock-doc-string-face nil t)
       '("\\<\\(where\\|forall\\)[ \t]*(" . 1)
       "\\<e\\(lse\\([ \t]*if\\|where\\)?\\|nd[ \t]*\\(where\\|forall\\)\\)\\>"
       "\\<\\(then\\|continue\\|format\\|include\\|stop\\|return\\)\\>"
       '("\\<\\(exit\\|cycle\\)\\>" 
	 1 font-lock-keyword-face)
       '("\\<\\(exit\\|cycle\\)[ \t]*\\(\\sw+\\)2\\>" 
	 2 font-lock-doc-string-face)
       '("\\<\\(case\\)[ \t]+\\(default\\|(\\)" . 1)
       '("\\<\\(do\\|go *to\\)\\>[ \t]*\\([0-9]+\\)"
	 1 font-lock-keyword-face)
       '("\\<\\(do\\|go *to\\)\\>[ \t]*\\([0-9]+\\)"
	 2 font-lock-doc-string-face)
       '("^[ \t]*\\([0-9]+\\)" 1 font-lock-doc-string-face t))
      (list				; Emacs
       ;; Variable declarations (avoid the real function call)
       '("^[ \t0-9]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|logical\\|type[ \t]*(\\sw+)\\)\\(.*::\\|[ \t]*(.*)\\)?\\(.*\\)"
	 (1 font-lock-type-face) (4 font-lock-variable-name-face))
       ;; do, if and select constructs
       '("\\<\\(end[ \t]*\\(do\\|if\\|select\\)\\)\\>\\([ \t]+\\(\\sw+\\)\\)?"
	 (1 font-lock-keyword-face) (3 font-lock-reference-face nil t))
       '("^[ \t0-9]*\\(\\(\\sw+\\)[ \t]*:[ \t]*\\)?\\(\\(if\\|do\\([ \t]*while\\)?\\|select[ \t]*case\\)\\)\\>"
	 (2 font-lock-reference-face nil t) (3 font-lock-keyword-face))
       ;; implicit declaration
       '("\\<\\(implicit\\)[ \t]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|logical\\|type[ \t]*(\\sw+)\\|none\\)\\>" (1 font-lock-keyword-face) (2 font-lock-type-face))
       '("\\<\\(namelist\\|common\\)[ \t]*\/\\(\\sw+\\)?\/" (1 font-lock-keyword-face) (2 font-lock-reference-face nil t))
       '("\\<\\(where\\|forall\\)[ \t]*(" . 1)
       "\\<e\\(lse\\([ \t]*if\\|where\\)?\\|nd[ \t]*\\(where\\|forall\\)\\)\\>"
       "\\<\\(then\\|continue\\|format\\|include\\|stop\\|return\\)\\>"
       '("\\<\\(exit\\|cycle\\)[ \t]*\\(\\sw+\\)?\\>" 
	 (1 font-lock-keyword-face) (2 font-lock-reference-face nil t))
       '("\\<\\(case\\)[ \t]+\\(default\\|(\\)" . 1)
       '("\\<\\(do\\|go *to\\)\\>[ \t]*\\([0-9]+\\)"
	 (1 font-lock-keyword-face) (2 font-lock-reference-face))
       '("^[ \t]*\\([0-9]+\\)" (1 font-lock-reference-face t)))))
  "Highlights declarations, do-loops and other constructions")

(defvar f90-font-lock-keywords-3
  (append f90-font-lock-keywords-2
   (list
    f90-keywords-level-3-re
    f90-operators-re
    (if (string-match "XEmacs" emacs-version)
	(append (list f90-procedures-re) '(1 font-lock-keyword-face t))
      (list f90-procedures-re '(1 font-lock-keyword-face t)))
    "\\<real\\>"			; Avoid overwriting real defs.
    ))
  "Highlights all F90 keywords and intrinsic procedures.")

(defvar f90-font-lock-keywords-4
  (append f90-font-lock-keywords-3
    (list f90-hpf-keywords-re))
  "Highlights all F90 and HPF keywords.")

(defvar f90-font-lock-keywords
      f90-font-lock-keywords-2
  "*Default expressions to highlight in F90 mode.")

;; hilit19 customization and expressions
(defvar f90-face-string 'named-param "*Face for strings.")
(defvar f90-face-comment 'comment "*Face for comments.")
(defvar f90-face-decl 'include "*Face for declarations.")
(defvar f90-face-prog 'defun "*Face for program blocks.")
(defvar f90-face-label 'Tomato-bold "*Face for labels.")
(defvar f90-face-type 'defun "*Face for type blocks.")
(defvar f90-face-interface 'defun "*Face for interface blocks.")
(defvar f90-face-contains 'defun "*Face for contains statement.")
(defvar f90-face-do 'SteelBlue-bold "*Face for do-structure.")
(defvar f90-face-if 'define "*Face for if-structure.")
(defvar f90-face-select 'define "*Face for select-case structure.")
(defvar f90-face-stop 'defun "*Face for stop and return.")
(defvar f90-face-exit 'SteelBlue-bold "*Face for exit and cycle.")
(defvar f90-face-keyword 'struct "*Face for keywords.")
(defvar f90-face-intrinsics 'struct "*Face for intrinsic procedures.")
;; Highlighting for HPF (High-Peformance Fortran)
(defvar f90-face-hpf-procedures 'struct "*Face for hpf procedures.")
(defvar f90-face-hpf-directives 'struct "*Face for hpf directives.")
(defvar f90-face-hpf-keywords   'struct "*Face for hpf keywords.")

(defvar f90-hilit-patterns
  (list
   ;; Allow for strings delimited by ' and by " and for multirow strings.
   ;; A multi-row string includes &\n& (+ possible whitespace and comments)
   (list (concat
	  "\\(\"[^\"\n]*\\(&[ \t]*\\(![^\n]*\\)?\n[ \t]*&[^\"\n]*\\)*\""
	  "\\|'[^'\n]*\\(&[ \t]*\\(![^\n]*\\)?\n[ \t]*&[^'\n]*\\)*'\\)")
	 nil f90-face-string)
   (list "!" "$" f90-face-comment)
   (list "\\(\\(real\\|integer\\|character\\|complex\\|logical\
\\|type[ \t]*(\\sw+)\\).*\\)::" 1 f90-face-decl)
   (list "implicit[ \t]*none" nil f90-face-decl)
   (list "^[ \t]*\\(program\\|module\\)[ \t]+\\sw+" 1 f90-face-prog)
   (list "^[ \t]*\\(program\\|module\\)[ \t]+\\(\\sw+\\)" 2 f90-face-label)
   (list "\\(^.*\\(function\\|subroutine\\)\\)[ \t]+\\sw+" 1
	 f90-face-prog)
   (list "^.*\\(function\\|subroutine\\)[ \t]+\\(\\sw+\\)" 2
	 f90-face-label)
   (list "^[ \t]*end[ \t]*\\(program\\|module\\|function\
\\|subroutine\\|type\\)" nil f90-face-prog)
   (list (concat "^[ \t]*end[ \t]*\\(program\\|module\\|function\\|"
		 "subroutine\\|type\\)[ \t]+\\(\\sw+\\)") 2 f90-face-label)
   (list "^[ \t]*\\(type\\)[ \t]+\\sw+" 1 f90-face-type)
   (list "^[ \t]*type[ \t]+\\(\\sw+\\)" 1 f90-face-label)
   (list "^[ \t]*\\(type[ \t]*,[ \t]*\\(private\\|public\\)\\)[ \t]*::[ \t]*\\(\\sw+\\)" 1 f90-face-type)
   (list "^[ \t]*\\(type[ \t]*,[ \t]*\\(private\\|public\\)\\)[ \t]*::[ \t]*\\(\\sw+\\)" 3 f90-face-label)
   (list "^[ \t]*\\(end[ \t]*\\)?interface\\>" nil f90-face-interface)
   (list "^[ \t]*contains\\>" nil f90-face-contains)
   (list "^[ \t]*\\(\\sw+[ \t]*:[ \t]*\\)?\\(do\\([ \t]*while\\)?\\)\\>"
	 2 f90-face-do)
   (list "^[ \t]*\\(\\sw+\\)[ \t]*:[ \t]*\\(do\\([ \t]*while\\)?\\)\\>" 1
	 f90-face-label)
   (list "^[ \t]*\\(end[ \t]*do\\)\\>" 1 f90-face-do)
   (list "^[ \t]*end[ \t]*do[ \t]+\\(\\sw+\\)" 1 f90-face-label)
   (list "^[ \t]*\\(\\sw+[ \t]*:[ \t]*\\)?\\(if\\)\\>" 2 f90-face-if)
   (list "^[ \t]*\\(\\sw+\\)[ \t]*:[ \t]*if\\>" 1 f90-face-label)
   (list "^[ \t]*\\(end[ \t]*if\\)\\>" 1 f90-face-if)
   (list "^[ \t]*end[ \t]*if[ \t]+\\(\\sw+\\)" 1 f90-face-label)
   (list "^[ \t]*\\(\\sw+[ \t]*:[ \t]*\\)?\\(select[ \t]*case\\)\\>" 2
	 f90-face-select)
   (list "^[ \t]*\\(\\sw+\\)[ \t]*:[ \t]*\\(select[ \t]*case\\)\\>" 1
	 f90-face-label)
   (list "^[ \t]*end[ \t]*select\\>" nil f90-face-select)
   (list "^[ \t]*end[ \t]*select\\>[ \t]+\\(\\sw+\\)" 1 f90-face-label)
   (list "\\(where\\|forall\\)[ \t]*(" 1 f90-face-if)
   (list "\\<\\(elsewhere\\|else\\|else[ \t]*if\\)\\>" nil f90-face-if)
   (list "\\<end[ \t]*\\(where\\|forall\\)\\>" nil f90-face-if)
   (list "\\<then\\>" nil f90-face-if)
   (list "\\<\\(exit\\|cycle\\)\\>" nil f90-face-exit)
   (list "\\<\\(exit\\|cycle\\)[ \t]*\\sw+\\>" nil f90-face-label)
   (list "\\<\\(stop\\|return\\)\\>" nil f90-face-stop)
   (list "^[ \t]*\\(case\\)[ \t]*\\((\\|default\\)" 1 f90-face-select)
   (list (concat "\\<\\("(mapconcat 'identity f90-keywords "\\|")
		 "\\)\\>") nil f90-face-keyword)
 (list (concat "\\<\\("(mapconcat 'identity f90-intrinsic-procedures "\\|")
	       "\\)\\>") nil f90-face-intrinsics)
 (list (concat "\\<\\("(mapconcat 'identity f90-hpf-procedures "\\|")
	       "\\)\\>") nil f90-face-hpf-procedures)
 (list (concat "\\<\\("(mapconcat 'identity f90-hpf-directives "\\|")
	       "\\)\\>") nil f90-face-hpf-directives)
 (list (concat "\\<\\("(mapconcat 'identity f90-hpf-keywords "\\|")
	       "\\)\\>") nil f90-face-hpf-keywords)))

;; syntax table
(defvar f90-mode-syntax-table nil
  "Syntax table in use in F90 mode buffers.")

(if f90-mode-syntax-table
    ()
  (setq f90-mode-syntax-table (make-syntax-table))
  (modify-syntax-entry ?\! "<" f90-mode-syntax-table)  ; beg. comment
  (modify-syntax-entry ?\n ">" f90-mode-syntax-table)  ; end comment
  (modify-syntax-entry ?_ "w" f90-mode-syntax-table)   ; underscore in names
  (modify-syntax-entry ?\' "\"" f90-mode-syntax-table) ; string quote
  (modify-syntax-entry ?\" "\"" f90-mode-syntax-table) ; string quote
  (modify-syntax-entry ?\` "w" f90-mode-syntax-table)  ; for abbrevs
  (modify-syntax-entry ?\r " " f90-mode-syntax-table)  ; return is whitespace
  (modify-syntax-entry ?+ "." f90-mode-syntax-table)  
  (modify-syntax-entry ?- "." f90-mode-syntax-table)
  (modify-syntax-entry ?= "." f90-mode-syntax-table)
  (modify-syntax-entry ?* "." f90-mode-syntax-table)
  (modify-syntax-entry ?/ "." f90-mode-syntax-table)
  (modify-syntax-entry ?\\ "/" f90-mode-syntax-table)) ; escape chars

;; keys
(defvar f90-mode-map ()
  "Keymap used in F90 mode.")

(if f90-mode-map
    ()
  (setq f90-mode-map (make-sparse-keymap))
  (define-key f90-mode-map "`"        'f90-abbrev-start)
  (define-key f90-mode-map "\C-c;"    'f90-comment-region)
  (define-key f90-mode-map "\C-\M-a"  'f90-beginning-of-subprogram)
  (define-key f90-mode-map "\C-\M-e"  'f90-end-of-subprogram)
  (define-key f90-mode-map "\C-\M-h"  'f90-mark-subprogram)
  (define-key f90-mode-map "\C-\M-q"  'f90-indent-subprogram)
  (define-key f90-mode-map "\C-j"     'f90-indent-new-line) ; LFD equals C-j
  (define-key f90-mode-map "\r"       'newline)
  (define-key f90-mode-map "\C-c\r"   'f90-break-line)
  ;;  (define-key f90-mode-map [M-return] 'f90-break-line)
  (define-key f90-mode-map "\C-c\C-d" 'f90-join-lines)
  (define-key f90-mode-map "\C-c\C-f" 'f90-fill-region)
  (define-key f90-mode-map "\C-c\C-p" 'f90-previous-statement)
  (define-key f90-mode-map "\C-c\C-n" 'f90-next-statement)
  (define-key f90-mode-map "\C-c\C-w" 'f90-insert-end)
  (define-key f90-mode-map "\t"       'f90-indent-line))

;; menus
(if (string-match "XEmacs" emacs-version)
    (defvar f90-xemacs-menu
      '("F90"
	["Indent Subprogram"       f90-indent-subprogram t]
	["Mark Subprogram"         f90-mark-subprogram t]
	["Beginning of Subprogram" f90-beginning-of-subprogram t]
	["End of Subprogram"       f90-end-of-subprogram t]
	"-----"
	["(Un)Comment Region"      f90-comment-region t]
	["Indent Region"           indent-region t]
	["Fill Region"             f90-fill-region t]
	"-----"
	["Break Line at Point"     f90-break-line t]
	["Join with Next Line"     f90-join-lines t]
	["Insert Newline"          newline t]
	["Insert End"              f90-insert-end t]
	"-----"
	["Upcase Keywords (buffer)"      f90-upcase-keywords t]
	["Upcase Keywords (region)"      f90-upcase-region-keywords
	 t]
	["Capitalize Keywords (buffer)"  f90-capitalize-keywords t]
	["Capitalize Keywords (region)" 
	 f90-capitalize-region-keywords t]
	["Downcase Keywords (buffer)"    f90-downcase-keywords t]
	["Downcase Keywords (region)"   
	 f90-downcase-region-keywords t]
	"-----"
	["Toggle abbrev-mode"   abbrev-mode             t]
	["Toggle auto-fill"     f90-auto-fill-mode      t])
      "XEmacs menu for F90 mode.")
  ;; Emacs
  (define-key f90-mode-map [menu-bar] (make-sparse-keymap))
  (define-key f90-mode-map [menu-bar f90] 
    (cons "F90" (make-sparse-keymap "f90"))) 
  (define-key f90-mode-map [menu-bar f90 abbrev-mode]
    '("Toggle abbrev-mode" . abbrev-mode))
  (define-key f90-mode-map [menu-bar f90 f90-auto-fill-mode]
    '("Toggle auto-fill" . f90-auto-fill-mode))
  (define-key f90-mode-map [menu-bar f90 f90-downcase-region-keywords]
    '("Downcase Keywords (region)" . f90-downcase-region-keywords))
  (define-key f90-mode-map [menu-bar f90 f90-downcase-keywords]
    '("Downcase Keywords (buffer)" . f90-downcase-keywords))
  (define-key f90-mode-map [menu-bar f90 f90-capitalize-keywords]
    '("Capitalize Keywords (region)" . f90-capitalize-region-keywords))
  (define-key f90-mode-map [menu-bar f90 f90-capitalize-region-keywords]
    '("Capitalize Keywords (buffer)" . f90-capitalize-keywords))
  (define-key f90-mode-map [menu-bar f90 f90-upcase-region-keywords]
    '("Upcase Keywords (region)" . f90-upcase-region-keywords))
  (define-key f90-mode-map [menu-bar f90 f90-upcase-keywords]
    '("Upcase Keywords (buffer)" . f90-upcase-keywords))
  (define-key f90-mode-map [menu-bar f90 f90-insert-end]
    '("Insert end" . f90-insert-end))
  (define-key f90-mode-map [menu-bar f90 f90-join-lines]
    '("Join with Next Line" . f90-join-lines))
  (define-key f90-mode-map [menu-bar f90 f90-break-line]
    '("Break Line at Point" . f90-break-line))
  (define-key f90-mode-map [menu-bar f90 f90-fill-region]
    '("Fill Region" . f90-fill-region))
  (define-key f90-mode-map [menu-bar f90 indent-region]
    '("Indent Region" . indent-region))
  (define-key f90-mode-map [menu-bar f90 f90-comment-region]
    '("(Un)Comment Region" . f90-comment-region))
  (define-key f90-mode-map [menu-bar f90 f90-end-of-subprogram]
    '("End of Subprogram" . f90-end-of-subprogram))
  (define-key f90-mode-map [menu-bar f90 f90-beginning-of-subprogram]
    '("Beginning of Subprogram" . f90-beginning-of-subprogram))
  (define-key f90-mode-map [menu-bar f90 f90-mark-subprogram]
    '("Mark Subprogram" . f90-mark-subprogram))
  (define-key f90-mode-map [menu-bar f90 f90-indent-subprogram]
    '("Indent Subprogram" . f90-indent-subprogram)))
  
;; Regexps for finding program structures.
(defconst f90-blocks-re 
  "\\(block[ \t]*data\\|do\\|if\\|interface\\|function\\|module\\|\
program\\|select\\|subroutine\\|type\\|where\\|forall\\)\\>")
(defconst f90-program-block-re 
  "\\(program\\|module\\|subroutine\\|function\\)")
(defconst f90-else-like-re 
  "\\(else\\([ \t]*if\\|where\\)?\\|case[ \t]*\\(default\\|(\\)\\)\\>")
(defconst f90-end-if-re 
  "end[ \t]*\\(if\\|select\\|where\\|forall\\)\\>")
(defconst f90-end-type-re 
  "end[ \t]*\\(type\\|interface\\|block[ \t]*data\\)")
(defconst f90-type-def-re
  "\\<\\(type\\)[ \t]*\\(,.*::[ \t]*\\|[ \t]+\\)\\(\\sw+\\)")
(defconst f90-no-break-re  "\\(\\*\\*\\|//\\|=>\\)")
;; A temporary position to make region operators faster
(defvar f90-cache-position nil)
(make-variable-buffer-local 'f90-cache-position)

;; Imenu support
(defvar f90-imenu-generic-expression
  (cons
   (concat
    "^[ \t0-9]*\\("
    "program[ \t]+\\(\\sw+\\)\\|"
    "module[ \t]+\\(\\sw+\\)[ \t]*\\(!\\|$\\)\\|"
    "\\(recursive[ \t]*\\)?subroutine[ \t]+\\(\\sw+\\)\\|"
    ; avoid end function, but allow for most other things
    "\\([^!]*\\([^e!].[^ \t!]\\|.[^n!][^ \t!]\\|..[^d \t!]\\)"
    "\\|[^!]?[^!]?\\)[ \t]*function[ \t]+\\(\\sw+\\)"
    "\\)")
   (list 2 3 6 9))
  "imenu generic expression for F90 mode.")

;; When compiling under GNU Emacs, load imenu during compilation.  If
;; you have 19.22 or earlier, comment this out, or get imenu.
(and (fboundp 'eval-when-compile)
     (eval-when-compile
       (if (not (string-match "XEmacs" emacs-version))
	   (require 'imenu))
       ()))



;; abbrevs have generally two letters, except standard types `c, `i, `r, `t
(defvar f90-mode-abbrev-table nil)
(if f90-mode-abbrev-table
    ()
  (let ((ac abbrevs-changed))
    (define-abbrev-table 'f90-mode-abbrev-table ())
    (define-abbrev f90-mode-abbrev-table  "`al"  "allocate" nil)
    (define-abbrev f90-mode-abbrev-table  "`ab"  "allocatable" nil)
    (define-abbrev f90-mode-abbrev-table  "`as"  "assignment" nil)
    (define-abbrev f90-mode-abbrev-table  "`ba"  "backspace" nil)
    (define-abbrev f90-mode-abbrev-table  "`bd"  "block data" nil)
    (define-abbrev f90-mode-abbrev-table  "`c"   "character" nil)
    (define-abbrev f90-mode-abbrev-table  "`cl"  "close" nil)
    (define-abbrev f90-mode-abbrev-table  "`cm"  "common" nil)
    (define-abbrev f90-mode-abbrev-table  "`cx"  "complex" nil)
    (define-abbrev f90-mode-abbrev-table  "`cn"  "contains" nil)
    (define-abbrev f90-mode-abbrev-table  "`cy"  "cycle" nil)
    (define-abbrev f90-mode-abbrev-table  "`de"  "deallocate" nil)
    (define-abbrev f90-mode-abbrev-table  "`df"  "define" nil)
    (define-abbrev f90-mode-abbrev-table  "`di"  "dimension" nil)
    (define-abbrev f90-mode-abbrev-table  "`dw"  "do while" nil)
    (define-abbrev f90-mode-abbrev-table  "`el"  "else" nil)
    (define-abbrev f90-mode-abbrev-table  "`eli" "else if" nil)
    (define-abbrev f90-mode-abbrev-table  "`elw" "elsewhere" nil)
    (define-abbrev f90-mode-abbrev-table  "`eq"  "equivalence" nil)
    (define-abbrev f90-mode-abbrev-table  "`ex"  "external" nil)
    (define-abbrev f90-mode-abbrev-table  "`ey"  "entry" nil)
    (define-abbrev f90-mode-abbrev-table  "`fl"  "forall" nil)
    (define-abbrev f90-mode-abbrev-table  "`fo"  "format" nil)
    (define-abbrev f90-mode-abbrev-table  "`fu"  "function" nil)
    (define-abbrev f90-mode-abbrev-table  "`fa"  ".false." nil)
    (define-abbrev f90-mode-abbrev-table  "`im"  "implicit none" nil)
    (define-abbrev f90-mode-abbrev-table  "`in " "include" nil)
    (define-abbrev f90-mode-abbrev-table  "`i"   "integer" nil)
    (define-abbrev f90-mode-abbrev-table  "`it"  "intent" nil)
    (define-abbrev f90-mode-abbrev-table  "`if"  "interface" nil)
    (define-abbrev f90-mode-abbrev-table  "`lo"  "logical" nil)
    (define-abbrev f90-mode-abbrev-table  "`mo"  "module" nil)
    (define-abbrev f90-mode-abbrev-table  "`na"  "namelist" nil)
    (define-abbrev f90-mode-abbrev-table  "`nu"  "nullify" nil)
    (define-abbrev f90-mode-abbrev-table  "`op"  "optional" nil)
    (define-abbrev f90-mode-abbrev-table  "`pa"  "parameter" nil)
    (define-abbrev f90-mode-abbrev-table  "`po"  "pointer" nil)
    (define-abbrev f90-mode-abbrev-table  "`pr"  "print" nil)
    (define-abbrev f90-mode-abbrev-table  "`pi"  "private" nil)
    (define-abbrev f90-mode-abbrev-table  "`pm"  "program" nil)
    (define-abbrev f90-mode-abbrev-table  "`pu"  "public" nil)
    (define-abbrev f90-mode-abbrev-table  "`r"   "real" nil)
    (define-abbrev f90-mode-abbrev-table  "`rc"  "recursive" nil)
    (define-abbrev f90-mode-abbrev-table  "`rt"  "return" nil)
    (define-abbrev f90-mode-abbrev-table  "`rw"  "rewind" nil)
    (define-abbrev f90-mode-abbrev-table  "`se"  "select" nil)
    (define-abbrev f90-mode-abbrev-table  "`sq"  "sequence" nil)
    (define-abbrev f90-mode-abbrev-table  "`su"  "subroutine" nil)
    (define-abbrev f90-mode-abbrev-table  "`ta"  "target" nil)
    (define-abbrev f90-mode-abbrev-table  "`tr"  ".true." nil)
    (define-abbrev f90-mode-abbrev-table  "`t"   "type" nil)
    (define-abbrev f90-mode-abbrev-table  "`wh"  "where" nil)
    (define-abbrev f90-mode-abbrev-table  "`wr"  "write" nil)
    (setq abbrevs-changed ac)))

;;;###autoload
(defun f90-mode ()
  "Major mode for editing Fortran 90 code in free format.

\\[f90-indent-new-line] corrects current indentation and creates new\
 indented line.
\\[f90-indent-line] indents the current line correctly. 
\\[f90-indent-subprogram] indents the current subprogram. 

Type `? or `\\[help-command] to display a list of built-in\
 abbrevs for F90 keywords.

Key definitions:
\\{f90-mode-map}

Variables controlling indentation style and extra features:

 f90-do-indent
    Extra indentation within do blocks.  (default 3)
 f90-if-indent
    Extra indentation within if/select case/where/forall blocks. (default 3)
 f90-type-indent
    Extra indentation within type/interface/block-data blocks.  (default 3)
 f90-program-indent
    Extra indentation within program/module/subroutine/function blocks.
      (default 2)
 f90-continuation-indent
    Extra indentation applied to continuation lines.  (default 5)
 f90-comment-region
    String inserted by \\[f90-comment-region] at start of each line in 
    region.  (default \"!!!$\")
 f90-indented-comment-re
    Regexp determining the type of comment to be intended like code.
    (default \"!\")
 f90-directive-comment-re
    Regexp of comment-like directive like \"!HPF\\\\$\", not to be indented.
    (default \"!hpf\\\\$\")
 f90-break-delimiters
    Regexp holding list of delimiters at which lines may be broken.
    (default \"[-+*/><=,% \\t]\")
 f90-break-before-delimiters
    Non-nil causes `f90-do-auto-fill' to break lines before delimiters.
    (default t)
 f90-beginning-ampersand 
    Automatic insertion of \& at beginning of continuation lines. (default t)
 f90-smart-end 
    From an END statement, check and fill the end using matching block start.
    Allowed values are 'blink, 'no-blink, and nil, which determine
    whether to blink the matching beginning.) (default 'blink)
 f90-auto-keyword-case
    Automatic change of case of keywords. (default nil)
    The possibilities are 'downcase-word, 'upcase-word, 'capitalize-word.
 f90-leave-line-no
    Do not left-justify line numbers. (default nil)
 f90-startup-message
    Set to nil to inhibit message first time F90 mode is used. (default t)
 f90-keywords
    List of keywords used for highlighting/upcase-keywords etc.

Turning on F90 mode calls the value of the variable `f90-mode-hook'
with no args, if that value is non-nil."
  (interactive)
  (kill-all-local-variables)
  (setq major-mode 'f90-mode)
  (setq mode-name "F90")
  (setq local-abbrev-table f90-mode-abbrev-table)
  (set-syntax-table f90-mode-syntax-table)
  (use-local-map f90-mode-map)
  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'f90-indent-line)
  (make-local-variable 'indent-region-function)
  (setq indent-region-function 'f90-indent-region)
  (make-local-variable 'require-final-newline)
  (setq require-final-newline t)
  (make-local-variable 'comment-start)
  (setq comment-start "!")
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip "!+ *")
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'f90-comment-indent)
  (make-local-variable 'abbrev-all-caps)
  (setq abbrev-all-caps t)
  (setq indent-tabs-mode nil)

  (if (fboundp 'hilit-set-mode-patterns)
      (hilit-set-mode-patterns
       'f90-mode f90-hilit-patterns nil 'case-insensitive))
  ;; Setting up things for font-lock
  (if (string-match "Xemacs" emacs-version)
      (progn
	(put 'f90-mode 'font-lock-keywords-case-fold-search t)
	(if (and current-menubar
		 (not (assoc "F90" current-menubar)))
	    (progn
	      (set-buffer-menubar (copy-sequence current-menubar))
	      (add-submenu nil f90-xemacs-menu)))
	(make-local-variable 'font-lock-keywords)
	(setq font-lock-keywords f90-font-lock-keywords))
    ;; Emacs
    (make-local-variable 'font-lock-defaults)
    (setq font-lock-defaults 
	  '((f90-font-lock-keywords f90-font-lock-keywords-1
				    f90-font-lock-keywords-2
				    f90-font-lock-keywords-3
				    f90-font-lock-keywords-4)
	    nil t))
    ;; Tell imenu how to handle f90.
    (make-local-variable 'imenu-generic-expression)
    (setq imenu-generic-expression f90-imenu-generic-expression))
  (run-hooks 'f90-mode-hook)
  (if f90-startup-message
      (message "Emacs F90 mode; please report bugs to %s" bug-f90-mode))
  (setq f90-startup-message nil))

;; inline-functions
(defsubst f90-get-beg-of-line ()
  (save-excursion (beginning-of-line) (point)))

(defsubst f90-get-end-of-line ()
  (save-excursion (end-of-line) (point)))

(defsubst f90-in-string ()
  (let ((beg-pnt
	 (if (and f90-cache-position (> (point) f90-cache-position))
	     f90-cache-position
	   (point-min))))
    (nth 3 (parse-partial-sexp beg-pnt (point)))))
	    
(defsubst f90-in-comment ()
  (let ((beg-pnt
	 (if (and f90-cache-position (> (point) f90-cache-position))
	     f90-cache-position
	   (point-min))))
    (nth 4 (parse-partial-sexp beg-pnt (point)))))

(defsubst f90-line-continued ()
  (save-excursion
    (let ((bol (f90-get-beg-of-line)))
      (end-of-line)
      (while (f90-in-comment)
	(search-backward "!" bol)
	(skip-chars-backward "!"))
      (skip-chars-backward " \t")
      (= (preceding-char) ?&))))

(defsubst f90-current-indentation ()
  "Return indentation of current line.
Line-numbers are considered whitespace characters."
  (save-excursion
    (beginning-of-line) (skip-chars-forward " \t0-9")
    (current-column)))

(defsubst f90-indent-to (col &optional no-line-number)
  "Indent current line to column COL.
If no-line-number nil, jump over a possible line-number."
  (beginning-of-line)
  (if (not no-line-number)
      (skip-chars-forward " \t0-9"))
  (delete-horizontal-space)
  (if (zerop (current-column))
      (indent-to col)
    (indent-to col 1)))

(defsubst f90-match-piece (arg)
  (if (match-beginning arg)
      (buffer-substring (match-beginning arg) (match-end arg))))

(defsubst f90-get-present-comment-type ()
  (save-excursion
    (let ((type nil) (eol (f90-get-end-of-line)))
      (if (f90-in-comment)
	  (progn
	    (beginning-of-line)
	    (re-search-forward "[!]+" eol)
	    (while (f90-in-string)
	      (re-search-forward "[!]+" eol))
	    (setq type (buffer-substring (match-beginning 0) (match-end 0)))))
      type)))

(defsubst f90-equal-symbols (a b)
  "Compare strings neglecting case and allowing for nil value."
  (let ((a-local (if a (downcase a) nil))
	(b-local (if b (downcase b) nil)))
    (equal a-local b-local)))

;; XEmacs 19.11 & 19.12 gives back a single char when matching an empty regular
;; expression. Therefore, the next 2 functions are longer than necessary.

(defsubst f90-looking-at-do ()
  "Return (\"do\" name) if a do statement starts after point.
Name is nil if the statement has no label."
  (if (looking-at "\\(\\(\\sw+\\)[ \t]*\:\\)?[ \t]*\\(do\\)\\>")
      (let (label
	    (struct (f90-match-piece 3)))
	(if (looking-at "\\(\\sw+\\)[ \t]*\:")
	    (setq label (f90-match-piece 1)))
	(list struct label))))

(defsubst f90-looking-at-select-case ()
  "Return (\"select\" name) if a select-case statement starts after point.
Name is nil if the statement has no label."
  (if (looking-at "\\(\\(\\sw+\\)[ \t]*\:\\)?[ \t]*\\(select\\)[ \t]*case[ \t]*(")
      (let (label
	    (struct (f90-match-piece 3)))
	(if (looking-at "\\(\\sw+\\)[ \t]*\:")
	    (setq label (f90-match-piece 1)))
	(list struct label))))

(defsubst f90-looking-at-if-then ()
  "Return (\"if\" name) if an if () then statement starts after point.
Name is nil if the statement has no label."
  (save-excursion
    (let (struct (label nil))
      (if (looking-at "\\(\\(\\sw+\\)[ \t]*\:\\)?[ \t]*\\(if\\)\\>")
	  (progn
	    (setq struct (f90-match-piece 3))
	    (if (looking-at "\\(\\sw+\\)[ \t]*\:")
		(setq label (f90-match-piece 1)))
	    (goto-char (scan-lists (point) 1 0))
	    (skip-chars-forward " \t")
	    (if (or (looking-at "then\\>")
		    (if (f90-line-continued)
			(progn
			  (f90-next-statement)
			  (skip-chars-forward " \t0-9&")
			  (looking-at "then\\>"))))
		(list struct label)))))))

(defsubst f90-looking-at-where-or-forall ()
  "Return (kind nil) if where/forall...end starts after point."
  (save-excursion
    (let (command)
      (if (looking-at "\\(where\\|forall\\)[ \t]*(")
	  (progn
	    (setq command (list (f90-match-piece 1) nil))
	    (goto-char (scan-lists (point) 1 0))
	    (skip-chars-forward " \t")
	    (if (looking-at "\\(!\\|$\\)")
		command))))))

(defsubst f90-looking-at-type-like ()
  "Return (kind name) at the start of a type/interface/block-data block.
Name is non-nil only for type."
  (cond 
   ((looking-at f90-type-def-re)
    (list (f90-match-piece 1) (f90-match-piece 3)))
   ((looking-at "\\(interface\\|block[\t]*data\\)\\>")
    (list (f90-match-piece 1) nil))))

(defsubst f90-looking-at-program-block-start ()
  "Return (kind name) if a program block with name name starts after point."
  (cond
   ((looking-at "\\(program\\)[ \t]+\\(\\sw+\\)\\>")
    (list (f90-match-piece 1) (f90-match-piece 2)))
   ((and (not (looking-at "module[ \t]*procedure\\>"))
	 (looking-at "\\(module\\)[ \t]+\\(\\sw+\\)\\>"))
    (list (f90-match-piece 1) (f90-match-piece 2)))
   ((looking-at "\\(recursive[ \t]*\\)?\\(subroutine\\)[ \t]+\\(\\sw+\\)")
    (list (f90-match-piece 2) (f90-match-piece 3)))
   ((and (not (looking-at "end[ \t]*function"))
	 (looking-at ".*\\(function\\)[ \t]+\\(\\sw+\\)"))
    (list (f90-match-piece 1) (f90-match-piece 2)))))

(defsubst f90-looking-at-program-block-end ()
  "Return list of type and name of end of block."
  (if (looking-at (concat "end[ \t]*" f90-blocks-re 
			  "?\\([ \t]+\\(\\sw+\\)\\)?\\>"))
      (list (f90-match-piece 1) (f90-match-piece 3))))

(defsubst f90-comment-indent ()
  (cond ((looking-at "!!!") 0)
	((and f90-directive-comment-re
	      (looking-at f90-directive-comment-re)) 0)
	((looking-at (regexp-quote f90-comment-region)) 0)
	((looking-at f90-indented-comment-re)
	 (f90-calculate-indent))
	(t (skip-chars-backward " \t")
	   (max (if (bolp) 0 (1+ (current-column))) comment-column))))

(defsubst f90-present-statement-cont ()
  "Return continuation properties of present statement."
  (let (pcont cont)
    (save-excursion
      (setq pcont (if (f90-previous-statement) (f90-line-continued) nil)))
    (setq cont (f90-line-continued))
    (cond ((and (not pcont) (not cont)) 'single)
 	  ((and (not pcont) cont)       'begin)
 	  ((and pcont       (not cont)) 'end)
 	  ((and pcont       cont)       'middle)
 	  (t (error)))))

(defsubst f90-indent-line-no ()
  (if f90-leave-line-no
      ()
    (if (and (not (zerop (skip-chars-forward " \t")))
	     (looking-at "[0-9]"))
	(delete-horizontal-space)))
  (skip-chars-forward " \t0-9"))

(defsubst f90-no-block-limit ()
  (let ((eol (f90-get-end-of-line)))
    (save-excursion
      (not (or (looking-at "end")
	       (looking-at "\\(do\\|if\\|else\\|select[ \t]*case\\|\
case\\|where\\|forall\\)\\>")
	       (looking-at "\\(program\\|module\\|interface\\|\
block[ \t]*data\\)\\>")
	       (looking-at "\\(contains\\|\\sw+[ \t]*:\\)")
	       (looking-at f90-type-def-re)
	       (re-search-forward "\\(function\\|subroutine\\)" eol t))))))

(defsubst f90-update-line ()
  (let (bol eol)
    (if f90-auto-keyword-case
	(progn (setq bol (f90-get-beg-of-line)
		     eol (f90-get-end-of-line))
	       (if f90-auto-keyword-case
		   (f90-change-keywords f90-auto-keyword-case bol eol)
	       (if (and f90-auto-hilit19 (fboundp 'hilit-rehighlight-region))
		   (hilit-rehighlight-region bol eol t)))))))

(defun f90-get-correct-indent ()
  "Get correct indent for a line starting with line number.
Does not check type and subprogram indentation."
  (let ((epnt (f90-get-end-of-line)) icol cont)
    (save-excursion
      (while (and (f90-previous-statement)
		  (or (progn
			(setq cont (f90-present-statement-cont))
			(or (eq cont 'end) (eq cont 'middle)))
		      (looking-at "[ \t]*[0-9]"))))
      (setq icol (current-indentation))
      (beginning-of-line)
      (if (re-search-forward "\\(if\\|do\\|select\\|where\\|forall\\)"
			     (f90-get-end-of-line) t)
	  (progn
	    (beginning-of-line) (skip-chars-forward " \t")
	    (cond ((f90-looking-at-do)
		   (setq icol (+ icol f90-do-indent)))
		  ((or (f90-looking-at-if-then)
		       (f90-looking-at-where-or-forall)
		       (f90-looking-at-select-case))
		   (setq icol (+ icol f90-if-indent))))
	    (end-of-line)))
      (while (re-search-forward
	      "\\(if\\|do\\|select\\|where\\|forall\\)" epnt t)
	(beginning-of-line) (skip-chars-forward " \t0-9")
	(cond  ((f90-looking-at-do)
		(setq icol (+ icol f90-do-indent)))
	       ((or (f90-looking-at-if-then)
		    (f90-looking-at-where-or-forall)
		    (f90-looking-at-select-case))
		(setq icol (+ icol f90-if-indent)))
	       ((looking-at f90-end-if-re)
		(setq icol (- icol f90-if-indent)))
	       ((looking-at "end[ \t]*do\\>")
		(setq icol (- icol f90-do-indent))))
	(end-of-line))
      icol)))
	       
	  
(defun f90-calculate-indent ()
  "Calculate the indent column based on previous statements."
  (interactive)
  (let (icol cont (case-fold-search t) (pnt (point)))
    (save-excursion
      (if (not (f90-previous-statement))
	  (setq icol 0)
	(setq cont (f90-present-statement-cont))
	(if (eq cont 'end)
	    (while (not (eq 'begin (f90-present-statement-cont)))
	      (f90-previous-statement)))
	(cond ((eq cont 'begin)
	       (setq icol (+ (f90-current-indentation)
			     f90-continuation-indent)))
	      ((eq cont 'middle) (setq icol(current-indentation)))
	      (t (setq icol (f90-current-indentation))
		 (skip-chars-forward " \t")
		 (if (looking-at "[0-9]")
		     (setq icol (f90-get-correct-indent))
		   (cond ((or (f90-looking-at-if-then)
			      (f90-looking-at-where-or-forall)
			      (f90-looking-at-select-case)
			      (looking-at f90-else-like-re))		       
			  (setq icol (+ icol f90-if-indent)))
			 ((f90-looking-at-do)
			  (setq icol (+ icol f90-do-indent)))
			 ((f90-looking-at-type-like)
			  (setq icol (+ icol f90-type-indent)))
			 ((or (f90-looking-at-program-block-start)
			      (looking-at "contains[ \t]*\\($\\|!\\)"))
			  (setq icol (+ icol f90-program-indent)))))
		 (goto-char pnt)
		 (beginning-of-line)
		 (cond ((looking-at "[ \t]*$"))
		       ((looking-at "[ \t]*#") ; Check for cpp directive.
			(setq icol 0))
		       (t
			(skip-chars-forward " \t0-9")
			(cond ((or (looking-at f90-else-like-re)
				   (looking-at f90-end-if-re))
			       (setq icol (- icol f90-if-indent)))
			      ((looking-at "end[ \t]*do\\>")
			       (setq icol (- icol f90-do-indent)))
			      ((looking-at f90-end-type-re)
			       (setq icol (- icol f90-type-indent)))
			      ((or (looking-at "contains[ \t]*\\(!\\|$\\)")
				   (f90-looking-at-program-block-end))
			       (setq icol (- icol f90-program-indent))))))
		 ))))
    icol))

;; Statement = statement line, a line which is neither blank, nor a comment.
(defun f90-previous-statement ()
  "Move point to beginning of the previous F90 statement.
Return nil if no previous statement is found."
  (interactive)
  (let (not-first-statement)
    (beginning-of-line)
    (while (and (setq not-first-statement (zerop (forward-line -1)))
		(looking-at "[ \t0-9]*\\(!\\|$\\|#\\)")))
    not-first-statement))

(defun f90-next-statement ()
  "Move point to beginning of the next F90 statement.
Return nil if no later statement is found."
  (interactive)
  (let (not-last-statement)
    (beginning-of-line)
    (while (and (setq not-last-statement
		      (and (zerop (forward-line 1))
			   (not (eobp))))
 		(looking-at "[ \t0-9]*\\(!\\|$\\)")))
    not-last-statement))

(defun f90-beginning-of-subprogram ()
  "Move point to the beginning of subprogram.
Return (type name) or nil if not found."
  (interactive)
  (let ((count 1) (case-fold-search t) matching-beg)
    (beginning-of-line) (skip-chars-forward " \t0-9")
    (if (setq matching-beg (f90-looking-at-program-block-start)) 
	(setq count (- count 1)))
    (while (and (not (zerop count))
		(re-search-backward f90-program-block-re nil 'move))
      (beginning-of-line) (skip-chars-forward " \t0-9")
      (cond 
       ((setq matching-beg (f90-looking-at-program-block-start))
	(setq count (- count 1)))
       ((f90-looking-at-program-block-end)
	(setq count (+ count 1)))))
    (beginning-of-line)
    (if (zerop count)
	matching-beg
      (message "No beginning-found.")
      nil)))

(defun f90-end-of-subprogram ()
  "Move point to the end of subprogram.
Return (type name) or nil if not found."
  (interactive)
  (let ((count 1) (case-fold-search t) matching-end)
    (beginning-of-line) (skip-chars-forward " \t0-9")
    (if (setq matching-end (f90-looking-at-program-block-end))
	(setq count (1- count)))
    (end-of-line)
    (while (and (not (zerop count))
		(re-search-forward f90-program-block-re nil 'move))
      (beginning-of-line) (skip-chars-forward " \t0-9")
      (cond ((f90-looking-at-program-block-start)
	     (setq count (+ count 1)))
	    ((setq matching-end (f90-looking-at-program-block-end))
	     (setq count (1- count ))))
      (end-of-line))
    (forward-line 1)
    (if (zerop count)
	matching-end
      (message "No end found.")
      nil)))

(defun f90-mark-subprogram ()
  "Put mark at end of F90 subprogram, point at beginning.
Marks are pushed and highlight (grey shadow) is turned on."
  (interactive)
  (let ((pos (point)) program)
    (f90-end-of-subprogram)
    (push-mark (point) t)
    (goto-char pos)
    (setq program (f90-beginning-of-subprogram))
    ;; The keywords in the preceding lists assume case-insensitivity.
    (if (string-match "XEmacs" emacs-version)
	(zmacs-activate-region)
      (setq mark-active t)
      (setq deactivate-mark nil))
    program))

(defun f90-comment-region (beg-region end-region)
  "Comment/uncomment every line in the region.
Insert f90-comment-region at the beginning of every line in the region
or, if already present, remove it."
  (interactive "*r")
  (let ((end (make-marker)))
    (set-marker end end-region)
    (goto-char beg-region)
    (beginning-of-line)
    (if (looking-at (regexp-quote f90-comment-region))
	(delete-region (point) (match-end 0))
      (insert f90-comment-region))
    (while (and  (zerop (forward-line 1))
		 (< (point) (marker-position end)))
      (if (looking-at (regexp-quote f90-comment-region))
	  (delete-region (point) (match-end 0))
	(insert f90-comment-region)))
    (set-marker end nil)))

(defun f90-indent-line (&optional no-update)
  "Indent current line as F90 code."
  (interactive)
  (let (indent (no-line-number nil) (pos (make-marker)) (case-fold-search t))
    (set-marker pos (point))
    (beginning-of-line)			; Digits after & \n are not line-no
    (if (save-excursion (and (f90-previous-statement) (f90-line-continued)))
	(progn (setq no-line-number t) (skip-chars-forward " \t"))
      (f90-indent-line-no))
    (if (looking-at "!")
	(setq indent (f90-comment-indent))
      (if (and (looking-at "end") f90-smart-end)
	    (f90-match-end))
      (setq indent (f90-calculate-indent)))
    (if (zerop (- indent (current-column)))
	nil
      (f90-indent-to indent no-line-number))
    ;; If initial point was within line's indentation,
    ;; position after the indentation.  Else stay at same point in text.
    (if (< (point) (marker-position pos))
	(goto-char (marker-position pos)))
    (if (not no-update) (f90-update-line))
    (if (and auto-fill-function
	     (> (save-excursion (end-of-line) (current-column)) fill-column))
	(save-excursion (f90-do-auto-fill)))
    (set-marker pos nil)))

(defun f90-indent-new-line ()
  "Reindent the current F90 line, insert a newline and indent the newline.
An abbrev before point is expanded if `abbrev-mode' is non-nil.
If run in the middle of a line, the line is not broken."
  (interactive)
  (let (string cont (case-fold-search t))
    (if abbrev-mode (expand-abbrev))
    (beginning-of-line)			; Reindent where likely to be needed.
    (f90-indent-line-no)
    (if (or (looking-at "\\(end\\|else\\|!\\)"))
	(f90-indent-line 'no-update))
    (end-of-line)
    (delete-horizontal-space)		;Destroy trailing whitespace
    (setq string (f90-in-string))
    (setq cont (f90-line-continued))
    (if (and string (not cont)) (insert "&"))
    (f90-update-line)
    (newline)
    (if (or string (and cont f90-beginning-ampersand)) (insert "&"))
    (f90-indent-line 'no-update)))


(defun f90-indent-region (beg-region end-region)
  "Indent every line in region by forward parsing."
  (interactive "*r")
  (let ((end-region-mark (make-marker)) (save-point (point-marker))
	(block-list nil) ind-lev ind-curr ind-b cont
	struct beg-struct end-struct)
    (set-marker end-region-mark end-region)
    (goto-char beg-region)
    ;; first find a line which is not a continuation line or comment
    (beginning-of-line)
    (while (and (looking-at "[ \t]*[0-9]*\\(!\\|#\\|[ \t]*$\\)")
		(progn (f90-indent-line 'no-update)
		       (zerop (forward-line 1)))
		(< (point) end-region-mark)))
    (setq cont (f90-present-statement-cont))
    (while (and (or (eq cont 'middle) (eq cont 'end))
		(f90-previous-statement))
      (setq cont (f90-present-statement-cont)))
    ;; process present line for beginning of block
    (setq f90-cache-position (point))
    (f90-indent-line 'no-update)
    (setq ind-lev (f90-current-indentation))
    (setq ind-curr ind-lev)
    (beginning-of-line) (skip-chars-forward " \t0-9")
    (setq struct nil)
    (setq ind-b (cond ((setq struct (f90-looking-at-do)) f90-do-indent)
		      ((or (setq struct (f90-looking-at-if-then))
			   (setq struct (f90-looking-at-select-case))
			   (setq struct (f90-looking-at-where-or-forall))
			   (looking-at f90-else-like-re))
		       f90-if-indent)
		      ((setq struct (f90-looking-at-type-like))
		       f90-type-indent)
		      ((or(setq struct (f90-looking-at-program-block-start))
			  (looking-at "contains[ \t]*\\($\\|!\\)"))
		       f90-program-indent)))
    (if ind-b (setq ind-lev (+ ind-lev ind-b)))
    (if struct (setq block-list (cons struct block-list)))
    (while (and (f90-line-continued) (zerop (forward-line 1))
		(< (point) end-region-mark))
      (if (not (zerop (- (current-indentation) 
			 (+ ind-curr f90-continuation-indent))))
	  (f90-indent-to (+ ind-curr f90-continuation-indent) 'no-line-no)))
    ;; process all following lines
    (while (and  (zerop (forward-line 1)) (< (point) end-region-mark))
      (beginning-of-line)
      (f90-indent-line-no)
      (setq f90-cache-position (point))
      (cond ((looking-at "[ \t]*$") (setq ind-curr 0))
	    ((looking-at "[ \t]*#") (setq ind-curr 0))
	    ((looking-at "!") (setq ind-curr (f90-comment-indent)))
	    ((f90-no-block-limit) (setq ind-curr ind-lev))
	    ((looking-at f90-else-like-re) (setq ind-curr
						 (- ind-lev f90-if-indent)))
	    ((looking-at "contains[ \t]*\\($\\|!\\)")
	     (setq ind-curr (- ind-lev f90-program-indent)))
	    ((setq ind-b
		   (cond ((setq struct (f90-looking-at-do)) f90-do-indent)
			 ((or (setq struct (f90-looking-at-if-then))
			      (setq struct (f90-looking-at-select-case))
			      (setq struct (f90-looking-at-where-or-forall)))
			  f90-if-indent)
			 ((setq struct (f90-looking-at-type-like))
			  f90-type-indent)
			 ((setq struct (f90-looking-at-program-block-start))
			  f90-program-indent)))
	     (setq ind-curr ind-lev)
	     (if ind-b (setq ind-lev (+ ind-lev ind-b)))
	     (setq block-list (cons struct block-list)))
	    ((setq end-struct (f90-looking-at-program-block-end))
	     (setq beg-struct (car block-list)
		   block-list (cdr block-list))
	     (if f90-smart-end 
		 (save-excursion
		   (f90-block-match (car beg-struct)(car (cdr beg-struct))
				    (car end-struct)(car (cdr end-struct)))))
	     (setq ind-b
		   (cond ((looking-at f90-end-if-re) f90-if-indent)
			 ((looking-at "end[ \t]*do\\>")  f90-do-indent)
			 ((looking-at f90-end-type-re) f90-type-indent)
			 ((f90-looking-at-program-block-end)
			  f90-program-indent)))
	     (if ind-b (setq ind-lev (- ind-lev ind-b)))
	     (setq ind-curr ind-lev))
	    (t (setq ind-curr ind-lev)))
      ;; do the indentation if necessary
      (if (not (zerop (- ind-curr (current-column))))
	  (f90-indent-to ind-curr))
      (while (and (f90-line-continued) (zerop (forward-line 1))
		  (< (point) end-region-mark))
	(if (not (zerop (- (current-indentation) 
			   (+ ind-curr f90-continuation-indent))))
	    (f90-indent-to (+ ind-curr f90-continuation-indent) 'no-line-no))))
    ;; restore point etc
    (setq f90-cache-position nil)
    (goto-char save-point)
    (set-marker end-region-mark nil)
    (set-marker save-point nil)
    (if (string-match "Xemacs" emacs-version)
	(zmacs-deactivate-region)
      (deactivate-mark))))

(defun f90-indent-subprogram ()
  "Properly indent the subprogram which contains point."
  (interactive)
  (save-excursion
    (let (program)
      (setq program (f90-mark-subprogram))
      (if program
	  (progn
	    (message "Indenting %s %s..."
		     (car program) (car (cdr program)))
	    (f90-indent-region (point) (mark))
	    (message "Indenting %s %s...done"
		     (car program) (car (cdr program))))
	(message "Indenting the whole file...")
	(f90-indent-region (point) (mark))
	(message "Indenting the whole file...done")))))

;; autofill and break-line
(defun f90-break-line (&optional no-update)
  "Break line at point, insert continuation marker(s) and indent."
  (interactive)
  (let (ctype)
    (cond ((f90-in-string)
	   (insert "&") (newline) (insert "&"))
	  ((f90-in-comment)
	   (delete-horizontal-space)
	   (setq ctype (f90-get-present-comment-type))
	   (newline) (insert (concat ctype " ")))
	  (t (delete-horizontal-space)
	     (insert "&")
	     (if (not no-update) (f90-update-line))
	     (newline)
	     (if f90-beginning-ampersand (insert "& ")))))
  (if (not no-update) (f90-indent-line)))
  
(defun f90-find-breakpoint ()
  "From fill-column, search backward for break-delimiter."
  (let ((bol (f90-get-beg-of-line)))
    (re-search-backward f90-break-delimiters bol)
    (if f90-break-before-delimiters
	(progn (backward-char)
	       (if (not (looking-at f90-no-break-re))
		   (forward-char)))
      (if (looking-at f90-no-break-re)
	  (forward-char 2)
	(forward-char)))))

(defun f90-auto-fill-mode (arg)
  "Toggle f90-auto-fill mode.
With ARG, turn `f90-auto-fill' mode on iff ARG is positive.
In `f90-auto-fill' mode, inserting a space at a column beyond `fill-column'
automatically breaks the line at a previous space."
  (interactive "P")
  (prog1 (setq auto-fill-function
	       (if (if (null arg)
		       (not auto-fill-function)
		     (> (prefix-numeric-value arg) 0))
		   'f90-do-auto-fill))
    (force-mode-line-update)))

(defun f90-do-auto-fill ()
  "Break line if non-white characters beyond fill-column."
  (interactive)
  ;; Break the line before or after the last delimiter (non-word char).
  ;; Will not break **, //, or => (specified by f90-no-break-re).
  ;; Start by checking that line is longer than fill-column.
  (if (> (save-excursion (end-of-line) (current-column)) fill-column)
      (progn
	(move-to-column fill-column)
	(if (and (looking-at "[ \t]*$") (not (f90-in-string)))
	    (delete-horizontal-space)
	  (f90-find-breakpoint)
	  (f90-break-line)
	  (end-of-line)))))

(defun f90-join-lines ()
  "Join present line with next line, if this line ends with \&."
  (interactive)
  (let (pos (oldpos (point)))
    (end-of-line)
    (skip-chars-backward " \t")
    (cond ((= (preceding-char) ?&)
	   (delete-char -1)
	   (setq pos (point))
	   (forward-line 1)
	   (skip-chars-forward " \t")
	   (if (looking-at "\&") (delete-char 1))
	   (delete-region pos (point))
	   (if (not (f90-in-string))
	       (progn (delete-horizontal-space) (insert " ")))
	   (if (and auto-fill-function
		    (> (save-excursion (end-of-line)
				       (current-column))
		       fill-column))
	       (f90-do-auto-fill))
	   (goto-char oldpos)
	   t))))

(defun f90-fill-region (beg-region end-region)
  "Fill every line in region by forward parsing. Join lines if possible."
  (interactive "*r")
  (let ((end-region-mark (make-marker))
	(f90-auto-hilit19 nil)
	(f90-smart-end nil) (f90-auto-keyword-case nil) indent (go-on t)
	(af-function auto-fill-function) (auto-fill-function nil))
    (set-marker end-region-mark end-region)
    (goto-char beg-region)
    (while go-on
      ;; join as much as possible
      (while (f90-join-lines));
      (setq indent (+ (f90-current-indentation) f90-continuation-indent))
      ;; chop the line if necessary
      (while (> (save-excursion (end-of-line) (current-column))
		fill-column)
	(move-to-column fill-column)
	(if (and (looking-at "[ \t]*$") (not (f90-in-string)))
	    (delete-horizontal-space)
	  (f90-find-breakpoint)
	  (f90-break-line 'no-update)
	  (f90-indent-to indent 'no-line-no)))
      (setq go-on (and  (< (point) (marker-position end-region-mark))
			(zerop (forward-line 1))))
      (setq f90-cache-position (point)))
    (setq auto-fill-function af-function)
    (setq f90-cache-position nil)
    (if (string-match "XEmacs" emacs-version)
	(zmacs-deactivate-region)
      (deactivate-mark))))

(defun f90-block-match (beg-block beg-name end-block end-name)
  "Match end-struct with beg-struct and complete end-block if possible.
Leave point at the end of line."
  (search-forward "end" (f90-get-end-of-line))
  (catch 'no-match
    (if (not (f90-equal-symbols beg-block end-block))
	(if end-block
	    (progn
	      (message "END %s does not match %s." end-block beg-block)
	      (end-of-line) 
	      (throw 'no-match nil))
	  (message "Inserting %s." beg-block)
	  (insert (concat " " beg-block)))
      (search-forward end-block))
    (if (not (f90-equal-symbols beg-name end-name))
	(cond ((and beg-name (not end-name)) 
	       (message "Inserting %s." beg-name)
	       (insert (concat " " beg-name)))
	      ((and beg-name end-name) 
	       (message "Replacing %s with %s." end-name beg-name)
	       (search-forward end-name)
	       (replace-match beg-name))
	      ((and (not beg-name) end-name) 
	       (message "Deleting %s." end-name)
	       (search-forward end-name)
	       (replace-match "")))
      (if end-name (search-forward end-name)))
    (if (not (looking-at "[ \t]*!")) (delete-horizontal-space))))

(defun f90-match-end ()
  "From an end foo statement, find the corresponding foo including name."
  (interactive)
  (let ((count 1) (top-of-window (window-start)) (matching-beg nil)
	(end-point (point)) (case-fold-search t)
	beg-name end-name beg-block end-block end-struct)
    (if (save-excursion (beginning-of-line) (skip-chars-forward " \t0-9")
			(setq end-struct (f90-looking-at-program-block-end)))
	(progn
	  (setq end-block (car end-struct))
	  (setq end-name  (car (cdr end-struct)))
	  (save-excursion
	    (beginning-of-line)
	    (while (and (not (zerop count))
			(re-search-backward 
			 (concat "\\(" f90-blocks-re "\\)") nil t))
	      (beginning-of-line) (skip-chars-forward " \t0-9")
	      (cond ((setq matching-beg
			   (cond
			    ((f90-looking-at-do))
			    ((f90-looking-at-if-then))
			    ((f90-looking-at-where-or-forall))
			    ((f90-looking-at-select-case))
			    ((f90-looking-at-type-like))
			    ((f90-looking-at-program-block-start))))
		     (setq count (- count 1)))
		    ((looking-at (concat "end[ \t]*" f90-blocks-re "\\b"))
		     (setq count (+ count 1)))))
	    (if (not (zerop count))
		(message "No matching beginning.")
	      (f90-update-line)
	      (if (eq f90-smart-end 'blink)
		  (if (< (point) top-of-window)
		      (message "Matches %d: %s"
			       (what-line)
			       (buffer-substring
				(progn (beginning-of-line) (point))
				(progn (end-of-line) (point))))
		    (sit-for 1)))
	      (setq beg-block (car matching-beg))
	      (setq beg-name (car (cdr matching-beg)))
	      (goto-char end-point)
	      (beginning-of-line)
	      (f90-block-match beg-block beg-name end-block end-name)))))))

(defun f90-insert-end ()
  "Inserts an complete end statement matching beginning of present block."
  (interactive)
  (let ((f90-smart-end (if f90-smart-end f90-smart-end 'blink)))
    (insert "end")
    (f90-indent-new-line)))

;; abbrevs and keywords

(defun f90-abbrev-start ()
  "Typing `\\[help-command] or `? lists all the F90 abbrevs. 
Any other key combination is executed normally."
  (interactive)
  (let (e c)
    (insert last-command-char)
    (setq e (next-command-event)
	  c (if (string-match "XEmacs" emacs-version)
		(event-to-character e)
	      (read-event)))
    ;; insert char if not equal to `?'
    (if (or (= c ??) (eq c help-char))
	(f90-abbrev-help)
      (if (string-match "XEmacs" emacs-version)
	  (setq unread-command-event e)
	(setq unread-command-events (list c))))))

(defun f90-abbrev-help ()
  "List the currently defined abbrevs in F90 mode."
  (interactive)
  (message "Listing abbrev table...")
  (display-buffer (f90-prepare-abbrev-list-buffer))
  (message "Listing abbrev table...done"))

(defun f90-prepare-abbrev-list-buffer ()
  (save-excursion
    (set-buffer (get-buffer-create "*Abbrevs*"))
    (erase-buffer)
    (insert-abbrev-table-description 'f90-mode-abbrev-table t)
    (goto-char (point-min))
    (set-buffer-modified-p nil)
    (edit-abbrevs-mode))
  (get-buffer-create "*Abbrevs*"))

(defun f90-upcase-keywords ()
  "Upcase all F90 keywords in the buffer."
  (interactive)
  (f90-change-keywords 'upcase-word))

(defun f90-capitalize-keywords ()
  "Capitalize all F90 keywords in the buffer."
  (interactive)
  (f90-change-keywords 'capitalize-word))

(defun f90-downcase-keywords ()
  "Downcase all F90 keywords in the buffer."
  (interactive)
  (f90-change-keywords 'downcase-word))

(defun f90-upcase-region-keywords (beg end)
  "Upcase all F90 keywords in the region."
  (interactive "*r")
  (f90-change-keywords 'upcase-word beg end))

(defun f90-capitalize-region-keywords (beg end)
  "Capitalize all F90 keywords in the region."
  (interactive "*r")
  (f90-change-keywords 'capitalize-word beg end))

(defun f90-downcase-region-keywords (beg end)
  "Downcase all F90 keywords in the region."
  (interactive "*r")
  (f90-change-keywords 'downcase-word beg end))

;; Change the keywords according to argument.
(defun f90-change-keywords (change-word &optional beg end)
  (save-excursion
    (setq beg (if beg beg (point-min)))
    (setq end (if end end (point-max)))
    (let ((keyword-re 
	   (concat "\\("
		   f90-keywords-re "\\|" f90-procedures-re "\\|"
		   f90-hpf-keywords-re "\\|" f90-operators-re "\\)"))
	  (ref-point (point-min)) state
	  (modified (buffer-modified-p)) saveword back-point)
      (goto-char beg)
      (unwind-protect
	  (while (re-search-forward keyword-re end t)
	    (if (progn
		  (setq state (parse-partial-sexp ref-point (point)))
		  (or (nth 3 state) (nth 4 state)
		      (save-excursion	; Check for cpp directive.
			(beginning-of-line)
			(skip-chars-forward " \t0-9")
			(looking-at "#"))))
		()
	      (setq ref-point (point)
		    back-point (save-excursion (backward-word 1) (point)))
	      (setq saveword (buffer-substring back-point ref-point))
	      (funcall change-word -1)
	      (or (string= saveword (buffer-substring back-point ref-point))
		  (setq modified t))))
	(or modified (set-buffer-modified-p nil))))))

(provide 'f90)

;;; f90.el ends here