1;;; f90.el --- Fortran-90 mode (free format)
2
3;; Copyright (C) 1995, 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005,
4;;   2006, 2007  Free Software Foundation, Inc.
5
6;; Author: Torbj\"orn Einarsson <Torbjorn.Einarsson@era.ericsson.se>
7;; Maintainer: Glenn Morris <rgm@gnu.org>
8;; Keywords: fortran, f90, languages
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs; see the file COPYING.  If not, write to the
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
26
27;;; Commentary:
28
29;; Major mode for editing F90 programs in FREE FORMAT.
30;; The minor language revision F95 is also supported (with font-locking).
31
32;; Knows about continuation lines, named structured statements, and other
33;; features in F90 including HPF (High Performance Fortran) structures.
34;; The basic feature provides accurate indentation of F90 programs.
35;; In addition, there are many more features like automatic matching of all
36;; end statements, an auto-fill function to break long lines, a join-lines
37;; function which joins continued lines, etc.
38
39;; To facilitate typing, a fairly complete list of abbreviations is provided.
40;; All abbreviations begin with the backquote character "`"
41;; (this requires modification of the syntax-table).
42;; For example, `i expands to integer (if abbrev-mode is on).
43
44;; There are two separate features for altering the appearance of code:
45;;   1) Upcasing or capitalizing of all keywords.
46;;   2) Colors/fonts using font-lock-mode.
47;; Automatic upcase or downcase of keywords is controlled by the variable
48;; f90-auto-keyword-case.
49
50;; The indentations of lines starting with ! is determined by the first of the
51;; following matches (values in the left column are the defaults):
52
53;; start-string/regexp  indent         variable holding start-string/regexp
54;;    !!!                  0
55;;    !hpf\\$ (re)         0              f90-directive-comment-re
56;;    !!$                  0              f90-comment-region
57;;    !      (re)        as code          f90-indented-comment-re
58;;    default            comment-column
59
60;; Ex: Here is the result of 3 different settings of f90-indented-comment-re
61;;     f90-indented-comment-re  !-indentation      !!-indentation
62;;          !                    as code             as code
63;;          !!                   comment-column      as code
64;;          ![^!]                as code             comment-column
65;; Trailing comments are indented to comment-column with indent-for-comment.
66;; The function f90-comment-region toggles insertion of
67;; the variable f90-comment-region in every line of the region.
68
69;; One common convention for free vs. fixed format is that free format files
70;; have the ending .f90 or .f95 while fixed format files have the ending .f.
71;; Emacs automatically loads Fortran files in the appropriate mode based
72;; on extension. You can modify this by adjusting the variable auto-mode-alist.
73;; For example:
74;; (add-to-list 'auto-mode-alist '("\\.f\\'" . f90-mode))
75
76;; Once you have entered f90-mode, you may get more info by using
77;; the command describe-mode (C-h m). For online help use
78;; C-h f <Name of function you want described>, or
79;; C-h v <Name of variable you want described>.
80
81;; To customize f90-mode for your taste, use, for example:
82;; (you don't have to specify values for all the parameters below)
83;;
84;;(add-hook 'f90-mode-hook
85;;      ;; These are the default values.
86;;      '(lambda () (setq f90-do-indent 3
87;;                        f90-if-indent 3
88;;                        f90-type-indent 3
89;;                        f90-program-indent 2
90;;                        f90-continuation-indent 5
91;;                        f90-comment-region "!!$"
92;;                        f90-directive-comment-re "!hpf\\$"
93;;                        f90-indented-comment-re "!"
94;;                        f90-break-delimiters "[-+\\*/><=,% \t]"
95;;                        f90-break-before-delimiters t
96;;                        f90-beginning-ampersand t
97;;                        f90-smart-end 'blink
98;;                        f90-auto-keyword-case nil
99;;                        f90-leave-line-no nil
100;;                        indent-tabs-mode nil
101;;                        f90-font-lock-keywords f90-font-lock-keywords-2
102;;                  )
103;;       ;; These are not default.
104;;       (abbrev-mode 1)             ; turn on abbreviation mode
105;;       (f90-add-imenu-menu)        ; extra menu with functions etc.
106;;       (if f90-auto-keyword-case   ; change case of all keywords on startup
107;;           (f90-change-keywords f90-auto-keyword-case))
108;;	 ))
109;;
110;; in your .emacs file. You can also customize the lists
111;; f90-font-lock-keywords, etc.
112;;
113;; The auto-fill and abbreviation minor modes are accessible from the F90 menu,
114;; or by using M-x auto-fill-mode and M-x abbrev-mode, respectively.
115
116;; Remarks
117;; 1) Line numbers are by default left-justified. If f90-leave-line-no is
118;;    non-nil, the line numbers are never touched.
119;; 2) Multi-; statements like "do i=1,20 ; j=j+i ; end do" are not handled
120;;    correctly, but I imagine them to be rare.
121;; 3) Regexps for hilit19 are no longer supported.
122;; 4) For FIXED FORMAT code, use fortran mode.
123;; 5) This mode does not work under emacs-18.x.
124;; 6) Preprocessor directives, i.e., lines starting with # are left-justified
125;;    and are untouched by all case-changing commands. There is, at present, no
126;;    mechanism for treating multi-line directives (continued by \ ).
127;; 7) f77 do-loops do 10 i=.. ; ; 10 continue are not correctly indented.
128;;    You are urged to use f90-do loops (with labels if you wish).
129;; 8) The highlighting mode under XEmacs is not as complete as under Emacs.
130
131;; List of user commands
132;;   f90-previous-statement         f90-next-statement
133;;   f90-beginning-of-subprogram    f90-end-of-subprogram   f90-mark-subprogram
134;;   f90-comment-region
135;;   f90-indent-line                f90-indent-new-line
136;;   f90-indent-region    (can be called by calling indent-region)
137;;   f90-indent-subprogram
138;;   f90-break-line                 f90-join-lines
139;;   f90-fill-region
140;;   f90-insert-end
141;;   f90-upcase-keywords            f90-upcase-region-keywords
142;;   f90-downcase-keywords          f90-downcase-region-keywords
143;;   f90-capitalize-keywords        f90-capitalize-region-keywords
144;;   f90-add-imenu-menu
145;;   f90-font-lock-1, f90-font-lock-2, f90-font-lock-3, f90-font-lock-4
146
147;; Original author's thanks
148;; Thanks to all the people who have tested the mode. Special thanks to Jens
149;; Bloch Helmers for encouraging me to write this code, for creative
150;; suggestions as well as for the lists of hpf-commands.
151;; Also thanks to the authors of the fortran and pascal modes, on which some
152;; of this code is built.
153
154;;; Code:
155
156;; TODO
157;; Support for align.
158;; OpenMP, preprocessor highlighting.
159
160(defvar comment-auto-fill-only-comments)
161(defvar font-lock-keywords)
162
163;; User options
164
165(defgroup f90 nil
166  "Major mode for editing free format Fortran 90,95 code."
167  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
168  :group 'languages)
169
170(defgroup f90-indent nil
171  "Indentation in free format Fortran."
172  :prefix "f90-"
173  :group  'f90)
174
175
176(defcustom f90-do-indent 3
177  "*Extra indentation applied to DO blocks."
178  :type  'integer
179  :group 'f90-indent)
180
181(defcustom f90-if-indent 3
182  "*Extra indentation applied to IF, SELECT CASE, WHERE and FORALL blocks."
183  :type  'integer
184  :group 'f90-indent)
185
186(defcustom f90-type-indent 3
187  "*Extra indentation applied to TYPE, INTERFACE and BLOCK DATA blocks."
188  :type  'integer
189  :group 'f90-indent)
190
191(defcustom f90-program-indent 2
192  "*Extra indentation applied to PROGRAM, MODULE, SUBROUTINE, FUNCTION blocks."
193  :type  'integer
194  :group 'f90-indent)
195
196(defcustom f90-continuation-indent 5
197  "*Extra indentation applied to continuation lines."
198  :type  'integer
199  :group 'f90-indent)
200
201(defcustom f90-comment-region "!!$"
202  "*String inserted by \\[f90-comment-region] at start of each line in region."
203  :type  'string
204  :group 'f90-indent)
205
206(defcustom f90-indented-comment-re "!"
207  "*Regexp matching comments to indent as code."
208  :type  'regexp
209  :group 'f90-indent)
210
211(defcustom f90-directive-comment-re "!hpf\\$"
212  "*Regexp of comment-like directive like \"!HPF\\\\$\", not to be indented."
213  :type  'regexp
214  :group 'f90-indent)
215
216(defcustom f90-beginning-ampersand t
217  "*Non-nil gives automatic insertion of \& at start of continuation line."
218  :type  'boolean
219  :group 'f90)
220
221(defcustom f90-smart-end 'blink
222  "*Qualification of END statements according to the matching block start.
223For example, the END that closes an IF block is changed to END
224IF.  If the block has a label, this is added as well.  Allowed
225values are 'blink, 'no-blink, and nil.  If nil, nothing is done.
226The other two settings have the same effect, but 'blink
227additionally blinks the cursor to the start of the block."
228  :type  '(choice (const blink) (const no-blink) (const nil))
229  :group 'f90)
230
231(defcustom f90-break-delimiters "[-+\\*/><=,% \t]"
232  "*Regexp matching delimiter characters at which lines may be broken.
233There are certain tokens comprised entirely of characters
234matching this regexp that should not be split, and these are
235specified by the constant `f90-no-break-re'."
236  :type  'regexp
237  :group 'f90)
238
239(defcustom f90-break-before-delimiters t
240  "*Non-nil causes `f90-do-auto-fill' to break lines before delimiters."
241  :type  'boolean
242  :group 'f90)
243
244(defcustom f90-auto-keyword-case nil
245  "*Automatic case conversion of keywords.
246The options are 'downcase-word, 'upcase-word, 'capitalize-word and nil."
247  :type  '(choice (const downcase-word) (const upcase-word)
248                  (const capitalize-word) (const nil))
249  :group 'f90)
250
251(defcustom f90-leave-line-no nil
252  "*If non-nil, line numbers are not left justified."
253  :type  'boolean
254  :group 'f90)
255
256(defcustom f90-mode-hook nil
257  "Hook run when entering F90 mode."
258  :type    'hook
259  :options '(f90-add-imenu-menu)
260  :group   'f90)
261
262;; User options end here.
263
264(defconst f90-keywords-re
265  (regexp-opt '("allocatable" "allocate" "assign" "assignment" "backspace"
266		"block" "call" "case" "character" "close" "common" "complex"
267		"contains" "continue" "cycle" "data" "deallocate"
268		"dimension" "do" "double" "else" "elseif" "elsewhere" "end"
269		"enddo" "endfile" "endif" "entry" "equivalence" "exit"
270		"external" "forall" "format" "function" "goto" "if"
271		"implicit" "include" "inquire" "integer" "intent"
272		"interface" "intrinsic" "logical" "module" "namelist" "none"
273		"nullify" "only" "open" "operator" "optional" "parameter"
274		"pause" "pointer" "precision" "print" "private" "procedure"
275		"program" "public" "read" "real" "recursive" "result" "return"
276		"rewind" "save" "select" "sequence" "stop" "subroutine"
277		"target" "then" "type" "use" "where" "while" "write"
278		;; F95 keywords.
279		"elemental" "pure") 'words)
280  "Regexp used by the function `f90-change-keywords'.")
281
282(defconst f90-keywords-level-3-re
283  (regexp-opt
284   '("allocatable" "allocate" "assign" "assignment" "backspace"
285     "close" "deallocate" "dimension" "endfile" "entry" "equivalence"
286     "external" "inquire" "intent" "intrinsic" "nullify" "only" "open"
287     "operator" "optional" "parameter" "pause" "pointer" "print" "private"
288     "public" "read" "recursive" "result" "rewind" "save" "select"
289     "sequence" "target" "write"
290     ;; F95 keywords.
291     "elemental" "pure") 'words)
292  "Keyword-regexp for font-lock level >= 3.")
293
294(defconst f90-procedures-re
295  (concat "\\<"
296          (regexp-opt
297           '("abs" "achar" "acos" "adjustl" "adjustr" "aimag" "aint"
298             "all" "allocated" "anint" "any" "asin" "associated"
299             "atan" "atan2" "bit_size" "btest" "ceiling" "char" "cmplx"
300             "conjg" "cos" "cosh" "count" "cshift" "date_and_time" "dble"
301             "digits" "dim" "dot_product" "dprod" "eoshift" "epsilon"
302             "exp" "exponent" "floor" "fraction" "huge" "iachar" "iand"
303             "ibclr" "ibits" "ibset" "ichar" "ieor" "index" "int" "ior"
304             "ishft" "ishftc" "kind" "lbound" "len" "len_trim" "lge" "lgt"
305             "lle" "llt" "log" "log10" "logical" "matmul" "max"
306             "maxexponent" "maxloc" "maxval" "merge" "min" "minexponent"
307             "minloc" "minval" "mod" "modulo" "mvbits" "nearest" "nint"
308             "not" "pack" "precision" "present" "product" "radix"
309             ;; Real is taken out here to avoid highlighting declarations.
310             "random_number" "random_seed" "range" ;; "real"
311             "repeat" "reshape" "rrspacing" "scale" "scan"
312             "selected_int_kind" "selected_real_kind" "set_exponent"
313             "shape" "sign" "sin" "sinh" "size" "spacing" "spread" "sqrt"
314             "sum" "system_clock" "tan" "tanh" "tiny" "transfer"
315             "transpose" "trim" "ubound" "unpack" "verify"
316             ;; F95 intrinsic functions.
317             "null" "cpu_time") t)
318          ;; A left parenthesis to avoid highlighting non-procedures.
319          "[ \t]*(")
320  "Regexp whose first part matches F90 intrinsic procedures.")
321
322(defconst f90-operators-re
323  (concat "\\."
324          (regexp-opt '("and" "eq" "eqv" "false" "ge" "gt" "le" "lt" "ne"
325                        "neqv" "not" "or" "true") t)
326          "\\.")
327  "Regexp matching intrinsic operators.")
328
329(defconst f90-hpf-keywords-re
330  (regexp-opt
331   ;; Intrinsic procedures.
332   '("all_prefix" "all_scatter" "all_suffix" "any_prefix"
333     "any_scatter" "any_suffix" "copy_prefix" "copy_scatter"
334     "copy_suffix" "count_prefix" "count_scatter" "count_suffix"
335     "grade_down" "grade_up"
336     "hpf_alignment" "hpf_distribution" "hpf_template" "iall" "iall_prefix"
337     "iall_scatter" "iall_suffix" "iany" "iany_prefix" "iany_scatter"
338     "iany_suffix" "ilen" "iparity" "iparity_prefix"
339     "iparity_scatter" "iparity_suffix" "leadz" "maxval_prefix"
340     "maxval_scatter" "maxval_suffix" "minval_prefix" "minval_scatter"
341     "minval_suffix" "number_of_processors" "parity"
342     "parity_prefix" "parity_scatter" "parity_suffix" "popcnt" "poppar"
343     "processors_shape" "product_prefix" "product_scatter"
344     "product_suffix" "sum_prefix" "sum_scatter" "sum_suffix"
345     ;; Directives.
346     "align" "distribute" "dynamic" "independent" "inherit" "processors"
347     "realign" "redistribute" "template"
348     ;; Keywords.
349     "block" "cyclic" "extrinsic" "new" "onto" "pure" "with") 'words)
350  "Regexp for all HPF keywords, procedures and directives.")
351
352;; Highlighting patterns.
353
354(defvar f90-font-lock-keywords-1
355  (list
356   ;; Special highlighting of "module procedure".
357   '("\\<\\(module[ \t]*procedure\\)\\>" (1 font-lock-keyword-face))
358   ;; Highlight definition of derived type.
359   '("\\<\\(\\(?:end[ \t]*\\)?type\\)\\>\\([^()\n]*::\\)?[ \t]*\\(\\sw+\\)"
360     (1 font-lock-keyword-face) (3 font-lock-function-name-face))
361   ;; Other functions and declarations.
362   '("\\<\\(\\(?:end[ \t]*\\)?\\(program\\|module\\|function\\|\
363subroutine\\)\\|use\\|call\\)\\>[ \t]*\\(\\sw+\\)?"
364     (1 font-lock-keyword-face) (3 font-lock-function-name-face nil t))
365   "\\<\\(\\(end[ \t]*\\)?\\(interface\\|block[ \t]*data\\)\\|contains\\)\\>")
366  "This does fairly subdued highlighting of comments and function calls.")
367
368(defvar f90-font-lock-keywords-2
369  (append
370   f90-font-lock-keywords-1
371   (list
372    ;; Variable declarations (avoid the real function call).
373    '("^[ \t0-9]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|\
374logical\\|double[ \t]*precision\\|*type[ \t]*(\\sw+)\\)\
375\\(.*::\\|[ \t]*(.*)\\)?\\([^&!\n]*\\)"
376      (1 font-lock-type-face t) (4 font-lock-variable-name-face t))
377    ;; do, if, select, where, and forall constructs.
378    '("\\<\\(end[ \t]*\\(do\\|if\\|select\\|forall\\|where\\)\\)\\>\
379\\([ \t]+\\(\\sw+\\)\\)?"
380      (1 font-lock-keyword-face) (3 font-lock-constant-face nil t))
381    '("^[ \t0-9]*\\(\\(\\sw+\\)[ \t]*:[ \t]*\\)?\\(\\(if\\|\
382do\\([ \t]*while\\)?\\|select[ \t]*case\\|where\\|forall\\)\\)\\>"
383      (2 font-lock-constant-face nil t) (3 font-lock-keyword-face))
384    ;; Implicit declaration.
385    '("\\<\\(implicit\\)[ \t]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\
386\\|logical\\|double[ \t]*precision\\|type[ \t]*(\\sw+)\\|none\\)[ \t]*"
387      (1 font-lock-keyword-face) (2 font-lock-type-face))
388    '("\\<\\(namelist\\|common\\)[ \t]*\/\\(\\sw+\\)?\/"
389      (1 font-lock-keyword-face) (2 font-lock-constant-face nil t))
390    "\\<else\\([ \t]*if\\|where\\)?\\>"
391    '("\\(&\\)[ \t]*\\(!\\|$\\)"  (1 font-lock-keyword-face))
392    "\\<\\(then\\|continue\\|format\\|include\\|stop\\|return\\)\\>"
393    '("\\<\\(exit\\|cycle\\)[ \t]*\\(\\sw+\\)?\\>"
394      (1 font-lock-keyword-face) (2 font-lock-constant-face nil t))
395    '("\\<\\(case\\)[ \t]*\\(default\\|(\\)" . 1)
396    '("\\<\\(do\\|go *to\\)\\>[ \t]*\\([0-9]+\\)"
397      (1 font-lock-keyword-face) (2 font-lock-constant-face))
398    ;; Line numbers (lines whose first character after number is letter).
399    '("^[ \t]*\\([0-9]+\\)[ \t]*[a-z]+" (1 font-lock-constant-face t))))
400  "Highlights declarations, do-loops and other constructs.")
401
402(defvar f90-font-lock-keywords-3
403  (append f90-font-lock-keywords-2
404          (list
405           f90-keywords-level-3-re
406           f90-operators-re
407           (list f90-procedures-re '(1 font-lock-keyword-face keep))
408           "\\<real\\>"			; avoid overwriting real defs
409           ))
410  "Highlights all F90 keywords and intrinsic procedures.")
411
412(defvar f90-font-lock-keywords-4
413  (append f90-font-lock-keywords-3
414          (list f90-hpf-keywords-re))
415  "Highlights all F90 and HPF keywords.")
416
417(defvar f90-font-lock-keywords
418  f90-font-lock-keywords-2
419  "*Default expressions to highlight in F90 mode.
420Can be overridden by the value of `font-lock-maximum-decoration'.")
421
422
423(defvar f90-mode-syntax-table
424  (let ((table (make-syntax-table)))
425    (modify-syntax-entry ?\! "<"  table) ; begin comment
426    (modify-syntax-entry ?\n ">"  table) ; end comment
427    (modify-syntax-entry ?_  "w"  table) ; underscore in names
428    (modify-syntax-entry ?\' "\"" table) ; string quote
429    (modify-syntax-entry ?\" "\"" table) ; string quote
430    (modify-syntax-entry ?\` "w"  table) ; for abbrevs
431    (modify-syntax-entry ?\r " "  table) ; return is whitespace
432    (modify-syntax-entry ?+  "."  table) ; punctuation
433    (modify-syntax-entry ?-  "."  table)
434    (modify-syntax-entry ?=  "."  table)
435    (modify-syntax-entry ?*  "."  table)
436    (modify-syntax-entry ?/  "."  table)
437    ;; I think that the f95 standard leaves the behaviour of \
438    ;; unspecified, but that f2k will require it to be non-special.
439    ;; Use `f90-backslash-not-special' to change.
440    (modify-syntax-entry ?\\ "\\" table) ; escape chars
441    table)
442  "Syntax table used in F90 mode.")
443
444(defvar f90-mode-map
445  (let ((map (make-sparse-keymap)))
446    (define-key map "`"        'f90-abbrev-start)
447    (define-key map "\C-c;"    'f90-comment-region)
448    (define-key map "\C-\M-a"  'f90-beginning-of-subprogram)
449    (define-key map "\C-\M-e"  'f90-end-of-subprogram)
450    (define-key map "\C-\M-h"  'f90-mark-subprogram)
451    (define-key map "\C-\M-n"  'f90-end-of-block)
452    (define-key map "\C-\M-p"  'f90-beginning-of-block)
453    (define-key map "\C-\M-q"  'f90-indent-subprogram)
454    (define-key map "\C-j"     'f90-indent-new-line) ; LFD equals C-j
455    (define-key map "\r"       'newline)
456    (define-key map "\C-c\r"   'f90-break-line)
457;;;  (define-key map [M-return] 'f90-break-line)
458    (define-key map "\C-c\C-a" 'f90-previous-block)
459    (define-key map "\C-c\C-e" 'f90-next-block)
460    (define-key map "\C-c\C-d" 'f90-join-lines)
461    (define-key map "\C-c\C-f" 'f90-fill-region)
462    (define-key map "\C-c\C-p" 'f90-previous-statement)
463    (define-key map "\C-c\C-n" 'f90-next-statement)
464    (define-key map "\C-c\C-w" 'f90-insert-end)
465    (define-key map "\t"       'f90-indent-line)
466    (define-key map ","        'f90-electric-insert)
467    (define-key map "+"        'f90-electric-insert)
468    (define-key map "-"        'f90-electric-insert)
469    (define-key map "*"        'f90-electric-insert)
470    (define-key map "/"        'f90-electric-insert)
471
472    (easy-menu-define f90-menu map "Menu for F90 mode."
473      `("F90"
474        ("Customization"
475         ,(custom-menu-create 'f90)
476         ["Set"  Custom-set t]
477         ["Save" Custom-save t]
478         ["Reset to Current" Custom-reset-current t]
479         ["Reset to Saved"   Custom-reset-saved t]
480         ["Reset to Standard Settings" Custom-reset-standard t]
481         )
482        "--"
483        ["Indent Subprogram"       f90-indent-subprogram       t]
484        ["Mark Subprogram"         f90-mark-subprogram         t]
485        ["Beginning of Subprogram" f90-beginning-of-subprogram t]
486        ["End of Subprogram"       f90-end-of-subprogram       t]
487        "--"
488        ["(Un)Comment Region" f90-comment-region mark-active]
489        ["Indent Region"      f90-indent-region  mark-active]
490        ["Fill Region"        f90-fill-region    mark-active]
491        "--"
492        ["Break Line at Point"     f90-break-line t]
493        ["Join with Previous Line" f90-join-lines t]
494        ["Insert Block End"        f90-insert-end t]
495        "--"
496        ("Highlighting"
497         ["Toggle font-lock-mode" font-lock-mode :selected font-lock-mode
498          :style toggle]
499         "--"
500         ["Light highlighting (level 1)"    f90-font-lock-1 t]
501         ["Moderate highlighting (level 2)" f90-font-lock-2 t]
502         ["Heavy highlighting (level 3)"    f90-font-lock-3 t]
503         ["Maximum highlighting (level 4)"  f90-font-lock-4 t]
504         )
505        ("Change Keyword Case"
506         ["Upcase Keywords (buffer)"     f90-upcase-keywords     t]
507         ["Capitalize Keywords (buffer)" f90-capitalize-keywords t]
508         ["Downcase Keywords (buffer)"   f90-downcase-keywords   t]
509         "--"
510         ["Upcase Keywords (region)"     f90-upcase-region-keywords
511          mark-active]
512         ["Capitalize Keywords (region)" f90-capitalize-region-keywords
513          mark-active]
514         ["Downcase Keywords (region)"   f90-downcase-region-keywords
515          mark-active]
516         )
517        "--"
518        ["Toggle auto-fill"   auto-fill-mode :selected auto-fill-function
519         :style toggle]
520        ["Toggle abbrev-mode" abbrev-mode    :selected abbrev-mode
521         :style toggle]
522        ["Add imenu Menu" f90-add-imenu-menu
523         :active   (not (lookup-key (current-local-map) [menu-bar index]))
524         :included (fboundp 'imenu-add-to-menubar)]))
525    map)
526  "Keymap used in F90 mode.")
527
528
529(defun f90-font-lock-1 ()
530  "Set `font-lock-keywords' to `f90-font-lock-keywords-1'."
531  (interactive)
532  (font-lock-mode 1)
533  (setq font-lock-keywords f90-font-lock-keywords-1)
534  (font-lock-fontify-buffer))
535
536(defun f90-font-lock-2 ()
537  "Set `font-lock-keywords' to `f90-font-lock-keywords-2'."
538  (interactive)
539  (font-lock-mode 1)
540  (setq font-lock-keywords f90-font-lock-keywords-2)
541  (font-lock-fontify-buffer))
542
543(defun f90-font-lock-3 ()
544  "Set `font-lock-keywords' to `f90-font-lock-keywords-3'."
545  (interactive)
546  (font-lock-mode 1)
547  (setq font-lock-keywords f90-font-lock-keywords-3)
548  (font-lock-fontify-buffer))
549
550(defun f90-font-lock-4 ()
551  "Set `font-lock-keywords' to `f90-font-lock-keywords-4'."
552  (interactive)
553  (font-lock-mode 1)
554  (setq font-lock-keywords f90-font-lock-keywords-4)
555  (font-lock-fontify-buffer))
556
557
558;; Regexps for finding program structures.
559(defconst f90-blocks-re
560  (concat "\\(block[ \t]*data\\|"
561          (regexp-opt '("do" "if" "interface" "function" "module" "program"
562                        "select" "subroutine" "type" "where" "forall"))
563          "\\)\\>")
564  "Regexp potentially indicating a \"block\" of F90 code.")
565
566(defconst f90-program-block-re
567  (regexp-opt '("program" "module" "subroutine" "function") 'paren)
568  "Regexp used to locate the start/end of a \"subprogram\".")
569
570(defconst f90-else-like-re
571  "\\(else\\([ \t]*if\\|where\\)?\\|case[ \t]*\\(default\\|(\\)\\)"
572  "Regexp matching an ELSE IF, ELSEWHERE, CASE statement.")
573
574(defconst f90-end-if-re
575  (concat "end[ \t]*"
576          (regexp-opt '("if" "select" "where" "forall") 'paren)
577          "\\>")
578  "Regexp matching the end of an IF, SELECT, WHERE, FORALL block.")
579
580(defconst f90-end-type-re
581  "end[ \t]*\\(type\\|interface\\|block[ \t]*data\\)\\>"
582  "Regexp matching the end of a TYPE, INTERFACE, BLOCK DATA section.")
583
584(defconst f90-type-def-re
585  "\\<\\(type\\)\\>\\(?:[^()\n]*::\\)?[ \t]*\\(\\sw+\\)"
586  "Regexp matching the definition of a derived type.")
587
588(defconst f90-no-break-re
589  (regexp-opt '("**" "//" "=>" ">=" "<=" "==" "/=") 'paren)
590  "Regexp specifying where not to break lines when filling.
591This regexp matches certain tokens comprised entirely of
592characters matching the regexp `f90-break-delimiters' that should
593not be split by filling.  Each element is assumed to be two
594characters long.")
595
596(defvar f90-cache-position nil
597  "Temporary position used to speed up region operations.")
598(make-variable-buffer-local 'f90-cache-position)
599
600
601;; Hideshow support.
602(defconst f90-end-block-re
603  (concat "^[ \t0-9]*\\<end[ \t]*"
604          (regexp-opt '("do" "if" "forall" "function" "interface"
605                        "module" "program" "select" "subroutine"
606                        "type" "where" ) t)
607          "[ \t]*\\sw*")
608  "Regexp matching the end of an F90 \"block\", from the line start.
609Used in the F90 entry in `hs-special-modes-alist'.")
610
611;; Ignore the fact that FUNCTION, SUBROUTINE, WHERE, FORALL have a
612;; following "(".  DO, CASE, IF can have labels.
613(defconst f90-start-block-re
614  (concat
615   "^[ \t0-9]*"                         ; statement number
616   "\\(\\("
617   "\\(\\sw+[ \t]*:[ \t]*\\)?"          ; structure label
618   "\\(do\\|select[ \t]*case\\|"
619   ;; See comments in fortran-start-block-re for the problems of IF.
620   "if[ \t]*(\\(.*\\|"
621   ".*\n\\([^if]*\\([^i].\\|.[^f]\\|.\\>\\)\\)\\)\\<then\\|"
622   ;; Distinguish WHERE block from isolated WHERE.
623   "\\(where\\|forall\\)[ \t]*(.*)[ \t]*\\(!\\|$\\)\\)\\)"
624   "\\|"
625   "program\\|interface\\|module\\|type\\|function\\|subroutine"
626   "\\)"
627   "[ \t]*")
628  "Regexp matching the start of an F90 \"block\", from the line start.
629A simple regexp cannot do this in fully correct fashion, so this
630tries to strike a compromise between complexity and flexibility.
631Used in the F90 entry in `hs-special-modes-alist'.")
632
633;; hs-special-modes-alist is autoloaded.
634(add-to-list 'hs-special-modes-alist
635             `(f90-mode ,f90-start-block-re ,f90-end-block-re
636                        "!" f90-end-of-block nil))
637
638
639;; Imenu support.
640(defvar f90-imenu-generic-expression
641  (let ((good-char "[^!\"\&\n \t]") (not-e "[^e!\n\"\& \t]")
642	(not-n "[^n!\n\"\& \t]") (not-d "[^d!\n\"\& \t]"))
643    (list
644     '(nil "^[ \t0-9]*program[ \t]+\\(\\sw+\\)" 1)
645     '("Modules" "^[ \t0-9]*module[ \t]+\\(\\sw+\\)[ \t]*\\(!\\|$\\)" 1)
646     '("Types" "^[ \t0-9]*type[ \t]+\\(\\sw+\\)" 1)
647     (list
648      "Procedures"
649      (concat
650       "^[ \t0-9]*"
651       "\\("
652       ;; At least three non-space characters before function/subroutine.
653       ;; Check that the last three non-space characters do not spell E N D.
654       "[^!\"\&\n]*\\("
655       not-e good-char good-char "\\|"
656       good-char not-n good-char "\\|"
657       good-char good-char not-d "\\)"
658       "\\|"
659       ;; Less than three non-space characters before function/subroutine.
660       good-char "?" good-char "?"
661       "\\)"
662       "[ \t]*\\(function\\|subroutine\\)[ \t]+\\(\\sw+\\)")
663      4)))
664  "Value for `imenu-generic-expression' in F90 mode.")
665
666(defun f90-add-imenu-menu ()
667  "Add an imenu menu to the menubar."
668  (interactive)
669  (if (lookup-key (current-local-map) [menu-bar index])
670      (message "%s" "F90-imenu already exists.")
671    (imenu-add-to-menubar "F90-imenu")
672    (redraw-frame (selected-frame))))
673
674
675;; Abbrevs have generally two letters, except standard types `c, `i, `r, `t.
676(defvar f90-mode-abbrev-table
677  (progn
678    (define-abbrev-table 'f90-mode-abbrev-table nil)
679    f90-mode-abbrev-table)
680  "Abbrev table for F90 mode.")
681
682(let (abbrevs-changed)
683  ;; Use the 6th arg (SYSTEM-FLAG) of define-abbrev if possible.
684  ;; A little baroque to quieten the byte-compiler.
685  (mapcar
686   (function (lambda (element)
687               (condition-case nil
688                   (apply 'define-abbrev f90-mode-abbrev-table
689                          (append element '(nil 0 t)))
690                 (wrong-number-of-arguments
691                  (apply 'define-abbrev f90-mode-abbrev-table
692                         (append element '(nil 0)))))))
693   '(("`al"  "allocate"     )
694     ("`ab"  "allocatable"  )
695     ("`as"  "assignment"   )
696     ("`ba"  "backspace"    )
697     ("`bd"  "block data"   )
698     ("`c"   "character"    )
699     ("`cl"  "close"        )
700     ("`cm"  "common"       )
701     ("`cx"  "complex"      )
702     ("`cn"  "contains"     )
703     ("`cy"  "cycle"        )
704     ("`de"  "deallocate"   )
705     ("`df"  "define"       )
706     ("`di"  "dimension"    )
707     ("`dp"  "double precision")
708     ("`dw"  "do while"     )
709     ("`el"  "else"         )
710     ("`eli" "else if"      )
711     ("`elw" "elsewhere"    )
712     ("`eq"  "equivalence"  )
713     ("`ex"  "external"     )
714     ("`ey"  "entry"        )
715     ("`fl"  "forall"       )
716     ("`fo"  "format"       )
717     ("`fu"  "function"     )
718     ("`fa"  ".false."      )
719     ("`im"  "implicit none")
720     ("`in"  "include"      )
721     ("`i"   "integer"      )
722     ("`it"  "intent"       )
723     ("`if"  "interface"    )
724     ("`lo"  "logical"      )
725     ("`mo"  "module"       )
726     ("`na"  "namelist"     )
727     ("`nu"  "nullify"      )
728     ("`op"  "optional"     )
729     ("`pa"  "parameter"    )
730     ("`po"  "pointer"      )
731     ("`pr"  "print"        )
732     ("`pi"  "private"      )
733     ("`pm"  "program"      )
734     ("`pu"  "public"       )
735     ("`r"   "real"         )
736     ("`rc"  "recursive"    )
737     ("`rt"  "return"       )
738     ("`rw"  "rewind"       )
739     ("`se"  "select"       )
740     ("`sq"  "sequence"     )
741     ("`su"  "subroutine"   )
742     ("`ta"  "target"       )
743     ("`tr"  ".true."       )
744     ("`t"   "type"         )
745     ("`wh"  "where"        )
746     ("`wr"  "write"        ))))
747
748
749;;;###autoload
750(defun f90-mode ()
751  "Major mode for editing Fortran 90,95 code in free format.
752For fixed format code, use `fortran-mode'.
753
754\\[f90-indent-line] indents the current line.
755\\[f90-indent-new-line] indents current line and creates a new\
756 indented line.
757\\[f90-indent-subprogram] indents the current subprogram.
758
759Type `? or `\\[help-command] to display a list of built-in\
760 abbrevs for F90 keywords.
761
762Key definitions:
763\\{f90-mode-map}
764
765Variables controlling indentation style and extra features:
766
767`f90-do-indent'
768  Extra indentation within do blocks (default 3).
769`f90-if-indent'
770  Extra indentation within if/select case/where/forall blocks (default 3).
771`f90-type-indent'
772  Extra indentation within type/interface/block-data blocks (default 3).
773`f90-program-indent'
774  Extra indentation within program/module/subroutine/function blocks
775  (default 2).
776`f90-continuation-indent'
777  Extra indentation applied to continuation lines (default 5).
778`f90-comment-region'
779  String inserted by function \\[f90-comment-region] at start of each
780  line in region (default \"!!!$\").
781`f90-indented-comment-re'
782  Regexp determining the type of comment to be intended like code
783  (default \"!\").
784`f90-directive-comment-re'
785  Regexp of comment-like directive like \"!HPF\\\\$\", not to be indented
786  (default \"!hpf\\\\$\").
787`f90-break-delimiters'
788  Regexp holding list of delimiters at which lines may be broken
789  (default \"[-+*/><=,% \\t]\").
790`f90-break-before-delimiters'
791  Non-nil causes `f90-do-auto-fill' to break lines before delimiters
792  (default t).
793`f90-beginning-ampersand'
794  Automatic insertion of \& at beginning of continuation lines (default t).
795`f90-smart-end'
796  From an END statement, check and fill the end using matching block start.
797  Allowed values are 'blink, 'no-blink, and nil, which determine
798  whether to blink the matching beginning (default 'blink).
799`f90-auto-keyword-case'
800  Automatic change of case of keywords (default nil).
801  The possibilities are 'downcase-word, 'upcase-word, 'capitalize-word.
802`f90-leave-line-no'
803  Do not left-justify line numbers (default nil).
804
805Turning on F90 mode calls the value of the variable `f90-mode-hook'
806with no args, if that value is non-nil."
807  (interactive)
808  (kill-all-local-variables)
809  (setq major-mode 'f90-mode
810        mode-name "F90"
811        local-abbrev-table f90-mode-abbrev-table)
812  (set-syntax-table f90-mode-syntax-table)
813  (use-local-map f90-mode-map)
814  (set (make-local-variable 'indent-line-function) 'f90-indent-line)
815  (set (make-local-variable 'indent-region-function) 'f90-indent-region)
816  (set (make-local-variable 'require-final-newline) mode-require-final-newline)
817  (set (make-local-variable 'comment-start) "!")
818  (set (make-local-variable 'comment-start-skip) "!+ *")
819  (set (make-local-variable 'comment-indent-function) 'f90-comment-indent)
820  (set (make-local-variable 'abbrev-all-caps) t)
821  (set (make-local-variable 'normal-auto-fill-function) 'f90-do-auto-fill)
822  (setq indent-tabs-mode nil)           ; auto buffer local
823  (set (make-local-variable 'font-lock-defaults)
824       '((f90-font-lock-keywords f90-font-lock-keywords-1
825                                 f90-font-lock-keywords-2
826                                 f90-font-lock-keywords-3
827                                 f90-font-lock-keywords-4)
828         nil t))
829  (set (make-local-variable 'imenu-case-fold-search) t)
830  (set (make-local-variable 'imenu-generic-expression)
831       f90-imenu-generic-expression)
832  (set (make-local-variable 'beginning-of-defun-function)
833       'f90-beginning-of-subprogram)
834  (set (make-local-variable 'end-of-defun-function) 'f90-end-of-subprogram)
835  (set (make-local-variable 'add-log-current-defun-function)
836       #'f90-current-defun)
837  (run-mode-hooks 'f90-mode-hook))
838
839
840;; Inline-functions.
841(defsubst f90-in-string ()
842  "Return non-nil if point is inside a string.
843Checks from `point-min', or `f90-cache-position', if that is non-nil
844and lies before point."
845  (let ((beg-pnt
846	 (if (and f90-cache-position (> (point) f90-cache-position))
847	     f90-cache-position
848	   (point-min))))
849    (nth 3 (parse-partial-sexp beg-pnt (point)))))
850
851(defsubst f90-in-comment ()
852  "Return non-nil if point is inside a comment.
853Checks from `point-min', or `f90-cache-position', if that is non-nil
854and lies before point."
855  (let ((beg-pnt
856	 (if (and f90-cache-position (> (point) f90-cache-position))
857	     f90-cache-position
858	   (point-min))))
859    (nth 4 (parse-partial-sexp beg-pnt (point)))))
860
861(defsubst f90-line-continued ()
862  "Return t if the current line is a continued one.
863This includes comment lines embedded in continued lines, but
864not the last line of a continued statement."
865  (save-excursion
866    (beginning-of-line)
867    (while (and (looking-at "[ \t]*\\(!\\|$\\)") (zerop (forward-line -1))))
868    (end-of-line)
869    (while (f90-in-comment)
870      (search-backward "!" (line-beginning-position))
871      (skip-chars-backward "!"))
872    (skip-chars-backward " \t")
873    (= (preceding-char) ?&)))
874
875;; GM this is not right, eg a continuation line starting with a number.
876;; Need f90-code-start-position function.
877;; And yet, things seems to work with this...
878;; cf f90-indent-line
879;;     (beginning-of-line)           ; digits after & \n are not line-nos
880;;     (if (not (save-excursion (and (f90-previous-statement)
881;;                                   (f90-line-continued))))
882;;         (f90-indent-line-no)
883(defsubst f90-current-indentation ()
884  "Return indentation of current line.
885Line-numbers are considered whitespace characters."
886  (save-excursion (beginning-of-line) (skip-chars-forward " \t0-9")))
887
888(defsubst f90-indent-to (col &optional no-line-number)
889  "Indent current line to column COL.
890If optional argument NO-LINE-NUMBER is nil, jump over a possible
891line-number before indenting."
892  (beginning-of-line)
893  (or no-line-number
894      (skip-chars-forward " \t0-9"))
895  (delete-horizontal-space)
896  ;; Leave >= 1 space after line number.
897  (indent-to col (if (zerop (current-column)) 0 1)))
898
899(defsubst f90-get-present-comment-type ()
900  "If point lies within a comment, return the string starting the comment.
901For example, \"!\" or \"!!\", followed by the appropriate amount of
902whitespace, if any."
903  ;; Include the whitespace for consistent auto-filling of comment blocks.
904  (save-excursion
905    (when (f90-in-comment)
906      (beginning-of-line)
907      (re-search-forward "!+[ \t]*" (line-end-position))
908      (while (f90-in-string)
909        (re-search-forward "!+[ \t]*" (line-end-position)))
910      (match-string-no-properties 0))))
911
912(defsubst f90-equal-symbols (a b)
913  "Compare strings A and B neglecting case and allowing for nil value."
914  (equal (if a (downcase a) nil)
915         (if b (downcase b) nil)))
916
917(defsubst f90-looking-at-do ()
918  "Return (\"do\" NAME) if a do statement starts after point.
919NAME is nil if the statement has no label."
920  (if (looking-at "\\(\\(\\sw+\\)[ \t]*:\\)?[ \t]*\\(do\\)\\>")
921      (list (match-string 3) (match-string 2))))
922
923(defsubst f90-looking-at-select-case ()
924  "Return (\"select\" NAME) if a select-case statement starts after point.
925NAME is nil if the statement has no label."
926  (if (looking-at "\\(\\(\\sw+\\)[ \t]*:\\)?[ \t]*\
927\\(select\\)[ \t]*case[ \t]*(")
928      (list (match-string 3) (match-string 2))))
929
930(defsubst f90-looking-at-if-then ()
931  "Return (\"if\" NAME) if an if () then statement starts after point.
932NAME is nil if the statement has no label."
933  (save-excursion
934    (when (looking-at "\\(\\(\\sw+\\)[ \t]*:\\)?[ \t]*\\(if\\)\\>")
935      (let ((struct (match-string 3))
936            (label (match-string 2))
937            (pos (scan-lists (point) 1 0)))
938        (and pos (goto-char pos))
939        (skip-chars-forward " \t")
940        (if (or (looking-at "then\\>")
941                (when (f90-line-continued)
942                  (f90-next-statement)
943                  (skip-chars-forward " \t0-9&")
944                  (looking-at "then\\>")))
945            (list struct label))))))
946
947(defsubst f90-looking-at-where-or-forall ()
948  "Return (KIND NAME) if a where or forall block starts after point.
949NAME is nil if the statement has no label."
950  (save-excursion
951    (when (looking-at "\\(\\(\\sw+\\)[ \t]*:\\)?[ \t]*\
952\\(where\\|forall\\)\\>")
953      (let ((struct (match-string 3))
954            (label (match-string 2))
955            (pos (scan-lists (point) 1 0)))
956        (and pos (goto-char pos))
957        (skip-chars-forward " \t")
958        (if (looking-at "\\(!\\|$\\)") (list struct label))))))
959
960(defsubst f90-looking-at-type-like ()
961  "Return (KIND NAME) if a type/interface/block-data block starts after point.
962NAME is non-nil only for type."
963  (cond
964   ((looking-at f90-type-def-re)
965    (list (match-string 1) (match-string 2)))
966   ((looking-at "\\(interface\\|block[\t]*data\\)\\>")
967    (list (match-string 1) nil))))
968
969(defsubst f90-looking-at-program-block-start ()
970  "Return (KIND NAME) if a program block with name NAME starts after point."
971;;;NAME is nil for an un-named main PROGRAM block."
972  (cond
973   ((looking-at "\\(program\\)[ \t]+\\(\\sw+\\)\\>")
974    (list (match-string 1) (match-string 2)))
975   ((and (not (looking-at "module[ \t]*procedure\\>"))
976	 (looking-at "\\(module\\)[ \t]+\\(\\sw+\\)\\>"))
977    (list (match-string 1) (match-string 2)))
978   ((and (not (looking-at "end[ \t]*\\(function\\|subroutine\\)"))
979	 (looking-at "[^!'\"\&\n]*\\(function\\|subroutine\\)[ \t]+\
980\\(\\sw+\\)"))
981    (list (match-string 1) (match-string 2)))))
982;; Following will match an un-named main program block; however
983;; one needs to check if there is an actual PROGRAM statement after
984;; point (and before any END program). Adding this will require
985;; change to eg f90-calculate-indent.
986;;;   ((save-excursion
987;;;     (not (f90-previous-statement)))
988;;;    '("program" nil))))
989
990(defsubst f90-looking-at-program-block-end ()
991  "Return (KIND NAME) if a block with name NAME ends after point."
992  (if (looking-at (concat "end[ \t]*" f90-blocks-re
993			  "?\\([ \t]+\\(\\sw+\\)\\)?\\>"))
994      (list (match-string 1) (match-string 3))))
995
996(defsubst f90-comment-indent ()
997  "Return the indentation to be used for a comment starting at point.
998Used for `comment-indent-function' by F90 mode.
999\"!!!\", `f90-directive-comment-re', variable `f90-comment-region' return 0.
1000`f90-indented-comment-re' (if not trailing code) calls `f90-calculate-indent'.
1001All others return `comment-column', leaving at least one space after code."
1002  (cond ((looking-at "!!!") 0)
1003	((and f90-directive-comment-re
1004	      (looking-at f90-directive-comment-re)) 0)
1005	((looking-at (regexp-quote f90-comment-region)) 0)
1006	((and (looking-at f90-indented-comment-re)
1007	      ;; Don't attempt to indent trailing comment as code.
1008	      (save-excursion
1009		(skip-chars-backward " \t")
1010		(bolp)))
1011	 (f90-calculate-indent))
1012	(t (save-excursion
1013             (skip-chars-backward " \t")
1014             (max (if (bolp) 0 (1+ (current-column))) comment-column)))))
1015
1016(defsubst f90-present-statement-cont ()
1017  "Return continuation properties of present statement.
1018Possible return values are:
1019single - statement is not continued.
1020begin  - current line is the first in a continued statement.
1021end    - current line is the last in a continued statement
1022middle - current line is neither first nor last in a continued statement.
1023Comment lines embedded amongst continued lines return 'middle."
1024  (let (pcont cont)
1025    (save-excursion
1026      (setq pcont (if (f90-previous-statement) (f90-line-continued))))
1027    (setq cont (f90-line-continued))
1028    (cond ((and (not pcont) (not cont)) 'single)
1029 	  ((and (not pcont) cont)       'begin)
1030 	  ((and pcont       (not cont)) 'end)
1031 	  ((and pcont       cont)       'middle)
1032 	  (t (error "The impossible occurred")))))
1033
1034(defsubst f90-indent-line-no ()
1035  "If `f90-leave-line-no' is nil, left-justify a line number.
1036Leaves point at the first non-blank character after the line number.
1037Call from beginning of line."
1038  (and (null f90-leave-line-no) (looking-at "[ \t]+[0-9]")
1039       (delete-horizontal-space))
1040  (skip-chars-forward " \t0-9"))
1041
1042(defsubst f90-no-block-limit ()
1043  "Return nil if point is at the edge of a code block.
1044Searches line forward for \"function\" or \"subroutine\",
1045if all else fails."
1046  (save-excursion
1047    (not (or (looking-at "end")
1048             (looking-at "\\(do\\|if\\|else\\(if\\|where\\)?\
1049\\|select[ \t]*case\\|case\\|where\\|forall\\)\\>")
1050             (looking-at "\\(program\\|module\\|interface\\|\
1051block[ \t]*data\\)\\>")
1052             (looking-at "\\(contains\\|\\sw+[ \t]*:\\)")
1053             (looking-at f90-type-def-re)
1054             (re-search-forward "\\(function\\|subroutine\\)"
1055                                (line-end-position) t)))))
1056
1057(defsubst f90-update-line ()
1058  "Change case of current line as per `f90-auto-keyword-case'."
1059  (if f90-auto-keyword-case
1060      (f90-change-keywords f90-auto-keyword-case
1061                           (line-beginning-position) (line-end-position))))
1062
1063(defun f90-electric-insert (&optional arg)
1064  "Change keyword case and auto-fill line as operators are inserted."
1065  (interactive "*p")
1066  (self-insert-command arg)
1067  (if auto-fill-function (f90-do-auto-fill) ; also updates line
1068    (f90-update-line)))
1069
1070
1071(defun f90-get-correct-indent ()
1072  "Get correct indent for a line starting with line number.
1073Does not check type and subprogram indentation."
1074  (let ((epnt (line-end-position)) icol cont)
1075    (save-excursion
1076      (while (and (f90-previous-statement)
1077		  (or (progn
1078			(setq cont (f90-present-statement-cont))
1079			(or (eq cont 'end) (eq cont 'middle)))
1080		      (looking-at "[ \t]*[0-9]"))))
1081      (setq icol (current-indentation))
1082      (beginning-of-line)
1083      (when (re-search-forward "\\(if\\|do\\|select\\|where\\|forall\\)"
1084                               (line-end-position) t)
1085        (beginning-of-line)
1086        (skip-chars-forward " \t")
1087        (cond ((f90-looking-at-do)
1088               (setq icol (+ icol f90-do-indent)))
1089              ((or (f90-looking-at-if-then)
1090                   (f90-looking-at-where-or-forall)
1091                   (f90-looking-at-select-case))
1092               (setq icol (+ icol f90-if-indent))))
1093        (end-of-line))
1094      (while (re-search-forward
1095	      "\\(if\\|do\\|select\\|where\\|forall\\)" epnt t)
1096	(beginning-of-line)
1097        (skip-chars-forward " \t0-9")
1098	(cond ((f90-looking-at-do)
1099               (setq icol (+ icol f90-do-indent)))
1100              ((or (f90-looking-at-if-then)
1101                   (f90-looking-at-where-or-forall)
1102                   (f90-looking-at-select-case))
1103               (setq icol (+ icol f90-if-indent)))
1104              ((looking-at f90-end-if-re)
1105               (setq icol (- icol f90-if-indent)))
1106              ((looking-at "end[ \t]*do\\>")
1107               (setq icol (- icol f90-do-indent))))
1108	(end-of-line))
1109      icol)))
1110
1111(defun f90-calculate-indent ()
1112  "Calculate the indent column based on previous statements."
1113  (interactive)
1114  (let (icol cont (case-fold-search t) (pnt (point)))
1115    (save-excursion
1116      (if (not (f90-previous-statement))
1117          ;; If f90-previous-statement returns nil, we must have been
1118          ;; called from on or before the first line of the first statement.
1119	  (setq icol (if (save-excursion
1120                           ;; f90-previous-statement has moved us over
1121                           ;; comment/blank lines, so we need to get
1122                           ;; back to the first code statement.
1123                           (when (looking-at "[ \t]*\\([!#]\\|$\\)")
1124                             (f90-next-statement))
1125                           (skip-chars-forward " \t0-9")
1126                           (f90-looking-at-program-block-start))
1127                         0
1128                       ;; No explicit PROGRAM start statement.
1129                       f90-program-indent))
1130	(setq cont (f90-present-statement-cont))
1131	(if (eq cont 'end)
1132	    (while (not (eq 'begin (f90-present-statement-cont)))
1133	      (f90-previous-statement)))
1134	(cond ((eq cont 'begin)
1135	       (setq icol (+ (f90-current-indentation)
1136			     f90-continuation-indent)))
1137	      ((eq cont 'middle) (setq icol (current-indentation)))
1138	      (t (setq icol (f90-current-indentation))
1139		 (skip-chars-forward " \t")
1140		 (if (looking-at "[0-9]")
1141		     (setq icol (f90-get-correct-indent))
1142		   (cond ((or (f90-looking-at-if-then)
1143			      (f90-looking-at-where-or-forall)
1144			      (f90-looking-at-select-case)
1145			      (looking-at f90-else-like-re))
1146			  (setq icol (+ icol f90-if-indent)))
1147			 ((f90-looking-at-do)
1148			  (setq icol (+ icol f90-do-indent)))
1149			 ((f90-looking-at-type-like)
1150			  (setq icol (+ icol f90-type-indent)))
1151			 ((or (f90-looking-at-program-block-start)
1152			      (looking-at "contains[ \t]*\\($\\|!\\)"))
1153			  (setq icol (+ icol f90-program-indent)))))
1154		 (goto-char pnt)
1155		 (beginning-of-line)
1156		 (cond ((looking-at "[ \t]*$"))
1157		       ((looking-at "[ \t]*#") ; check for cpp directive
1158			(setq icol 0))
1159		       (t
1160			(skip-chars-forward " \t0-9")
1161			(cond ((or (looking-at f90-else-like-re)
1162				   (looking-at f90-end-if-re))
1163			       (setq icol (- icol f90-if-indent)))
1164			      ((looking-at "end[ \t]*do\\>")
1165			       (setq icol (- icol f90-do-indent)))
1166			      ((looking-at f90-end-type-re)
1167			       (setq icol (- icol f90-type-indent)))
1168			      ((or (looking-at "contains[ \t]*\\(!\\|$\\)")
1169				   (f90-looking-at-program-block-end))
1170			       (setq icol (- icol f90-program-indent))))))
1171		 ))))
1172    icol))
1173
1174(defun f90-previous-statement ()
1175  "Move point to beginning of the previous F90 statement.
1176If no previous statement is found (i.e. if called from the first
1177statement in the buffer), move to the start of the buffer and
1178return nil.  A statement is a line which is neither blank nor a
1179comment."
1180  (interactive)
1181  (let (not-first-statement)
1182    (beginning-of-line)
1183    (while (and (setq not-first-statement (zerop (forward-line -1)))
1184		(looking-at "[ \t0-9]*\\(!\\|$\\|#\\)")))
1185    not-first-statement))
1186
1187(defun f90-next-statement ()
1188  "Move point to beginning of the next F90 statement.
1189Return nil if no later statement is found."
1190  (interactive)
1191  (let (not-last-statement)
1192    (beginning-of-line)
1193    (while (and (setq not-last-statement
1194		      (and (zerop (forward-line 1))
1195			   (not (eobp))))
1196 		(looking-at "[ \t0-9]*\\(!\\|$\\)")))
1197    not-last-statement))
1198
1199(defun f90-beginning-of-subprogram ()
1200  "Move point to the beginning of the current subprogram.
1201Return (TYPE NAME), or nil if not found."
1202  (interactive)
1203  (let ((count 1) (case-fold-search t) matching-beg)
1204    (beginning-of-line)
1205    (while (and (> count 0)
1206		(re-search-backward f90-program-block-re nil 'move))
1207      (beginning-of-line)
1208      (skip-chars-forward " \t0-9")
1209      (cond ((setq matching-beg (f90-looking-at-program-block-start))
1210             (setq count (1- count)))
1211            ((f90-looking-at-program-block-end)
1212             (setq count (1+ count)))))
1213    (beginning-of-line)
1214    (if (zerop count)
1215	matching-beg
1216      ;; Note this includes the case of an un-named main program,
1217      ;; in which case we go to (point-min).
1218      (message "No beginning found.")
1219      nil)))
1220
1221(defun f90-end-of-subprogram ()
1222  "Move point to the end of the current subprogram.
1223Return (TYPE NAME), or nil if not found."
1224  (interactive)
1225  (let ((case-fold-search t)
1226        (count 1)
1227        matching-end)
1228    (end-of-line)
1229    (while (and (> count 0)
1230		(re-search-forward f90-program-block-re nil 'move))
1231      (beginning-of-line)
1232      (skip-chars-forward " \t0-9")
1233      (cond ((f90-looking-at-program-block-start)
1234	     (setq count (1+ count)))
1235	    ((setq matching-end (f90-looking-at-program-block-end))
1236	     (setq count (1- count))))
1237      (end-of-line))
1238    ;; This means f90-end-of-subprogram followed by f90-start-of-subprogram
1239    ;; has a net non-zero effect, which seems odd.
1240;;;    (forward-line 1)
1241    (if (zerop count)
1242	matching-end
1243      (message "No end found.")
1244      nil)))
1245
1246
1247(defun f90-end-of-block (&optional num)
1248  "Move point forward to the end of the current code block.
1249With optional argument NUM, go forward that many balanced blocks.
1250If NUM is negative, go backward to the start of a block.  Checks
1251for consistency of block types and labels (if present), and
1252completes outermost block if `f90-smart-end' is non-nil.
1253Interactively, pushes mark before moving point."
1254  (interactive "p")
1255  (if (interactive-p) (push-mark (point) t)) ; can move some distance
1256  (and num (< num 0) (f90-beginning-of-block (- num)))
1257  (let ((f90-smart-end (if f90-smart-end 'no-blink)) ; for final match-end
1258        (case-fold-search t)
1259        (count (or num 1))
1260        start-list start-this start-type start-label end-type end-label)
1261    (end-of-line)                       ; probably want this
1262    (while (and (> count 0) (re-search-forward f90-blocks-re nil 'move))
1263      (beginning-of-line)
1264      (skip-chars-forward " \t0-9")
1265      (cond ((or (f90-in-string) (f90-in-comment)))
1266            ((setq start-this
1267                   (or
1268                    (f90-looking-at-do)
1269                    (f90-looking-at-select-case)
1270                    (f90-looking-at-type-like)
1271                    (f90-looking-at-program-block-start)
1272                    (f90-looking-at-if-then)
1273                    (f90-looking-at-where-or-forall)))
1274             (setq start-list (cons start-this start-list) ; not add-to-list!
1275                   count (1+ count)))
1276            ((looking-at (concat "end[ \t]*" f90-blocks-re
1277                                 "[ \t]*\\(\\sw+\\)?"))
1278             (setq end-type (match-string 1)
1279                   end-label (match-string 2)
1280                   count (1- count))
1281             ;; Check any internal blocks.
1282             (when start-list
1283               (setq start-this (car start-list)
1284                     start-list (cdr start-list)
1285                     start-type (car start-this)
1286                     start-label (cadr start-this))
1287               (or (f90-equal-symbols start-type end-type)
1288                   (error "End type `%s' does not match start type `%s'"
1289                          end-type start-type))
1290               (or (f90-equal-symbols start-label end-label)
1291                   (error "End label `%s' does not match start label `%s'"
1292                          end-label start-label)))))
1293      (end-of-line))
1294    (if (> count 0) (error "Missing block end"))
1295    ;; Check outermost block.
1296    (when f90-smart-end
1297      (save-excursion
1298        (beginning-of-line)
1299        (skip-chars-forward " \t0-9")
1300        (f90-match-end)))))
1301
1302(defun f90-beginning-of-block (&optional num)
1303  "Move point backwards to the start of the current code block.
1304With optional argument NUM, go backward that many balanced blocks.
1305If NUM is negative, go forward to the end of a block.
1306Checks for consistency of block types and labels (if present).
1307Does not check the outermost block, because it may be incomplete.
1308Interactively, pushes mark before moving point."
1309  (interactive "p")
1310  (if (interactive-p) (push-mark (point) t))
1311  (and num (< num 0) (f90-end-of-block (- num)))
1312  (let ((case-fold-search t)
1313        (count (or num 1))
1314        end-list end-this end-type end-label
1315        start-this start-type start-label)
1316    (beginning-of-line)                 ; probably want this
1317    (while (and (> count 0) (re-search-backward f90-blocks-re nil 'move))
1318      (beginning-of-line)
1319      (skip-chars-forward " \t0-9")
1320      (cond ((or (f90-in-string) (f90-in-comment)))
1321            ((looking-at (concat "end[ \t]*" f90-blocks-re
1322                                 "[ \t]*\\(\\sw+\\)?"))
1323             (setq end-list (cons (list (match-string 1) (match-string 2))
1324                                  end-list)
1325                   count (1+ count)))
1326            ((setq start-this
1327                   (or
1328                    (f90-looking-at-do)
1329                    (f90-looking-at-select-case)
1330                    (f90-looking-at-type-like)
1331                    (f90-looking-at-program-block-start)
1332                    (f90-looking-at-if-then)
1333                    (f90-looking-at-where-or-forall)))
1334             (setq start-type (car start-this)
1335                   start-label (cadr start-this)
1336                   count (1- count))
1337             ;; Check any internal blocks.
1338             (when end-list
1339               (setq end-this (car end-list)
1340                     end-list (cdr end-list)
1341                     end-type (car end-this)
1342                     end-label (cadr end-this))
1343               (or (f90-equal-symbols start-type end-type)
1344                   (error "Start type `%s' does not match end type `%s'"
1345                          start-type end-type))
1346               (or (f90-equal-symbols start-label end-label)
1347                   (error "Start label `%s' does not match end label `%s'"
1348                          start-label end-label))))))
1349    ;; Includes an un-named main program block.
1350    (if (> count 0) (error "Missing block start"))))
1351
1352(defun f90-next-block (&optional num)
1353  "Move point forward to the next end or start of a code block.
1354With optional argument NUM, go forward that many blocks.
1355If NUM is negative, go backwards.
1356A block is a subroutine, if-endif, etc."
1357  (interactive "p")
1358  (let ((case-fold-search t)
1359        (count (if num (abs num) 1)))
1360    (while (and (> count 0)
1361                (if (> num 0) (re-search-forward f90-blocks-re nil 'move)
1362                  (re-search-backward f90-blocks-re nil 'move)))
1363      (beginning-of-line)
1364      (skip-chars-forward " \t0-9")
1365      (cond ((or (f90-in-string) (f90-in-comment)))
1366            ((or
1367              (looking-at "end[ \t]*")
1368              (f90-looking-at-do)
1369              (f90-looking-at-select-case)
1370              (f90-looking-at-type-like)
1371              (f90-looking-at-program-block-start)
1372              (f90-looking-at-if-then)
1373              (f90-looking-at-where-or-forall))
1374             (setq count (1- count))))
1375      (if (> num 0) (end-of-line)
1376        (beginning-of-line)))))
1377
1378
1379(defun f90-previous-block (&optional num)
1380  "Move point backward to the previous end or start of a code block.
1381With optional argument NUM, go backward that many blocks.
1382If NUM is negative, go forwards.
1383A block is a subroutine, if-endif, etc."
1384  (interactive "p")
1385  (f90-next-block (- (or num 1))))
1386
1387
1388(defun f90-mark-subprogram ()
1389  "Put mark at end of F90 subprogram, point at beginning, push mark."
1390  (interactive)
1391  (let ((pos (point)) program)
1392    (f90-end-of-subprogram)
1393    (push-mark)
1394    (goto-char pos)
1395    (setq program (f90-beginning-of-subprogram))
1396    (if (fboundp 'zmacs-activate-region)
1397        (zmacs-activate-region)
1398      (setq mark-active t
1399            deactivate-mark nil))
1400    program))
1401
1402(defun f90-comment-region (beg-region end-region)
1403  "Comment/uncomment every line in the region.
1404Insert the variable `f90-comment-region' at the start of every line
1405in the region, or, if already present, remove it."
1406  (interactive "*r")
1407  (let ((end (copy-marker end-region)))
1408    (goto-char beg-region)
1409    (beginning-of-line)
1410    (if (looking-at (regexp-quote f90-comment-region))
1411	(delete-region (point) (match-end 0))
1412      (insert f90-comment-region))
1413    (while (and (zerop (forward-line 1))
1414		(< (point) end))
1415      (if (looking-at (regexp-quote f90-comment-region))
1416	  (delete-region (point) (match-end 0))
1417	(insert f90-comment-region)))
1418    (set-marker end nil)))
1419
1420(defun f90-indent-line (&optional no-update)
1421  "Indent current line as F90 code.
1422Unless optional argument NO-UPDATE is non-nil, call `f90-update-line'
1423after indenting."
1424  (interactive "*P")
1425  (let ((case-fold-search t)
1426        (pos (point-marker))
1427        indent no-line-number)
1428    (beginning-of-line)           ; digits after & \n are not line-nos
1429    (if (not (save-excursion (and (f90-previous-statement)
1430                                  (f90-line-continued))))
1431        (f90-indent-line-no)
1432      (setq no-line-number t)
1433      (skip-chars-forward " \t"))
1434    (if (looking-at "!")
1435	(setq indent (f90-comment-indent))
1436      (and f90-smart-end (looking-at "end")
1437           (f90-match-end))
1438      (setq indent (f90-calculate-indent)))
1439    (or (= indent (current-column))
1440        (f90-indent-to indent no-line-number))
1441    ;; If initial point was within line's indentation,
1442    ;; position after the indentation.  Else stay at same point in text.
1443    (and (< (point) pos)
1444         (goto-char pos))
1445    (if auto-fill-function
1446        ;; GM NO-UPDATE not honoured, since this calls f90-update-line.
1447        (f90-do-auto-fill)
1448      (or no-update (f90-update-line)))
1449    (set-marker pos nil)))
1450
1451(defun f90-indent-new-line ()
1452  "Re-indent current line, insert a newline and indent the newline.
1453An abbrev before point is expanded if the variable `abbrev-mode' is non-nil.
1454If run in the middle of a line, the line is not broken."
1455  (interactive "*")
1456  (if abbrev-mode (expand-abbrev))
1457  (beginning-of-line)             ; reindent where likely to be needed
1458  (f90-indent-line)                ; calls indent-line-no, update-line
1459  (end-of-line)
1460  (delete-horizontal-space)		; destroy trailing whitespace
1461  (let ((string (f90-in-string))
1462        (cont (f90-line-continued)))
1463    (and string (not cont) (insert "&"))
1464    (newline)
1465    (if (or string (and cont f90-beginning-ampersand)) (insert "&")))
1466  (f90-indent-line 'no-update))         ; nothing to update
1467
1468
1469;; TODO not add spaces to empty lines at the start.
1470;; Why is second line getting extra indent over first?
1471(defun f90-indent-region (beg-region end-region)
1472  "Indent every line in region by forward parsing."
1473  (interactive "*r")
1474  (let ((end-region-mark (copy-marker end-region))
1475        (save-point (point-marker))
1476        (case-fold-search t)
1477	block-list ind-lev ind-curr ind-b cont struct beg-struct end-struct)
1478    (goto-char beg-region)
1479    ;; First find a line which is not a continuation line or comment.
1480    (beginning-of-line)
1481    (while (and (looking-at "[ \t]*[0-9]*\\(!\\|#\\|[ \t]*$\\)")
1482		(progn (f90-indent-line 'no-update)
1483		       (zerop (forward-line 1)))
1484		(< (point) end-region-mark)))
1485    (setq cont (f90-present-statement-cont))
1486    (while (and (or (eq cont 'middle) (eq cont 'end))
1487		(f90-previous-statement))
1488      (setq cont (f90-present-statement-cont)))
1489    ;; Process present line for beginning of block.
1490    (setq f90-cache-position (point))
1491    (f90-indent-line 'no-update)
1492    (setq ind-lev (f90-current-indentation)
1493          ind-curr ind-lev)
1494    (beginning-of-line)
1495    (skip-chars-forward " \t0-9")
1496    (setq struct nil
1497          ind-b (cond ((setq struct (f90-looking-at-do)) f90-do-indent)
1498		      ((or (setq struct (f90-looking-at-if-then))
1499			   (setq struct (f90-looking-at-select-case))
1500			   (setq struct (f90-looking-at-where-or-forall))
1501			   (looking-at f90-else-like-re))
1502		       f90-if-indent)
1503		      ((setq struct (f90-looking-at-type-like))
1504		       f90-type-indent)
1505		      ((or (setq struct (f90-looking-at-program-block-start))
1506                           (looking-at "contains[ \t]*\\($\\|!\\)"))
1507		       f90-program-indent)))
1508    (if ind-b (setq ind-lev (+ ind-lev ind-b)))
1509    (if struct (setq block-list (cons struct block-list)))
1510    (while (and (f90-line-continued) (zerop (forward-line 1))
1511		(< (point) end-region-mark))
1512      (if (looking-at "[ \t]*!")
1513          (f90-indent-to (f90-comment-indent))
1514        (or (= (current-indentation)
1515               (+ ind-curr f90-continuation-indent))
1516            (f90-indent-to (+ ind-curr f90-continuation-indent) 'no-line-no))))
1517    ;; Process all following lines.
1518    (while (and (zerop (forward-line 1)) (< (point) end-region-mark))
1519      (beginning-of-line)
1520      (f90-indent-line-no)
1521      (setq f90-cache-position (point))
1522      (cond ((looking-at "[ \t]*$") (setq ind-curr 0))
1523	    ((looking-at "[ \t]*#") (setq ind-curr 0))
1524	    ((looking-at "!") (setq ind-curr (f90-comment-indent)))
1525	    ((f90-no-block-limit) (setq ind-curr ind-lev))
1526	    ((looking-at f90-else-like-re) (setq ind-curr
1527						 (- ind-lev f90-if-indent)))
1528	    ((looking-at "contains[ \t]*\\($\\|!\\)")
1529	     (setq ind-curr (- ind-lev f90-program-indent)))
1530	    ((setq ind-b
1531		   (cond ((setq struct (f90-looking-at-do)) f90-do-indent)
1532			 ((or (setq struct (f90-looking-at-if-then))
1533			      (setq struct (f90-looking-at-select-case))
1534			      (setq struct (f90-looking-at-where-or-forall)))
1535			  f90-if-indent)
1536			 ((setq struct (f90-looking-at-type-like))
1537			  f90-type-indent)
1538			 ((setq struct (f90-looking-at-program-block-start))
1539			  f90-program-indent)))
1540	     (setq ind-curr ind-lev)
1541	     (if ind-b (setq ind-lev (+ ind-lev ind-b)))
1542	     (setq block-list (cons struct block-list)))
1543	    ((setq end-struct (f90-looking-at-program-block-end))
1544	     (setq beg-struct (car block-list)
1545		   block-list (cdr block-list))
1546	     (if f90-smart-end
1547		 (save-excursion
1548		   (f90-block-match (car beg-struct) (car (cdr beg-struct))
1549				    (car end-struct) (car (cdr end-struct)))))
1550	     (setq ind-b
1551		   (cond ((looking-at f90-end-if-re) f90-if-indent)
1552			 ((looking-at "end[ \t]*do\\>")  f90-do-indent)
1553			 ((looking-at f90-end-type-re) f90-type-indent)
1554			 ((f90-looking-at-program-block-end)
1555			  f90-program-indent)))
1556	     (if ind-b (setq ind-lev (- ind-lev ind-b)))
1557	     (setq ind-curr ind-lev))
1558	    (t (setq ind-curr ind-lev)))
1559      ;; Do the indentation if necessary.
1560      (or (= ind-curr (current-column))
1561	  (f90-indent-to ind-curr))
1562      (while (and (f90-line-continued) (zerop (forward-line 1))
1563		  (< (point) end-region-mark))
1564        (if (looking-at "[ \t]*!")
1565            (f90-indent-to (f90-comment-indent))
1566          (or (= (current-indentation)
1567                 (+ ind-curr f90-continuation-indent))
1568              (f90-indent-to
1569               (+ ind-curr f90-continuation-indent) 'no-line-no)))))
1570    ;; Restore point, etc.
1571    (setq f90-cache-position nil)
1572    (goto-char save-point)
1573    (set-marker end-region-mark nil)
1574    (set-marker save-point nil)
1575    (if (fboundp 'zmacs-deactivate-region)
1576 	(zmacs-deactivate-region)
1577      (deactivate-mark))))
1578
1579(defun f90-indent-subprogram ()
1580  "Properly indent the subprogram containing point."
1581  (interactive "*")
1582  (save-excursion
1583    (let ((program (f90-mark-subprogram)))
1584      (if program
1585	  (progn
1586	    (message "Indenting %s %s..."
1587		     (car program) (car (cdr program)))
1588	    (indent-region (point) (mark) nil)
1589	    (message "Indenting %s %s...done"
1590		     (car program) (car (cdr program))))
1591	(message "Indenting the whole file...")
1592	(indent-region (point) (mark) nil)
1593	(message "Indenting the whole file...done")))))
1594
1595(defun f90-break-line (&optional no-update)
1596  "Break line at point, insert continuation marker(s) and indent.
1597Unless in a string or comment, or if the optional argument NO-UPDATE
1598is non-nil, call `f90-update-line' after inserting the continuation marker."
1599  (interactive "*P")
1600  (cond ((f90-in-string)
1601         (insert "&\n&"))
1602        ((f90-in-comment)
1603         (delete-horizontal-space 'backwards) ; remove trailing whitespace
1604         (insert "\n" (f90-get-present-comment-type)))
1605        (t (insert "&")
1606           (or no-update (f90-update-line))
1607           (newline 1)
1608           (if f90-beginning-ampersand (insert "&"))))
1609  (indent-according-to-mode))
1610
1611(defun f90-find-breakpoint ()
1612  "From `fill-column', search backward for break-delimiter."
1613  (re-search-backward f90-break-delimiters (line-beginning-position))
1614  (if (not f90-break-before-delimiters)
1615      (forward-char (if (looking-at f90-no-break-re) 2 1))
1616    (backward-char)
1617    (or (looking-at f90-no-break-re)
1618        (forward-char))))
1619
1620(defun f90-do-auto-fill ()
1621  "Break line if non-white characters beyond `fill-column'.
1622Update keyword case first."
1623  (interactive "*")
1624  ;; Break line before or after last delimiter (non-word char) if
1625  ;; position is beyond fill-column.
1626  ;; Will not break **, //, or => (as specified by f90-no-break-re).
1627  (f90-update-line)
1628  ;; Need this for `f90-electric-insert' and other f90- callers.
1629  (unless (and (boundp 'comment-auto-fill-only-comments)
1630               comment-auto-fill-only-comments
1631               (not (f90-in-comment)))
1632    (while (> (current-column) fill-column)
1633      (let ((pos-mark (point-marker)))
1634        (move-to-column fill-column)
1635        (or (f90-in-string) (f90-find-breakpoint))
1636        (f90-break-line)
1637        (goto-char pos-mark)
1638        (set-marker pos-mark nil)))))
1639
1640(defun f90-join-lines (&optional arg)
1641  "Join current line to previous, fix whitespace, continuation, comments.
1642With optional argument ARG, join current line to following line.
1643Like `join-line', but handles F90 syntax."
1644  (interactive "*P")
1645  (beginning-of-line)
1646  (if arg (forward-line 1))
1647  (when (eq (preceding-char) ?\n)
1648    (skip-chars-forward " \t")
1649    (if (looking-at "\&") (delete-char 1))
1650    (beginning-of-line)
1651    (delete-region (point) (1- (point)))
1652    (skip-chars-backward " \t")
1653    (and (eq (preceding-char) ?&) (delete-char -1))
1654    (and (f90-in-comment)
1655         (looking-at "[ \t]*!+")
1656         (replace-match ""))
1657    (or (f90-in-string)
1658        (fixup-whitespace))))
1659
1660(defun f90-fill-region (beg-region end-region)
1661  "Fill every line in region by forward parsing.  Join lines if possible."
1662  (interactive "*r")
1663  (let ((end-region-mark (copy-marker end-region))
1664        (go-on t)
1665	f90-smart-end f90-auto-keyword-case auto-fill-function)
1666    (goto-char beg-region)
1667    (while go-on
1668      ;; Join as much as possible.
1669      (while (progn
1670               (end-of-line)
1671               (skip-chars-backward " \t")
1672               (eq (preceding-char) ?&))
1673        (f90-join-lines 'forward))
1674      ;; Chop the line if necessary.
1675      (while (> (save-excursion (end-of-line) (current-column))
1676		fill-column)
1677	(move-to-column fill-column)
1678	(f90-find-breakpoint)
1679	(f90-break-line 'no-update))
1680      (setq go-on (and (< (point) end-region-mark)
1681                       (zerop (forward-line 1)))
1682            f90-cache-position (point)))
1683    (setq f90-cache-position nil)
1684    (set-marker end-region-mark nil)
1685    (if (fboundp 'zmacs-deactivate-region)
1686 	(zmacs-deactivate-region)
1687      (deactivate-mark))))
1688
1689(defun f90-block-match (beg-block beg-name end-block end-name)
1690  "Match end-struct with beg-struct and complete end-block if possible.
1691BEG-BLOCK is the type of block as indicated at the start (e.g., do).
1692BEG-NAME is the block start name (may be nil).
1693END-BLOCK is the type of block as indicated at the end (may be nil).
1694END-NAME is the block end name (may be nil).
1695Leave point at the end of line."
1696  ;; Hack to deal with the case when this is called from
1697  ;; f90-indent-region on a program block without an explicit PROGRAM
1698  ;; statement at the start. Should really be an error (?).
1699  (or beg-block (setq beg-block "program"))
1700  (search-forward "end" (line-end-position))
1701  (catch 'no-match
1702    (if (and end-block (f90-equal-symbols beg-block end-block))
1703        (search-forward end-block)
1704      (if end-block
1705          (progn
1706            (message "END %s does not match %s." end-block beg-block)
1707            (end-of-line)
1708            (throw 'no-match nil))
1709        (message "Inserting %s." beg-block)
1710        (insert (concat " " beg-block))))
1711    (if (f90-equal-symbols beg-name end-name)
1712        (and end-name (search-forward end-name))
1713      (cond ((and beg-name (not end-name))
1714             (message "Inserting %s." beg-name)
1715             (insert (concat " " beg-name)))
1716            ((and beg-name end-name)
1717             (message "Replacing %s with %s." end-name beg-name)
1718             (search-forward end-name)
1719             (replace-match beg-name))
1720            ((and (not beg-name) end-name)
1721             (message "Deleting %s." end-name)
1722             (search-forward end-name)
1723             (replace-match ""))))
1724    (or (looking-at "[ \t]*!") (delete-horizontal-space))))
1725
1726(defun f90-match-end ()
1727  "From an end block statement, find the corresponding block and name."
1728  (interactive)
1729  (let ((count 1)
1730        (top-of-window (window-start))
1731	(end-point (point))
1732        (case-fold-search t)
1733	matching-beg beg-name end-name beg-block end-block end-struct)
1734    (when (save-excursion (beginning-of-line) (skip-chars-forward " \t0-9")
1735                          (setq end-struct (f90-looking-at-program-block-end)))
1736      (setq end-block (car end-struct)
1737            end-name  (car (cdr end-struct)))
1738      (save-excursion
1739        (beginning-of-line)
1740        (while (and (> count 0)
1741                    (not (= (line-beginning-position) (point-min))))
1742          (re-search-backward f90-blocks-re nil 'move)
1743          (beginning-of-line)
1744          ;; GM not a line number if continued line.
1745;;;          (skip-chars-forward " \t")
1746;;;          (skip-chars-forward "0-9")
1747          (skip-chars-forward " \t0-9")
1748          (cond ((or (f90-in-string) (f90-in-comment)))
1749                ((setq matching-beg
1750                       (or
1751                        (f90-looking-at-do)
1752                        (f90-looking-at-if-then)
1753                        (f90-looking-at-where-or-forall)
1754                        (f90-looking-at-select-case)
1755                        (f90-looking-at-type-like)
1756                        (f90-looking-at-program-block-start)
1757                        ;; Interpret a single END without a block
1758                        ;; start to be the END of a program block
1759                        ;; without an initial PROGRAM line.
1760                        (if (= (line-beginning-position) (point-min))
1761                            '("program" nil))))
1762                 (setq count (1- count)))
1763                ((looking-at (concat "end[ \t]*" f90-blocks-re))
1764                 (setq count (1+ count)))))
1765        (if (> count 0)
1766            (message "No matching beginning.")
1767          (f90-update-line)
1768          (if (eq f90-smart-end 'blink)
1769              (if (< (point) top-of-window)
1770                  (message "Matches %s: %s"
1771                           (what-line)
1772                           (buffer-substring
1773                            (line-beginning-position)
1774                            (line-end-position)))
1775                (sit-for blink-matching-delay)))
1776          (setq beg-block (car matching-beg)
1777                beg-name (car (cdr matching-beg)))
1778          (goto-char end-point)
1779          (beginning-of-line)
1780          (f90-block-match beg-block beg-name end-block end-name))))))
1781
1782(defun f90-insert-end ()
1783  "Insert a complete end statement matching beginning of present block."
1784  (interactive "*")
1785  (let ((f90-smart-end (or f90-smart-end 'blink)))
1786    (insert "end")
1787    (f90-indent-new-line)))
1788
1789;; Abbrevs and keywords.
1790
1791(defun f90-abbrev-start ()
1792  "Typing `\\[help-command] or `? lists all the F90 abbrevs.
1793Any other key combination is executed normally."
1794  (interactive "*")
1795  (insert last-command-char)
1796  (let (char event)
1797    (if (fboundp 'next-command-event) ; XEmacs
1798        (setq event (next-command-event)
1799              char (and (fboundp 'event-to-character)
1800			(event-to-character event)))
1801      (setq event (read-event)
1802            char event))
1803    ;; Insert char if not equal to `?', or if abbrev-mode is off.
1804    (if (and abbrev-mode (or (eq char ??) (eq char help-char)))
1805	(f90-abbrev-help)
1806      (setq unread-command-events (list event)))))
1807
1808(defun f90-abbrev-help ()
1809  "List the currently defined abbrevs in F90 mode."
1810  (interactive)
1811  (message "Listing abbrev table...")
1812  (display-buffer (f90-prepare-abbrev-list-buffer))
1813  (message "Listing abbrev table...done"))
1814
1815(defun f90-prepare-abbrev-list-buffer ()
1816  "Create a buffer listing the F90 mode abbreviations."
1817  (save-excursion
1818    (set-buffer (get-buffer-create "*Abbrevs*"))
1819    (erase-buffer)
1820    (insert-abbrev-table-description 'f90-mode-abbrev-table t)
1821    (goto-char (point-min))
1822    (set-buffer-modified-p nil)
1823    (edit-abbrevs-mode))
1824  (get-buffer-create "*Abbrevs*"))
1825
1826(defun f90-upcase-keywords ()
1827  "Upcase all F90 keywords in the buffer."
1828  (interactive "*")
1829  (f90-change-keywords 'upcase-word))
1830
1831(defun f90-capitalize-keywords ()
1832  "Capitalize all F90 keywords in the buffer."
1833  (interactive "*")
1834  (f90-change-keywords 'capitalize-word))
1835
1836(defun f90-downcase-keywords ()
1837  "Downcase all F90 keywords in the buffer."
1838  (interactive "*")
1839  (f90-change-keywords 'downcase-word))
1840
1841(defun f90-upcase-region-keywords (beg end)
1842  "Upcase all F90 keywords in the region."
1843  (interactive "*r")
1844  (f90-change-keywords 'upcase-word beg end))
1845
1846(defun f90-capitalize-region-keywords (beg end)
1847  "Capitalize all F90 keywords in the region."
1848  (interactive "*r")
1849  (f90-change-keywords 'capitalize-word beg end))
1850
1851(defun f90-downcase-region-keywords (beg end)
1852  "Downcase all F90 keywords in the region."
1853  (interactive "*r")
1854  (f90-change-keywords 'downcase-word beg end))
1855
1856;; Change the keywords according to argument.
1857(defun f90-change-keywords (change-word &optional beg end)
1858  "Change the case of F90 keywords in the region (if specified) or buffer.
1859CHANGE-WORD should be one of 'upcase-word, 'downcase-word, 'capitalize-word."
1860  (save-excursion
1861    (setq beg (or beg (point-min))
1862          end (or end (point-max)))
1863    (let ((keyword-re
1864	   (concat "\\("
1865		   f90-keywords-re "\\|" f90-procedures-re "\\|"
1866		   f90-hpf-keywords-re "\\|" f90-operators-re "\\)"))
1867	  (ref-point (point-min))
1868	  (modified (buffer-modified-p))
1869          state saveword back-point)
1870      (goto-char beg)
1871      (unwind-protect
1872	  (while (re-search-forward keyword-re end t)
1873	    (unless (progn
1874                      (setq state (parse-partial-sexp ref-point (point)))
1875                      (or (nth 3 state) (nth 4 state)
1876                          ;; GM f90-directive-comment-re?
1877                          (save-excursion ; check for cpp directive
1878                            (beginning-of-line)
1879                            (skip-chars-forward " \t0-9")
1880                            (looking-at "#"))))
1881	      (setq ref-point (point)
1882		    back-point (save-excursion (backward-word 1) (point))
1883                    saveword (buffer-substring back-point ref-point))
1884	      (funcall change-word -1)
1885	      (or (string= saveword (buffer-substring back-point ref-point))
1886		  (setq modified t))))
1887	(or modified (set-buffer-modified-p nil))))))
1888
1889
1890(defun f90-current-defun ()
1891  "Function to use for `add-log-current-defun-function' in F90 mode."
1892  (save-excursion
1893    (nth 1 (f90-beginning-of-subprogram))))
1894
1895
1896(defun f90-backslash-not-special (&optional all)
1897  "Make the backslash character (\\) be non-special in the current buffer.
1898With optional argument ALL, change the default for all present
1899and future F90 buffers.  F90 mode normally treats backslash as an
1900escape character."
1901  (or (eq major-mode 'f90-mode)
1902      (error "This function should only be used in F90 buffers"))
1903  (when (equal (char-syntax ?\\ ) ?\\ )
1904    (or all (set-syntax-table (copy-syntax-table (syntax-table))))
1905    (modify-syntax-entry ?\\ ".")))
1906
1907
1908(provide 'f90)
1909
1910;;; arch-tag: fceac97c-c147-44bd-aec0-172d4b560ef8
1911;;; f90.el ends here
1912