]> code.delx.au - gnu-emacs/blob - lisp/progmodes/f90.el
* lisp/simple.el (shell-command): Add save-match-data comment
[gnu-emacs] / lisp / progmodes / f90.el
1 ;;; f90.el --- Fortran-90 mode (free format) -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1995-1997, 2000-2016 Free Software Foundation, Inc.
4
5 ;; Author: Torbjörn Einarsson <Torbjorn.Einarsson@era.ericsson.se>
6 ;; Maintainer: Glenn Morris <rgm@gnu.org>
7 ;; Keywords: fortran, f90, languages
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Major mode for editing F90 programs in FREE FORMAT.
27 ;; The minor language revision F95 is also supported (with font-locking).
28 ;; Some/many (?) aspects of F2003 are supported.
29 ;; Some aspects of F2008 are supported.
30
31 ;; Knows about continuation lines, named structured statements, and other
32 ;; features in F90 including HPF (High Performance Fortran) structures.
33 ;; The basic feature provides accurate indentation of F90 programs.
34 ;; In addition, there are many more features like automatic matching of all
35 ;; end statements, an auto-fill function to break long lines, a join-lines
36 ;; function which joins continued lines, etc.
37
38 ;; To facilitate typing, a fairly complete list of abbreviations is provided.
39 ;; All abbreviations begin with the backquote character "`"
40 ;; For example, `i expands to integer (if abbrev-mode is on).
41
42 ;; There are two separate features for altering the appearance of code:
43 ;; 1) Upcasing or capitalizing of all keywords.
44 ;; 2) Colors/fonts using font-lock-mode.
45 ;; Automatic upcase or downcase of keywords is controlled by the variable
46 ;; f90-auto-keyword-case.
47
48 ;; The indentations of lines starting with ! is determined by the first of the
49 ;; following matches (values in the left column are the defaults):
50
51 ;; start-string/regexp indent variable holding start-string/regexp
52 ;; !!! 0
53 ;; !hpf\\$ (re) 0 f90-directive-comment-re
54 ;; !!$ 0 f90-comment-region
55 ;; ! (re) as code f90-indented-comment-re
56 ;; default comment-column
57
58 ;; Ex: Here is the result of 3 different settings of f90-indented-comment-re
59 ;; f90-indented-comment-re !-indentation !!-indentation
60 ;; ! as code as code
61 ;; !! comment-column as code
62 ;; ![^!] as code comment-column
63 ;; Trailing comments are indented to comment-column with indent-for-comment.
64 ;; The function f90-comment-region toggles insertion of
65 ;; the variable f90-comment-region in every line of the region.
66
67 ;; One common convention for free vs. fixed format is that free format files
68 ;; have the ending .f90 or .f95 while fixed format files have the ending .f.
69 ;; Emacs automatically loads Fortran files in the appropriate mode based
70 ;; on extension. You can modify this by adjusting the variable auto-mode-alist.
71 ;; For example:
72 ;; (add-to-list 'auto-mode-alist '("\\.f\\'" . f90-mode))
73
74 ;; Once you have entered f90-mode, you can get more info by using
75 ;; the command describe-mode (C-h m). For help use
76 ;; C-h f <Name of function you want described>, or
77 ;; C-h v <Name of variable you want described>.
78
79 ;; To customize f90-mode for your taste, use, for example:
80 ;; (you don't have to specify values for all the parameters below)
81 ;;
82 ;; (add-hook 'f90-mode-hook
83 ;; ;; These are the default values.
84 ;; (lambda () (setq f90-do-indent 3
85 ;; f90-if-indent 3
86 ;; f90-type-indent 3
87 ;; f90-program-indent 2
88 ;; f90-continuation-indent 5
89 ;; f90-comment-region "!!$"
90 ;; f90-directive-comment-re "!hpf\\$"
91 ;; f90-indented-comment-re "!"
92 ;; f90-break-delimiters "[-+\\*/><=,% \t]"
93 ;; f90-break-before-delimiters t
94 ;; f90-beginning-ampersand t
95 ;; f90-smart-end 'blink
96 ;; f90-auto-keyword-case nil
97 ;; f90-leave-line-no nil
98 ;; indent-tabs-mode nil
99 ;; f90-font-lock-keywords f90-font-lock-keywords-2
100 ;; )
101 ;; ;; These are not default.
102 ;; (abbrev-mode 1) ; turn on abbreviation mode
103 ;; (f90-add-imenu-menu) ; extra menu with functions etc.
104 ;; (if f90-auto-keyword-case ; change case of all keywords on startup
105 ;; (f90-change-keywords f90-auto-keyword-case))))
106 ;;
107 ;; in your init file. You can also customize the lists
108 ;; f90-font-lock-keywords, etc.
109 ;;
110 ;; The auto-fill and abbreviation minor modes are accessible from the F90 menu,
111 ;; or by using M-x auto-fill-mode and M-x abbrev-mode, respectively.
112
113 ;; Remarks
114 ;; 1) Line numbers are by default left-justified. If f90-leave-line-no is
115 ;; non-nil, the line numbers are never touched.
116 ;; 2) Multi-; statements like "do i=1,20 ; j=j+i ; end do" are not handled
117 ;; correctly, but I imagine them to be rare.
118 ;; 3) Regexps for hilit19 are no longer supported.
119 ;; 4) For FIXED FORMAT code, use fortran mode.
120 ;; 5) This mode does not work under emacs-18.x.
121 ;; 6) Preprocessor directives, i.e., lines starting with # are left-justified
122 ;; and are untouched by all case-changing commands. There is, at present, no
123 ;; mechanism for treating multi-line directives (continued by \ ).
124 ;; 7) f77 do-loops do 10 i=.. ; ; 10 continue are not correctly indented.
125 ;; You are urged to use f90-do loops (with labels if you wish).
126 ;; 8) The highlighting mode under XEmacs is not as complete as under Emacs.
127
128 ;; List of user commands
129 ;; f90-previous-statement f90-next-statement
130 ;; f90-beginning-of-subprogram f90-end-of-subprogram f90-mark-subprogram
131 ;; f90-comment-region
132 ;; f90-indent-line f90-indent-new-line
133 ;; f90-indent-region (can be called by calling indent-region)
134 ;; f90-indent-subprogram
135 ;; f90-break-line f90-join-lines
136 ;; f90-fill-region
137 ;; f90-insert-end
138 ;; f90-upcase-keywords f90-upcase-region-keywords
139 ;; f90-downcase-keywords f90-downcase-region-keywords
140 ;; f90-capitalize-keywords f90-capitalize-region-keywords
141 ;; f90-add-imenu-menu
142 ;; f90-font-lock-1, f90-font-lock-2, f90-font-lock-3, f90-font-lock-4
143
144 ;; Original author's thanks
145 ;; Thanks to all the people who have tested the mode. Special thanks to Jens
146 ;; Bloch Helmers for encouraging me to write this code, for creative
147 ;; suggestions as well as for the lists of hpf-commands.
148 ;; Also thanks to the authors of the fortran and pascal modes, on which some
149 ;; of this code is built.
150
151 ;;; Code:
152
153 ;; TODO
154 ;; 1. Any missing F2003 syntax?
155 ;; 2. Have "f90-mode" just recognize F90 syntax, then derived modes
156 ;; "f95-mode", "f2003-mode" for the language revisions.
157 ;; 3. Support for align.
158 ;; Font-locking:
159 ;; 1. OpenMP, OpenMPI?, preprocessor highlighting.
160 ;; 2. integer_name = 1
161 ;; 3. Labels for "else" statements (F2003)?
162
163 (defvar comment-auto-fill-only-comments)
164 (defvar font-lock-keywords)
165
166 ;; User options
167
168 (defgroup f90 nil
169 "Major mode for editing free format Fortran 90,95 code."
170 :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
171 :group 'languages)
172
173 (defgroup f90-indent nil
174 "Indentation in free format Fortran."
175 :prefix "f90-"
176 :group 'f90)
177
178
179 (defcustom f90-do-indent 3
180 "Extra indentation applied to DO blocks."
181 :type 'integer
182 :safe 'integerp
183 :group 'f90-indent)
184
185 (defcustom f90-if-indent 3
186 "Extra indentation applied to IF, SELECT CASE, WHERE and FORALL blocks."
187 :type 'integer
188 :safe 'integerp
189 :group 'f90-indent)
190
191 (defcustom f90-type-indent 3
192 "Extra indentation applied to TYPE, ENUM, INTERFACE and BLOCK DATA blocks."
193 :type 'integer
194 :safe 'integerp
195 :group 'f90-indent)
196
197 (defcustom f90-program-indent 2
198 "Extra indentation applied to PROGRAM, MODULE, SUBROUTINE, FUNCTION blocks."
199 :type 'integer
200 :safe 'integerp
201 :group 'f90-indent)
202
203 (defcustom f90-associate-indent 2
204 "Extra indentation applied to ASSOCIATE blocks."
205 :type 'integer
206 :safe 'integerp
207 :group 'f90-indent
208 :version "23.1")
209
210 (defcustom f90-critical-indent 2
211 "Extra indentation applied to BLOCK, CRITICAL blocks."
212 :type 'integer
213 :safe 'integerp
214 :group 'f90-indent
215 :version "24.1")
216
217 (defcustom f90-continuation-indent 5
218 "Extra indentation applied to continuation lines."
219 :type 'integer
220 :safe 'integerp
221 :group 'f90-indent)
222
223 (defcustom f90-comment-region "!!$"
224 "String inserted by \\[f90-comment-region] at start of each line in region."
225 :type 'string
226 :safe 'stringp
227 :group 'f90-indent)
228
229 (defcustom f90-indented-comment-re "!"
230 "Regexp matching comments to indent as code."
231 :type 'regexp
232 :safe 'stringp
233 :group 'f90-indent)
234
235 ;; Should we add ^# to this? That's not really a comment.
236 (defcustom f90-directive-comment-re "!hpf\\$"
237 "Regexp of comment-like directive like \"!HPF\\\\$\", not to be indented."
238 :type 'regexp
239 :safe 'stringp
240 :group 'f90-indent)
241
242 (defcustom f90-beginning-ampersand t
243 "Non-nil gives automatic insertion of `&' at start of continuation line."
244 :type 'boolean
245 :safe 'booleanp
246 :group 'f90)
247
248 (defcustom f90-smart-end 'blink
249 "Qualification of END statements according to the matching block start.
250 For example, change the END that closes an IF block to END IF.
251 If the block has a label, add it as well (unless `f90-smart-end-names'
252 says not to). Allowed values are `blink', `no-blink', and nil. If nil,
253 nothing is done. The other two settings have the same effect, but `blink'
254 additionally blinks the cursor to the start of the block."
255 :type '(choice (const blink) (const no-blink) (const nil))
256 :safe (lambda (value) (memq value '(blink no-blink nil)))
257 :group 'f90)
258
259 ;; Optional: program, module, type, function, subroutine
260 ;; Not optional: block data?, forall, if, select case/type, associate, do,
261 ;; where, interface, critical
262 ;; No labels: enum
263 (defcustom f90-smart-end-names t
264 "Whether completion of END statements should insert optional block names.
265 For example, when closing a \"PROGRAM PROGNAME\" block, \"PROGNAME\" is
266 optional in the \"END PROGRAM\" statement. The same is true for modules,
267 functions, subroutines, and types. Some people prefer to omit the name
268 from the END statement, since it makes it easier to change the name.
269
270 This does not apply to named DO, IF, etc. blocks. If such blocks
271 start with a label, they must end with one.
272
273 If an end statement has a name that does not match the start, it is always
274 corrected, regardless of the value of this variable."
275 :type 'boolean
276 :safe 'booleanp
277 :group 'f90
278 :version "24.4")
279
280 (defcustom f90-break-delimiters "[-+\\*/><=,% \t]"
281 "Regexp matching delimiter characters at which lines may be broken.
282 There are some common two-character tokens where one or more of
283 the members matches this regexp. Although Fortran allows breaks
284 within lexical tokens (provided the next line has a beginning ampersand),
285 the constant `f90-no-break-re' ensures that such tokens are not split."
286 :type 'regexp
287 :safe 'stringp
288 :group 'f90)
289
290 (defcustom f90-break-before-delimiters t
291 "Non-nil causes `f90-do-auto-fill' to break lines before delimiters."
292 :type 'boolean
293 :safe 'booleanp
294 :group 'f90)
295
296 (defcustom f90-auto-keyword-case nil
297 "Automatic case conversion of keywords.
298 The options are `downcase-word', `upcase-word', `capitalize-word' and nil."
299 :type '(choice (const downcase-word) (const upcase-word)
300 (const capitalize-word) (const nil))
301 :safe (lambda (value) (memq value '(downcase-word
302 capitalize-word upcase-word nil)))
303 :group 'f90)
304
305 (defcustom f90-leave-line-no nil
306 "If non-nil, line numbers are not left justified."
307 :type 'boolean
308 :safe 'booleanp
309 :group 'f90)
310
311 (defcustom f90-mode-hook nil
312 "Hook run when entering F90 mode."
313 :type 'hook
314 ;; Not the only safe options, but some common ones.
315 :safe (lambda (value) (member value '((f90-add-imenu-menu) nil)))
316 :options '(f90-add-imenu-menu)
317 :group 'f90)
318
319 ;; User options end here.
320
321 (defconst f90-keywords-re
322 (concat
323 "\\_<"
324 (regexp-opt '("allocatable" "allocate" "assign" "assignment" "backspace"
325 "block" "call" "case" "character" "close" "common" "complex"
326 "contains" "continue" "cycle" "data" "deallocate"
327 "dimension" "do" "double" "else" "elseif" "elsewhere" "end"
328 "enddo" "endfile" "endif" "entry" "equivalence" "exit"
329 "external" "forall" "format" "function" "goto" "if"
330 "implicit" "include" "inquire" "integer" "intent"
331 "interface" "intrinsic" "logical" "module" "namelist" "none"
332 "nullify" "only" "open" "operator" "optional" "parameter"
333 "pause" "pointer" "precision" "print" "private" "procedure"
334 "program" "public" "read" "real" "recursive" "result" "return"
335 "rewind" "save" "select" "sequence" "stop" "subroutine"
336 "target" "then" "type" "use" "where" "while" "write"
337 ;; F95 keywords.
338 "elemental" "pure"
339 ;; F2003
340 "abstract" "associate" "asynchronous" "bind" "class"
341 "deferred" "enum" "enumerator" "extends" "extends_type_of"
342 "final" "generic" "import" "non_intrinsic" "non_overridable"
343 "nopass" "pass" "protected" "same_type_as" "value" "volatile"
344 ;; F2008.
345 ;; FIXME f90-change-keywords does not work right if
346 ;; there are spaces.
347 "contiguous" "submodule" "concurrent" "codimension"
348 "sync all" "sync memory" "critical" "image_index" "error stop"
349 ))
350 "\\_>")
351 "Regexp used by the function `f90-change-keywords'.")
352
353 (defconst f90-keywords-level-3-re
354 (concat
355 "\\_<"
356 (regexp-opt
357 '("allocatable" "allocate" "assign" "assignment" "backspace"
358 "close" "deallocate" "dimension" "endfile" "entry" "equivalence"
359 "external" "inquire" "intent" "intrinsic" "nullify" "only" "open"
360 ;; FIXME operator and assignment should be F2003 procedures?
361 "operator" "optional" "parameter" "pause" "pointer" "print" "private"
362 "public" "read" "recursive" "result" "rewind" "save" "select"
363 "sequence" "target" "write"
364 ;; F95 keywords.
365 "elemental" "pure"
366 ;; F2003. asynchronous separate.
367 "abstract" "deferred" "import" "final" "non_intrinsic" "non_overridable"
368 "nopass" "pass" "protected" "value" "volatile"
369 ;; F2008.
370 ;; "concurrent" is only in the sense of "do [,] concurrent", but given
371 ;; the [,] it's simpler to just do every instance (cf "do while").
372 "contiguous" "concurrent" "codimension" "sync all" "sync memory"
373 ))
374 "\\_>")
375 "Keyword-regexp for font-lock level >= 3.")
376
377 (defconst f90-procedures-re
378 (concat "\\_<"
379 (regexp-opt
380 '("abs" "achar" "acos" "adjustl" "adjustr" "aimag" "aint"
381 "all" "allocated" "anint" "any" "asin" "associated"
382 "atan" "atan2" "bit_size" "btest" "ceiling" "char" "cmplx"
383 "conjg" "cos" "cosh" "count" "cshift" "date_and_time" "dble"
384 "digits" "dim" "dot_product" "dprod" "eoshift" "epsilon"
385 "exp" "exponent" "floor" "fraction" "huge" "iachar" "iand"
386 "ibclr" "ibits" "ibset" "ichar" "ieor" "index" "int" "ior"
387 "ishft" "ishftc" "kind" "lbound" "len" "len_trim" "lge" "lgt"
388 "lle" "llt" "log" "log10" "logical" "matmul" "max"
389 "maxexponent" "maxloc" "maxval" "merge" "min" "minexponent"
390 "minloc" "minval" "mod" "modulo" "mvbits" "nearest" "nint"
391 "not" "pack" "precision" "present" "product" "radix"
392 ;; Real is taken out here to avoid highlighting declarations.
393 "random_number" "random_seed" "range" ;; "real"
394 "repeat" "reshape" "rrspacing" "scale" "scan"
395 "selected_int_kind" "selected_real_kind" "set_exponent"
396 "shape" "sign" "sin" "sinh" "size" "spacing" "spread" "sqrt"
397 "sum" "system_clock" "tan" "tanh" "tiny" "transfer"
398 "transpose" "trim" "ubound" "unpack" "verify"
399 ;; F95 intrinsic functions.
400 "null" "cpu_time"
401 ;; F2003.
402 "move_alloc" "command_argument_count" "get_command"
403 "get_command_argument" "get_environment_variable"
404 "selected_char_kind" "wait" "flush" "new_line"
405 "extends" "extends_type_of" "same_type_as" "bind"
406 ;; F2003 ieee_arithmetic intrinsic module.
407 "ieee_support_underflow_control" "ieee_get_underflow_mode"
408 "ieee_set_underflow_mode"
409 ;; F2003 iso_c_binding intrinsic module.
410 "c_loc" "c_funloc" "c_associated" "c_f_pointer"
411 "c_f_procpointer"
412 ;; F2008.
413 "bge" "bgt" "ble" "blt" "dshiftl" "dshiftr" "leadz" "popcnt"
414 "poppar" "trailz" "maskl" "maskr" "shifta" "shiftl" "shiftr"
415 "merge_bits" "iall" "iany" "iparity" "storage_size"
416 "bessel_j0" "bessel_j1" "bessel_jn"
417 "bessel_y0" "bessel_y1" "bessel_yn"
418 "erf" "erfc" "erfc_scaled" "gamma" "hypot" "log_gamma"
419 "norm2" "parity" "findloc" "is_contiguous"
420 "sync images" "lock" "unlock" "image_index"
421 "lcobound" "ucobound" "num_images" "this_image"
422 "acosh" "asinh" "atanh"
423 "atomic_define" "atomic_ref" "execute_command_line"
424 ;; F2008 iso_fortran_env module.
425 "compiler_options" "compiler_version"
426 ;; F2008 iso_c_binding module.
427 "c_sizeof"
428 ) t)
429 ;; A left parenthesis to avoid highlighting non-procedures.
430 "[ \t]*(")
431 "Regexp whose first part matches F90 intrinsic procedures.")
432
433 (defconst f90-operators-re
434 (concat "\\."
435 (regexp-opt '("and" "eq" "eqv" "false" "ge" "gt" "le" "lt" "ne"
436 "neqv" "not" "or" "true") t)
437 "\\.")
438 "Regexp matching intrinsic operators.")
439
440 (defconst f90-hpf-keywords-re
441 (concat
442 "\\_<"
443 (regexp-opt
444 ;; Intrinsic procedures.
445 '("all_prefix" "all_scatter" "all_suffix" "any_prefix"
446 "any_scatter" "any_suffix" "copy_prefix" "copy_scatter"
447 "copy_suffix" "count_prefix" "count_scatter" "count_suffix"
448 "grade_down" "grade_up"
449 "hpf_alignment" "hpf_distribution" "hpf_template" "iall" "iall_prefix"
450 "iall_scatter" "iall_suffix" "iany" "iany_prefix" "iany_scatter"
451 "iany_suffix" "ilen" "iparity" "iparity_prefix"
452 "iparity_scatter" "iparity_suffix" "leadz" "maxval_prefix"
453 "maxval_scatter" "maxval_suffix" "minval_prefix" "minval_scatter"
454 "minval_suffix" "number_of_processors" "parity"
455 "parity_prefix" "parity_scatter" "parity_suffix" "popcnt" "poppar"
456 "processors_shape" "product_prefix" "product_scatter"
457 "product_suffix" "sum_prefix" "sum_scatter" "sum_suffix"
458 ;; Directives.
459 "align" "distribute" "dynamic" "independent" "inherit" "processors"
460 "realign" "redistribute" "template"
461 ;; Keywords.
462 "block" "cyclic" "extrinsic" "new" "onto" "pure" "with"))
463 "\\_>")
464 "Regexp for all HPF keywords, procedures and directives.")
465
466 (defconst f90-constants-re
467 (concat
468 "\\_<"
469 (regexp-opt '( ;; F2003 iso_fortran_env constants.
470 "iso_fortran_env"
471 "input_unit" "output_unit" "error_unit"
472 "iostat_end" "iostat_eor"
473 "numeric_storage_size" "character_storage_size"
474 "file_storage_size"
475 ;; F2003 iso_c_binding constants.
476 "iso_c_binding"
477 "c_int" "c_short" "c_long" "c_long_long" "c_signed_char"
478 "c_size_t"
479 "c_int8_t" "c_int16_t" "c_int32_t" "c_int64_t"
480 "c_int_least8_t" "c_int_least16_t" "c_int_least32_t"
481 "c_int_least64_t"
482 "c_int_fast8_t" "c_int_fast16_t" "c_int_fast32_t"
483 "c_int_fast64_t"
484 "c_intmax_t" "c_intptr_t"
485 "c_float" "c_double" "c_long_double"
486 "c_float_complex" "c_double_complex" "c_long_double_complex"
487 "c_bool" "c_char"
488 "c_null_char" "c_alert" "c_backspace" "c_form_feed"
489 "c_new_line" "c_carriage_return" "c_horizontal_tab"
490 "c_vertical_tab"
491 "c_ptr" "c_funptr" "c_null_ptr" "c_null_funptr"
492 "ieee_exceptions"
493 "ieee_arithmetic"
494 "ieee_features"
495 ;; F2008 iso_fortran_env constants.
496 "character_kinds" "int8" "int16" "int32" "int64"
497 "integer_kinds" "iostat_inquire_internal_unit"
498 "logical_kinds" "real_kinds" "real32" "real64" "real128"
499 "lock_type" "atomic_int_kind" "atomic_logical_kind"
500 ))
501 "\\_>")
502 "Regexp for Fortran intrinsic constants.")
503
504 ;; cf f90-looking-at-type-like.
505 (defun f90-typedef-matcher (limit)
506 "Search for the start/end of the definition of a derived type, up to LIMIT.
507 Set the match data so that subexpression 1,2 are the TYPE, and
508 type-name parts, respectively."
509 (let (found l)
510 (while (and (re-search-forward "\\_<\\(\\(?:end[ \t]*\\)?type\\)\\_>[ \t]*"
511 limit t)
512 (not (setq found
513 (progn
514 (setq l (match-data))
515 (unless (looking-at "\\(is\\_>\\|(\\)")
516 (when (if (looking-at "\\(\\(?:\\sw\\|\\s_\\)+\\)")
517 (goto-char (match-end 0))
518 (re-search-forward
519 "[ \t]*::[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)"
520 (line-end-position) t))
521 ;; 0 is wrong, but we don't use it.
522 (set-match-data
523 (append l (list (match-beginning 1)
524 (match-end 1))))
525 t)))))))
526 found))
527
528 (defvar f90-font-lock-keywords-1
529 (list
530 ;; Special highlighting of "module procedure".
531 '("\\_<\\(module[ \t]*procedure\\)\\_>\\([^()\n]*::\\)?[ \t]*\\([^&!\n]*\\)"
532 (1 font-lock-keyword-face) (3 font-lock-function-name-face nil t))
533 ;; Highlight definition of derived type.
534 ;;; '("\\_<\\(\\(?:end[ \t]*\\)?type\\)\\_>\\([^()\n]*::\\)?[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)"
535 ;;; (1 font-lock-keyword-face) (3 font-lock-function-name-face))
536 '(f90-typedef-matcher
537 (1 font-lock-keyword-face) (2 font-lock-function-name-face))
538 ;; F2003. Prevent operators being highlighted as functions.
539 '("\\_<\\(\\(?:end[ \t]*\\)?interface[ \t]*\\(?:assignment\\|operator\\|\
540 read\\|write\\)\\)[ \t]*(" (1 font-lock-keyword-face t))
541 ;; Other functions and declarations. Named interfaces = F2003.
542 ;; F2008: end submodule submodule_name.
543 '("\\_<\\(\\(?:end[ \t]*\\)?\\(program\\|\\(?:sub\\)?module\\|\
544 function\\|associate\\|subroutine\\|interface\\)\\|use\\|call\\)\
545 \\_>[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)?"
546 (1 font-lock-keyword-face) (3 font-lock-function-name-face nil t))
547 ;; F2008: submodule (parent_name) submodule_name.
548 '("\\_<\\(submodule\\)\\_>[ \t]*([^)\n]+)[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)?"
549 (1 font-lock-keyword-face) (2 font-lock-function-name-face nil t))
550 ;; F2003.
551 '("\\_<\\(use\\)[ \t]*,[ \t]*\\(\\(?:non_\\)?intrinsic\\)[ \t]*::[ \t]*\
552 \\(\\(?:\\sw\\|\\s_\\)+\\)"
553 (1 font-lock-keyword-face) (2 font-lock-keyword-face)
554 (3 font-lock-function-name-face))
555 "\\_<\\(\\(end[ \t]*\\)?block[ \t]*data\\|contains\\)\\_>"
556 ;; "abstract interface" is F2003.
557 '("\\_<abstract[ \t]*interface\\_>" (0 font-lock-keyword-face t)))
558 "This does fairly subdued highlighting of comments and function calls.")
559
560 ;; NB not explicitly handling this, yet it seems to work.
561 ;; type(...) function foo()
562 (defun f90-typedec-matcher (limit)
563 "Search for the declaration of variables of derived type, up to LIMIT.
564 Set the match data so that subexpression 1,2 are the TYPE(...),
565 and variable-name parts, respectively."
566 ;; Matcher functions must return nil only when there are no more
567 ;; matches within the search range.
568 (let (found l)
569 (while (and (re-search-forward "\\_<\\(type\\|class\\)[ \t]*(" limit t)
570 (not
571 (setq found
572 (condition-case nil
573 (progn
574 ;; Set l after this to just highlight
575 ;; the "type" part.
576 (backward-char 1)
577 ;; Needed for: type( foo(...) ) :: bar
578 (forward-sexp)
579 (setq l (list (match-beginning 0) (point)))
580 (skip-chars-forward " \t")
581 (when
582 (re-search-forward
583 ;; type (foo) bar, qux
584 (if (looking-at "\\(?:\\sw\\|\\s_\\)+")
585 "\\([^&!\n]+\\)"
586 ;; type (foo), stuff :: bar, qux
587 "::[ \t]*\\([^&!\n]+\\)")
588 (line-end-position) t)
589 (set-match-data
590 (append (list (car l) (match-end 1))
591 l (list (match-beginning 1)
592 (match-end 1))))
593 t))
594 (error nil))))))
595 found))
596
597 (defvar f90-font-lock-keywords-2
598 (append
599 f90-font-lock-keywords-1
600 (list
601 ;; Variable declarations (avoid the real function call).
602 ;; NB by accident (?), this correctly fontifies the "integer" in:
603 ;; integer () function foo ()
604 ;; because "() function foo ()" matches \\3.
605 ;; The "pure" part does not really belong here, but was added to
606 ;; exploit that hack.
607 ;; The "function foo" bit is correctly fontified by keywords-1.
608 ;; TODO ? actually check for balanced parens in that case.
609 '("^[ \t0-9]*\\(?:pure\\|elemental\\)?[ \t]*\
610 \\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|\
611 enumerator\\|generic\\|procedure\\|logical\\|double[ \t]*precision\\)\
612 \\(.*::\\|[ \t]*(.*)\\)?\\([^&!\n]*\\)"
613 (1 font-lock-type-face t) (4 font-lock-variable-name-face t))
614 ;; Derived type/class variables.
615 ;; TODO ? If we just highlighted the "type" part, rather than
616 ;; "type(...)", this could be in the previous expression. And this
617 ;; would be consistent with integer( kind=8 ), etc.
618 '(f90-typedec-matcher
619 (1 font-lock-type-face) (2 font-lock-variable-name-face))
620 ;; "real function foo (args)". Must override previous. Note hack
621 ;; to get "args" unhighlighted again. Might not always be right,
622 ;; but probably better than leaving them as variables.
623 ;; NB not explicitly handling this case:
624 ;; integer( kind=1 ) function foo()
625 ;; thanks to the happy accident described above.
626 ;; Not anchored, so don't need to worry about "pure" etc.
627 '("\\_<\\(\\(real\\|integer\\|c\\(haracter\\|omplex\\)\\|\
628 logical\\|double[ \t]*precision\\|\
629 \\(?:type\\|class\\)[ \t]*([ \t]*\\(?:\\sw\\|\\s_\\)+[ \t]*)\\)[ \t]*\\)\
630 \\(function\\)\\_>[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*\\(([^&!\n]*)\\)"
631 (1 font-lock-type-face t) (4 font-lock-keyword-face t)
632 (5 font-lock-function-name-face t) (6 'default t))
633 ;; enum (F2003; must be followed by ", bind(C)").
634 '("\\_<\\(enum\\)[ \t]*," (1 font-lock-keyword-face))
635 ;; end do, enum (F2003), if, select, where, and forall constructs.
636 ;; block, critical (F2008).
637 ;; Note that "block data" may get somewhat mixed up with F2008 blocks,
638 ;; but since the former is obsolete I'm not going to worry about it.
639 '("\\_<\\(end[ \t]*\\(do\\|if\\|enum\\|select\\|forall\\|where\\|\
640 block\\|critical\\)\\)\\_>\
641 \\([ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)\\)?"
642 (1 font-lock-keyword-face) (3 font-lock-constant-face nil t))
643 '("^[ \t0-9]*\\(\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:[ \t]*\\)?\\(\\(if\\|\
644 do\\([ \t]*while\\)?\\|select[ \t]*\\(?:case\\|type\\)\\|where\\|\
645 forall\\|block\\|critical\\)\\)\\_>"
646 (2 font-lock-constant-face nil t) (3 font-lock-keyword-face))
647 ;; Implicit declaration.
648 '("\\_<\\(implicit\\)[ \t]*\\(real\\|integer\\|c\\(haracter\\|omplex\\)\
649 \\|enumerator\\|procedure\\|\
650 logical\\|double[ \t]*precision\\|type[ \t]*(\\(?:\\sw\\|\\s_\\)+)\\|none\\)[ \t]*"
651 (1 font-lock-keyword-face) (2 font-lock-type-face))
652 '("\\_<\\(namelist\\|common\\)[ \t]*/\\(\\(?:\\sw\\|\\s_\\)+\\)?\/"
653 (1 font-lock-keyword-face) (2 font-lock-constant-face nil t))
654 "\\_<else\\([ \t]*if\\|where\\)?\\_>"
655 '("\\(&\\)[ \t]*\\(!\\|$\\)" (1 font-lock-keyword-face))
656 "\\_<\\(then\\|continue\\|format\\|include\\|\\(?:error[ \t]+\\)?stop\\|\
657 return\\)\\_>"
658 '("\\_<\\(exit\\|cycle\\)[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)?\\_>"
659 (1 font-lock-keyword-face) (2 font-lock-constant-face nil t))
660 '("\\_<\\(case\\)[ \t]*\\(default\\|(\\)" . 1)
661 ;; F2003 "class default".
662 '("\\_<\\(class\\)[ \t]*default" . 1)
663 ;; F2003 "type is" in a "select type" block.
664 '("\\_<\\(\\(type\\|class\\)[ \t]*is\\)[ \t]*(" (1 font-lock-keyword-face t))
665 '("\\_<\\(do\\|go[ \t]*to\\)\\_>[ \t]*\\([0-9]+\\)"
666 (1 font-lock-keyword-face) (2 font-lock-constant-face))
667 ;; Line numbers (lines whose first character after number is letter).
668 '("^[ \t]*\\([0-9]+\\)[ \t]*[a-z]+" (1 font-lock-constant-face t))
669 ;; Override eg for "#include".
670 '("^#[ \t]*\\(?:\\sw\\|\\s_\\)+" (0 font-lock-preprocessor-face t)
671 ("\\_<defined\\_>" nil nil (0 font-lock-preprocessor-face)))
672 '("^#" ("\\(&&\\|||\\)" nil nil (0 font-lock-constant-face t)))
673 '("^#[ \t]*define[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)(" (1 font-lock-function-name-face))
674 '("^#[ \t]*define[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)" (1 font-lock-variable-name-face))
675 '("^#[ \t]*include[ \t]+\\(<.+>\\)" (1 font-lock-string-face))))
676 "Highlights declarations, do-loops and other constructs.")
677
678 (defvar f90-font-lock-keywords-3
679 (append f90-font-lock-keywords-2
680 (list
681 f90-keywords-level-3-re
682 f90-operators-re
683 ;; FIXME why isn't this font-lock-builtin-face, which
684 ;; otherwise we hardly use, as in fortran.el?
685 (list f90-procedures-re '(1 font-lock-keyword-face keep))
686 "\\_<real\\_>" ; avoid overwriting real defs
687 ;; As an attribute, but not as an optional argument.
688 '("\\_<\\(asynchronous\\)[ \t]*[^=]" . 1)))
689 "Highlights all F90 keywords and intrinsic procedures.")
690
691 (defvar f90-font-lock-keywords-4
692 (append f90-font-lock-keywords-3
693 (list (cons f90-constants-re 'font-lock-constant-face)
694 f90-hpf-keywords-re))
695 "Highlights all F90 and HPF keywords and constants.")
696
697 (defvar f90-font-lock-keywords
698 f90-font-lock-keywords-2
699 "Default expressions to highlight in F90 mode.
700 Can be overridden by the value of `font-lock-maximum-decoration'.")
701
702
703 (defvar f90-mode-syntax-table
704 (let ((table (make-syntax-table)))
705 (modify-syntax-entry ?\! "<" table) ; begin comment
706 (modify-syntax-entry ?\n ">" table) ; end comment
707 (modify-syntax-entry ?_ "_" table) ; underscore in names
708 (modify-syntax-entry ?\' "\"" table) ; string quote
709 (modify-syntax-entry ?\" "\"" table) ; string quote
710 ;; FIXME: We used to set ` to word syntax for the benefit of abbrevs, but
711 ;; we do not need it any more. Not sure if it should be "_" or "." now.
712 (modify-syntax-entry ?\` "_" table)
713 (modify-syntax-entry ?\r " " table) ; return is whitespace
714 (modify-syntax-entry ?+ "." table) ; punctuation
715 (modify-syntax-entry ?- "." table)
716 (modify-syntax-entry ?= "." table)
717 (modify-syntax-entry ?* "." table)
718 (modify-syntax-entry ?/ "." table)
719 (modify-syntax-entry ?% "." table) ; bug#8820
720 ;; I think that the f95 standard leaves the behavior of \
721 ;; unspecified, but that f2k will require it to be non-special.
722 ;; Use `f90-backslash-not-special' to change.
723 (modify-syntax-entry ?\\ "\\" table) ; escape chars
724 table)
725 "Syntax table used in F90 mode.")
726
727 (defvar f90-mode-map
728 (let ((map (make-sparse-keymap)))
729 (define-key map "`" 'f90-abbrev-start)
730 (define-key map "\C-c;" 'f90-comment-region)
731 (define-key map "\C-\M-a" 'f90-beginning-of-subprogram)
732 (define-key map "\C-\M-e" 'f90-end-of-subprogram)
733 (define-key map "\C-\M-h" 'f90-mark-subprogram)
734 (define-key map "\C-\M-n" 'f90-end-of-block)
735 (define-key map "\C-\M-p" 'f90-beginning-of-block)
736 (define-key map "\C-\M-q" 'f90-indent-subprogram)
737 (define-key map "\C-j" 'f90-indent-new-line) ; LFD equals C-j
738 ;;; (define-key map "\r" 'newline)
739 (define-key map "\C-c\r" 'f90-break-line)
740 ;;; (define-key map [M-return] 'f90-break-line)
741 (define-key map "\C-c\C-a" 'f90-previous-block)
742 (define-key map "\C-c\C-e" 'f90-next-block)
743 (define-key map "\C-c\C-d" 'f90-join-lines)
744 (define-key map "\C-c\C-f" 'f90-fill-region)
745 (define-key map "\C-c\C-p" 'f90-previous-statement)
746 (define-key map "\C-c\C-n" 'f90-next-statement)
747 (define-key map "\C-c]" 'f90-insert-end)
748 (define-key map "\C-c\C-w" 'f90-insert-end)
749 ;; Standard tab binding will call this, and also handle regions.
750 ;;; (define-key map "\t" 'f90-indent-line)
751 (define-key map "," 'f90-electric-insert)
752 (define-key map "+" 'f90-electric-insert)
753 (define-key map "-" 'f90-electric-insert)
754 (define-key map "*" 'f90-electric-insert)
755 (define-key map "/" 'f90-electric-insert)
756
757 (easy-menu-define f90-menu map "Menu for F90 mode."
758 `("F90"
759 ("Customization"
760 ,(custom-menu-create 'f90)
761 ;; FIXME useless?
762 ["Set" Custom-set :active t
763 :help "Set current value of all edited settings in the buffer"]
764 ["Save" Custom-save :active t
765 :help "Set and save all edited settings"]
766 ["Reset to Current" Custom-reset-current :active t
767 :help "Reset all edited settings to current"]
768 ["Reset to Saved" Custom-reset-saved :active t
769 :help "Reset all edited or set settings to saved"]
770 ["Reset to Standard Settings" Custom-reset-standard :active t
771 :help "Erase all customizations in buffer"]
772 )
773 "--"
774 ["Indent Subprogram" f90-indent-subprogram t]
775 ["Mark Subprogram" f90-mark-subprogram :active t :help
776 "Mark the end of the current subprogram, move point to the start"]
777 ["Beginning of Subprogram" f90-beginning-of-subprogram :active t
778 :help "Move point to the start of the current subprogram"]
779 ["End of Subprogram" f90-end-of-subprogram :active t
780 :help "Move point to the end of the current subprogram"]
781 "--"
782 ["(Un)Comment Region" f90-comment-region :active mark-active
783 :help "Comment or uncomment the region"]
784 ["Indent Region" f90-indent-region :active mark-active]
785 ["Fill Region" f90-fill-region :active mark-active
786 :help "Fill long lines in the region"]
787 "--"
788 ["Break Line at Point" f90-break-line :active t
789 :help "Break the current line at point"]
790 ["Join with Previous Line" f90-join-lines :active t
791 :help "Join the current line to the previous one"]
792 ["Insert Block End" f90-insert-end :active t
793 :help "Insert an end statement for the current code block"]
794 "--"
795 ("Highlighting"
796 :help "Fontify this buffer to varying degrees"
797 ["Toggle font-lock-mode" font-lock-mode :selected font-lock-mode
798 :style toggle :help "Fontify text in this buffer"]
799 "--"
800 ["Light highlighting (level 1)" f90-font-lock-1 t]
801 ["Moderate highlighting (level 2)" f90-font-lock-2 t]
802 ["Heavy highlighting (level 3)" f90-font-lock-3 t]
803 ["Maximum highlighting (level 4)" f90-font-lock-4 t]
804 )
805 ("Change Keyword Case"
806 :help "Change the case of keywords in the buffer or region"
807 ["Upcase Keywords (buffer)" f90-upcase-keywords t]
808 ["Capitalize Keywords (buffer)" f90-capitalize-keywords t]
809 ["Downcase Keywords (buffer)" f90-downcase-keywords t]
810 "--"
811 ["Upcase Keywords (region)" f90-upcase-region-keywords
812 mark-active]
813 ["Capitalize Keywords (region)" f90-capitalize-region-keywords
814 mark-active]
815 ["Downcase Keywords (region)" f90-downcase-region-keywords
816 mark-active]
817 )
818 "--"
819 ["Toggle Auto Fill" auto-fill-mode :selected auto-fill-function
820 :style toggle
821 :help "Automatically fill text while typing in this buffer"]
822 ["Toggle Abbrev Mode" abbrev-mode :selected abbrev-mode
823 :style toggle :help "Expand abbreviations while typing in this buffer"]
824 ["Add Imenu Menu" f90-add-imenu-menu
825 :active (not (lookup-key (current-local-map) [menu-bar index]))
826 :included (fboundp 'imenu-add-to-menubar)
827 :help "Add an index menu to the menu-bar"
828 ]))
829 map)
830 "Keymap used in F90 mode.")
831
832
833 (defun f90-font-lock-n (n)
834 "Set `font-lock-keywords' to F90 level N keywords."
835 (font-lock-mode 1)
836 (setq font-lock-keywords
837 (symbol-value (intern-soft (format "f90-font-lock-keywords-%d" n))))
838 (font-lock-flush))
839
840 (defun f90-font-lock-1 ()
841 "Set `font-lock-keywords' to `f90-font-lock-keywords-1'."
842 (interactive)
843 (f90-font-lock-n 1))
844
845 (defun f90-font-lock-2 ()
846 "Set `font-lock-keywords' to `f90-font-lock-keywords-2'."
847 (interactive)
848 (f90-font-lock-n 2))
849
850 (defun f90-font-lock-3 ()
851 "Set `font-lock-keywords' to `f90-font-lock-keywords-3'."
852 (interactive)
853 (f90-font-lock-n 3))
854
855 (defun f90-font-lock-4 ()
856 "Set `font-lock-keywords' to `f90-font-lock-keywords-4'."
857 (interactive)
858 (f90-font-lock-n 4))
859 \f
860 ;; Regexps for finding program structures.
861 (defconst f90-blocks-re
862 (concat "\\(\\(?:block[ \t]*data\\|"
863 (regexp-opt '("do" "if" "interface" "function" "module" "program"
864 "select" "subroutine" "type" "where" "forall"
865 ;; F2003.
866 "enum" "associate"
867 ;; F2008.
868 "submodule" "block" "critical"))
869 "\\)\\_>\\)")
870 "Regexp potentially indicating a \"block\" of F90 code.")
871
872 (defconst f90-program-block-re
873 (regexp-opt '("program" "module" "subroutine" "function" "submodule") 'paren)
874 "Regexp used to locate the start/end of a \"subprogram\".")
875
876 ;; "class is" is F2003.
877 (defconst f90-else-like-re
878 "\\(else\\([ \t]*if\\|where\\)?\\|case[ \t]*\\(default\\|(\\)\\|\
879 \\(class\\|type\\)[ \t]*is[ \t]*(\\|class[ \t]*default\\)"
880 "Regexp matching an ELSE IF, ELSEWHERE, CASE, CLASS/TYPE IS statement.")
881
882 (defconst f90-end-if-re
883 (concat "end[ \t]*"
884 (regexp-opt '("if" "select" "where" "forall") 'paren)
885 "\\_>")
886 "Regexp matching the end of an IF, SELECT, WHERE, FORALL block.")
887
888 (defconst f90-end-type-re
889 "end[ \t]*\\(type\\|enum\\|interface\\|block[ \t]*data\\)\\_>"
890 "Regexp matching the end of a TYPE, ENUM, INTERFACE, BLOCK DATA section.")
891
892 (defconst f90-end-associate-re
893 "end[ \t]*associate\\_>"
894 "Regexp matching the end of an ASSOCIATE block.")
895
896 ;; This is for a TYPE block, not a variable of derived TYPE.
897 ;; Hence no need to add CLASS for F2003.
898 (defconst f90-type-def-re
899 ;; type word
900 ;; type :: word
901 ;; type, attr-list :: word
902 ;; where attr-list = attr [, attr ...]
903 ;; and attr may include bind(c) or extends(thing)
904 ;; NOT "type ("
905 "\\_<\\(type\\)\\_>\\(?:\\(?:[^()\n]*\\|\
906 .*,[ \t]*\\(?:bind\\|extends\\)[ \t]*(.*).*\\)::\\)?\
907 [ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)"
908 "Regexp matching the definition of a derived type.")
909
910 (defconst f90-typeis-re
911 "\\_<\\(class\\|type\\)[ \t]*is[ \t]*("
912 "Regexp matching a CLASS/TYPE IS statement.")
913
914 (defconst f90-no-break-re
915 (regexp-opt '("**" "//" "=>" ">=" "<=" "==" "/=" "(/" "/)") 'paren)
916 "Regexp specifying two-character tokens not to split when breaking lines.
917 Each token has one or more of the characters from `f90-break-delimiters'.
918 Note that if only one of the characters is from that variable,
919 then the presence of the token here allows a line-break before or
920 after the other character, where a break would not normally be
921 allowed. This minor issue currently only affects \"(/\" and \"/)\".")
922
923 (defvar f90-cache-position nil
924 "Temporary position used to speed up region operations.")
925 (make-variable-buffer-local 'f90-cache-position)
926
927 \f
928 ;; Hideshow support.
929 (defconst f90-end-block-re
930 (concat "^[ \t0-9]*\\_<end[ \t]*"
931 (regexp-opt '("do" "if" "forall" "function" "interface"
932 "module" "program" "select" "subroutine"
933 "type" "where" "enum" "associate" "submodule"
934 "block" "critical") t)
935 "\\_>")
936 "Regexp matching the end of an F90 \"block\", from the line start.
937 Used in the F90 entry in `hs-special-modes-alist'.")
938
939 ;; Ignore the fact that FUNCTION, SUBROUTINE, WHERE, FORALL have a
940 ;; following "(". DO, CASE, IF can have labels.
941 (defconst f90-start-block-re
942 (concat
943 "^[ \t0-9]*" ; statement number
944 "\\(\\("
945 "\\(\\(?:\\sw\\|\\s_\\)+[ \t]*:[ \t]*\\)?" ; structure label
946 "\\(do\\|select[ \t]*\\(case\\|type\\)\\|"
947 ;; See comments in fortran-start-block-re for the problems of IF.
948 "if[ \t]*(\\(.*\\|"
949 ".*\n\\([^if]*\\([^i].\\|.[^f]\\|.\\_>\\)\\)\\)\\_<then\\|"
950 ;; Distinguish WHERE block from isolated WHERE.
951 "\\(where\\|forall\\)[ \t]*(.*)[ \t]*\\(!\\|$\\)\\)\\)"
952 "\\|"
953 ;; Avoid F2003 "type is" in "select type",
954 ;; and also variables of derived type "type (foo)".
955 ;; "type, foo" must be a block (?).
956 "type[ \t,]\\("
957 "[^i(!\n\"& \t]\\|" ; not-i(
958 "i[^s!\n\"& \t]\\|" ; i not-s
959 "is\\(?:\\sw\\|\\s_\\)\\)\\|"
960 ;; "abstract interface" is F2003; "submodule" is F2008.
961 "program\\|\\(?:abstract[ \t]*\\)?interface\\|\\(?:sub\\)?module\\|"
962 ;; "enum", but not "enumerator".
963 "function\\|subroutine\\|enum[^e]\\|associate\\|block\\|critical"
964 "\\)"
965 "[ \t]*")
966 "Regexp matching the start of an F90 \"block\", from the line start.
967 A simple regexp cannot do this in fully correct fashion, so this
968 tries to strike a compromise between complexity and flexibility.
969 Used in the F90 entry in `hs-special-modes-alist'.")
970
971 ;; hs-special-modes-alist is autoloaded.
972 (add-to-list 'hs-special-modes-alist
973 `(f90-mode ,f90-start-block-re ,f90-end-block-re
974 "!" f90-end-of-block nil))
975
976 \f
977 ;; Imenu support.
978 ;; FIXME trivial to extend this to enum. Worth it?
979 (defun f90-imenu-type-matcher ()
980 "Search backward for the start of a derived type.
981 Set subexpression 1 in the match-data to the name of the type."
982 (let (found)
983 (while (and (re-search-backward "^[ \t0-9]*type[ \t]*" nil t)
984 (not (setq found
985 (save-excursion
986 (goto-char (match-end 0))
987 (unless (looking-at "\\(is\\_>\\|(\\)")
988 (or (looking-at "\\(\\(?:\\sw\\|\\s_\\)+\\)")
989 (re-search-forward
990 "[ \t]*::[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)"
991 (line-end-position) t))))))))
992 found))
993
994 (defvar f90-imenu-generic-expression
995 (let ((good-char "[^!\"&\n \t]") (not-e "[^e!\n\"& \t]")
996 (not-n "[^n!\n\"& \t]") (not-d "[^d!\n\"& \t]")
997 ;; (not-ib "[^i(!\n\"& \t]") (not-s "[^s!\n\"& \t]")
998 )
999 `((nil "^[ \t0-9]*program[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)" 1)
1000 ("Submodules" "^[ \t0-9]*submodule[ \t]*([^)\n]+)[ \t]*\
1001 \\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*\\(!\\|$\\)" 1)
1002 ("Modules" "^[ \t0-9]*module[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*\\(!\\|$\\)" 1)
1003 ("Types" f90-imenu-type-matcher 1)
1004 ;; Does not handle: "type[, stuff] :: foo".
1005 ;;(format "^[ \t0-9]*type[ \t]+\\(\\(%s\\|i%s\\|is\\(?:\\sw\\|\\s_\\)\\)\\(?:\\sw\\|\\s_\\)*\\)"
1006 ;; not-ib not-s)
1007 ;;1)
1008 ;; Can't get the subexpression numbers to match in the two branches.
1009 ;; FIXME: Now with \(?N:..\) we can get the numbers to match!
1010 ;;(format "^[ \t0-9]*type\\([ \t]*,.*\\(::\\)[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)\\|[ \t]+\\(\\(%s\\|i%s\\|is\\(?:\\sw\\|\\s_\\)\\)\\(?:\\sw\\|\\s_\\)*\\)\\)" not-ib not-s)
1011 ;;3)
1012 ("Procedures"
1013 ,(concat
1014 "^[ \t0-9]*"
1015 "\\("
1016 ;; At least three non-space characters before function/subroutine.
1017 ;; Check that the last three non-space characters do not spell E N D.
1018 "[^!\"&\n]*\\("
1019 not-e good-char good-char "\\|"
1020 good-char not-n good-char "\\|"
1021 good-char good-char not-d "\\)"
1022 "\\|"
1023 ;; Less than three non-space characters before function/subroutine.
1024 good-char "?" good-char "?"
1025 "\\)"
1026 "[ \t]*\\(function\\|subroutine\\)[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)")
1027 4)))
1028 "Value for `imenu-generic-expression' in F90 mode.")
1029
1030 (defun f90-add-imenu-menu ()
1031 "Add an imenu menu to the menubar."
1032 (interactive)
1033 (if (lookup-key (current-local-map) [menu-bar index])
1034 (message "%s" "F90-imenu already exists.")
1035 (imenu-add-to-menubar "F90-imenu")
1036 (redraw-frame)))
1037
1038 \f
1039 ;; Abbrevs have generally two letters, except standard types `c, `i, `r, `t.
1040 (define-abbrev-table 'f90-mode-abbrev-table
1041 (mapcar (lambda (e) (list (car e) (cdr e) nil :system t))
1042 '(("`al" . "allocate" )
1043 ("`ab" . "allocatable" )
1044 ("`ai" . "abstract interface")
1045 ("`as" . "assignment" )
1046 ("`asy" . "asynchronous" )
1047 ("`ba" . "backspace" )
1048 ("`bd" . "block data" )
1049 ("`bl" . "block" )
1050 ("`c" . "character" )
1051 ("`cl" . "close" )
1052 ("`cm" . "common" )
1053 ("`cx" . "complex" )
1054 ("`cn" . "contains" )
1055 ("`cr" . "critical" )
1056 ("`cy" . "cycle" )
1057 ("`de" . "deallocate" )
1058 ("`df" . "define" )
1059 ("`di" . "dimension" )
1060 ("`dp" . "double precision")
1061 ("`dw" . "do while" )
1062 ("`el" . "else" )
1063 ("`eli" . "else if" )
1064 ("`elw" . "elsewhere" )
1065 ("`em" . "elemental" )
1066 ("`e" . "enumerator" )
1067 ("`eq" . "equivalence" )
1068 ("`ex" . "external" )
1069 ("`ey" . "entry" )
1070 ("`fl" . "forall" )
1071 ("`fo" . "format" )
1072 ("`fu" . "function" )
1073 ("`fa" . ".false." )
1074 ("`im" . "implicit none")
1075 ("`in" . "include" )
1076 ("`i" . "integer" )
1077 ("`it" . "intent" )
1078 ("`if" . "interface" )
1079 ("`lo" . "logical" )
1080 ("`mo" . "module" )
1081 ("`na" . "namelist" )
1082 ("`nu" . "nullify" )
1083 ("`op" . "optional" )
1084 ("`pa" . "parameter" )
1085 ("`po" . "pointer" )
1086 ("`pr" . "print" )
1087 ("`pi" . "private" )
1088 ("`pm" . "program" )
1089 ("`pr" . "protected" )
1090 ("`pu" . "public" )
1091 ("`r" . "real" )
1092 ("`rc" . "recursive" )
1093 ("`rt" . "return" )
1094 ("`rw" . "rewind" )
1095 ("`se" . "select" )
1096 ("`sq" . "sequence" )
1097 ("`su" . "subroutine" )
1098 ("`ta" . "target" )
1099 ("`tr" . ".true." )
1100 ("`t" . "type" )
1101 ("`vo" . "volatile" )
1102 ("`wh" . "where" )
1103 ("`wr" . "write" )))
1104 "Abbrev table for F90 mode."
1105 ;; Accept ` as the first char of an abbrev. Also allow _ in abbrevs.
1106 :regexp "\\(?:[^[:word:]_`]\\|^\\)\\(`?[[:word:]_]+\\)[^[:word:]_]*")
1107 \f
1108 ;;;###autoload
1109 (define-derived-mode f90-mode prog-mode "F90"
1110 "Major mode for editing Fortran 90,95 code in free format.
1111 For fixed format code, use `fortran-mode'.
1112
1113 \\[f90-indent-line] indents the current line.
1114 \\[f90-indent-new-line] indents current line and creates a new\
1115 indented line.
1116 \\[f90-indent-subprogram] indents the current subprogram.
1117
1118 Type \\=`? or \\=`\\[help-command] to display a list of built-in\
1119 abbrevs for F90 keywords.
1120
1121 Key definitions:
1122 \\{f90-mode-map}
1123
1124 Variables controlling indentation style and extra features:
1125
1126 `f90-do-indent'
1127 Extra indentation within do blocks (default 3).
1128 `f90-if-indent'
1129 Extra indentation within if/select/where/forall blocks (default 3).
1130 `f90-type-indent'
1131 Extra indentation within type/enum/interface/block-data blocks (default 3).
1132 `f90-program-indent'
1133 Extra indentation within program/module/subroutine/function blocks
1134 (default 2).
1135 `f90-associate-indent'
1136 Extra indentation within associate blocks (default 2).
1137 `f90-critical-indent'
1138 Extra indentation within critical/block blocks (default 2).
1139 `f90-continuation-indent'
1140 Extra indentation applied to continuation lines (default 5).
1141 `f90-comment-region'
1142 String inserted by function \\[f90-comment-region] at start of each
1143 line in region (default \"!!!$\").
1144 `f90-indented-comment-re'
1145 Regexp determining the type of comment to be intended like code
1146 (default \"!\").
1147 `f90-directive-comment-re'
1148 Regexp of comment-like directive like \"!HPF\\\\$\", not to be indented
1149 (default \"!hpf\\\\$\").
1150 `f90-break-delimiters'
1151 Regexp holding list of delimiters at which lines may be broken
1152 (default \"[-+*/><=,% \\t]\").
1153 `f90-break-before-delimiters'
1154 Non-nil causes `f90-do-auto-fill' to break lines before delimiters
1155 (default t).
1156 `f90-beginning-ampersand'
1157 Automatic insertion of `&' at beginning of continuation lines (default t).
1158 `f90-smart-end'
1159 From an END statement, check and fill the end using matching block start.
1160 Allowed values are `blink', `no-blink', and nil, which determine
1161 whether to blink the matching beginning (default `blink').
1162 `f90-auto-keyword-case'
1163 Automatic change of case of keywords (default nil).
1164 The possibilities are `downcase-word', `upcase-word', `capitalize-word'.
1165 `f90-leave-line-no'
1166 Do not left-justify line numbers (default nil).
1167
1168 Turning on F90 mode calls the value of the variable `f90-mode-hook'
1169 with no args, if that value is non-nil."
1170 :group 'f90
1171 :abbrev-table f90-mode-abbrev-table
1172 (set (make-local-variable 'indent-line-function) 'f90-indent-line)
1173 (set (make-local-variable 'indent-region-function) 'f90-indent-region)
1174 (set (make-local-variable 'comment-start) "!")
1175 (set (make-local-variable 'comment-start-skip) "!+ *")
1176 (set (make-local-variable 'comment-indent-function) 'f90-comment-indent)
1177 (set (make-local-variable 'abbrev-all-caps) t)
1178 (set (make-local-variable 'normal-auto-fill-function) 'f90-do-auto-fill)
1179 (setq indent-tabs-mode nil) ; auto buffer local
1180 (set (make-local-variable 'font-lock-defaults)
1181 '((f90-font-lock-keywords f90-font-lock-keywords-1
1182 f90-font-lock-keywords-2
1183 f90-font-lock-keywords-3
1184 f90-font-lock-keywords-4)
1185 nil t))
1186 (set (make-local-variable 'imenu-case-fold-search) t)
1187 (set (make-local-variable 'imenu-generic-expression)
1188 f90-imenu-generic-expression)
1189 (set (make-local-variable 'beginning-of-defun-function)
1190 'f90-beginning-of-subprogram)
1191 (set (make-local-variable 'end-of-defun-function) 'f90-end-of-subprogram)
1192 (set (make-local-variable 'add-log-current-defun-function)
1193 #'f90-current-defun))
1194
1195 \f
1196 ;; Inline-functions.
1197 (defsubst f90-in-string ()
1198 "Return non-nil if point is inside a string.
1199 Checks from `point-min', or `f90-cache-position', if that is non-nil
1200 and lies before point."
1201 (let ((beg-pnt
1202 (if (and f90-cache-position (> (point) f90-cache-position))
1203 f90-cache-position
1204 (point-min))))
1205 (nth 3 (parse-partial-sexp beg-pnt (point)))))
1206
1207 (defsubst f90-in-comment ()
1208 "Return non-nil if point is inside a comment.
1209 Checks from `point-min', or `f90-cache-position', if that is non-nil
1210 and lies before point."
1211 (let ((beg-pnt
1212 (if (and f90-cache-position (> (point) f90-cache-position))
1213 f90-cache-position
1214 (point-min))))
1215 (nth 4 (parse-partial-sexp beg-pnt (point)))))
1216
1217 (defsubst f90-line-continued ()
1218 "Return t if the current line is a continued one.
1219 This includes comment or preprocessor lines embedded in continued lines,
1220 but not the last line of a continued statement."
1221 (save-excursion
1222 (beginning-of-line)
1223 (while (and (looking-at "[ \t]*\\([!#]\\|$\\)") (zerop (forward-line -1))))
1224 (end-of-line)
1225 (while (f90-in-comment)
1226 (search-backward "!" (line-beginning-position))
1227 (skip-chars-backward "!"))
1228 (skip-chars-backward " \t")
1229 (= (preceding-char) ?&)))
1230
1231 ;; GM this is not right, eg a continuation line starting with a number.
1232 ;; Need f90-code-start-position function.
1233 ;; And yet, things seems to work with this...
1234 ;; cf f90-indent-line
1235 ;; (beginning-of-line) ; digits after & \n are not line-nos
1236 ;; (if (not (save-excursion (and (f90-previous-statement)
1237 ;; (f90-line-continued))))
1238 ;; (f90-indent-line-no)
1239 (defsubst f90-current-indentation ()
1240 "Return indentation of current line.
1241 Line-numbers are considered whitespace characters."
1242 (save-excursion (beginning-of-line) (skip-chars-forward " \t0-9")))
1243
1244 (defsubst f90-indent-to (col &optional no-line-number)
1245 "Indent current line to column COL.
1246 If optional argument NO-LINE-NUMBER is nil, jump over a possible
1247 line-number before indenting."
1248 (beginning-of-line)
1249 (or no-line-number
1250 (skip-chars-forward " \t0-9"))
1251 (delete-horizontal-space)
1252 ;; Leave >= 1 space after line number.
1253 (indent-to col (if (zerop (current-column)) 0 1)))
1254
1255 (defsubst f90-get-present-comment-type ()
1256 "If point lies within a comment, return the string starting the comment.
1257 For example, \"!\" or \"!!\", followed by the appropriate amount of
1258 whitespace, if any."
1259 ;; Include the whitespace for consistent auto-filling of comment blocks.
1260 (save-excursion
1261 (when (f90-in-comment)
1262 (beginning-of-line)
1263 (re-search-forward "!+[ \t]*" (line-end-position))
1264 (while (f90-in-string)
1265 (re-search-forward "!+[ \t]*" (line-end-position)))
1266 (match-string-no-properties 0))))
1267
1268 (defsubst f90-equal-symbols (a b)
1269 "Compare strings A and B neglecting case and allowing for nil value."
1270 (equal (if a (downcase a) nil)
1271 (if b (downcase b) nil)))
1272
1273 (defsubst f90-looking-at-do ()
1274 "Return (\"do\" NAME) if a do statement starts after point.
1275 NAME is nil if the statement has no label."
1276 (if (looking-at "\\(\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:\\)?[ \t]*\\(do\\)\\_>")
1277 (list (match-string 3) (match-string 2))))
1278
1279 (defsubst f90-looking-at-select-case ()
1280 "Return (\"select\" NAME) if a select statement starts after point.
1281 NAME is nil if the statement has no label."
1282 (if (looking-at "\\(\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:\\)?[ \t]*\
1283 \\(select\\)[ \t]*\\(case\\|type\\)[ \t]*(")
1284 (list (match-string 3) (match-string 2))))
1285
1286 (defsubst f90-looking-at-if-then ()
1287 "Return (\"if\" NAME) if an if () then statement starts after point.
1288 NAME is nil if the statement has no label."
1289 (save-excursion
1290 (when (looking-at "\\(\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:\\)?[ \t]*\\(if\\)\\_>")
1291 (let ((struct (match-string 3))
1292 (label (match-string 2))
1293 (pos (scan-lists (point) 1 0)))
1294 (and pos (goto-char pos))
1295 (skip-chars-forward " \t")
1296 (if (or (looking-at "then\\_>")
1297 (when (f90-line-continued)
1298 (f90-next-statement)
1299 (skip-chars-forward " \t0-9&")
1300 (looking-at "then\\_>")))
1301 (list struct label))))))
1302
1303 ;; FIXME label?
1304 (defsubst f90-looking-at-associate ()
1305 "Return (\"associate\") if an associate block starts after point."
1306 (if (looking-at "\\_<\\(associate\\)[ \t]*(")
1307 (list (match-string 1))))
1308
1309 (defsubst f90-looking-at-critical ()
1310 "Return (KIND NAME) if a critical or block block starts after point."
1311 (if (looking-at "\\(\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:\\)?[ \t]*\\(critical\\|block\\)\\_>")
1312 (let ((struct (match-string 3))
1313 (label (match-string 2)))
1314 (if (or (not (string-equal "block" struct))
1315 (save-excursion
1316 (skip-chars-forward " \t")
1317 (not (looking-at "data\\_>"))))
1318 (list struct label)))))
1319
1320 (defsubst f90-looking-at-end-critical ()
1321 "Return non-nil if a critical or block block ends after point."
1322 (if (looking-at "end[ \t]*\\(critical\\|block\\)\\_>")
1323 (or (not (string-equal "block" (match-string 1)))
1324 (save-excursion
1325 (skip-chars-forward " \t")
1326 (not (looking-at "data\\_>"))))))
1327
1328 (defsubst f90-looking-at-where-or-forall ()
1329 "Return (KIND NAME) if a where or forall block starts after point.
1330 NAME is nil if the statement has no label."
1331 (save-excursion
1332 (when (looking-at "\\(\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:\\)?[ \t]*\
1333 \\(where\\|forall\\)\\_>")
1334 (let ((struct (match-string 3))
1335 (label (match-string 2))
1336 (pos (scan-lists (point) 1 0)))
1337 (and pos (goto-char pos))
1338 (skip-chars-forward " \t")
1339 (if (looking-at "\\(!\\|$\\)") (list struct label))))))
1340
1341 (defsubst f90-looking-at-type-like ()
1342 "Return (KIND NAME) if a type/enum/interface/block-data starts after point.
1343 NAME is non-nil only for type and certain interfaces."
1344 (cond
1345 ((save-excursion
1346 (and (looking-at "\\_<type\\_>[ \t]*")
1347 (goto-char (match-end 0))
1348 (not (looking-at "\\(is\\_>\\|(\\)"))
1349 (or (looking-at "\\(\\(?:\\sw\\|\\s_\\)+\\)")
1350 (re-search-forward "[ \t]*::[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)"
1351 (line-end-position) t))))
1352 (list "type" (match-string 1)))
1353 ;;; ((and (not (looking-at f90-typeis-re))
1354 ;;; (looking-at f90-type-def-re))
1355 ;;; (list (match-string 1) (match-string 2)))
1356 ((looking-at "\\_<\\(interface\\)\\_>[ \t]*")
1357 (list (match-string 1)
1358 (save-excursion
1359 (goto-char (match-end 0))
1360 (if (or (looking-at "\\(operator\\|assignment\\|read\\|\
1361 write\\)[ \t]*([^)\n]*)")
1362 (looking-at "\\(?:\\sw\\|\\s_\\)+"))
1363 (match-string 0)))))
1364 ((looking-at "\\(enum\\|block[ \t]*data\\)\\_>")
1365 (list (match-string 1) nil))
1366 ((looking-at "abstract[ \t]*\\(interface\\)\\_>")
1367 (list (match-string 1) nil))))
1368
1369 (defsubst f90-looking-at-program-block-start ()
1370 "Return (KIND NAME) if a program block with name NAME starts after point."
1371 ;;;NAME is nil for an un-named main PROGRAM block."
1372 (cond
1373 ((looking-at "\\(program\\)[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
1374 (list (match-string 1) (match-string 2)))
1375 ((and (not (looking-at "module[ \t]*procedure\\_>"))
1376 (looking-at "\\(module\\)[ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>"))
1377 (list (match-string 1) (match-string 2)))
1378 ((looking-at "\\(submodule\\)[ \t]*([^)\n]+)[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)\\_>")
1379 (list (match-string 1) (match-string 2)))
1380 ((and (not (looking-at "end[ \t]*\\(function\\|subroutine\\)"))
1381 (looking-at "[^!'\"&\n]*\\(function\\|subroutine\\)[ \t]+\
1382 \\(\\(?:\\sw\\|\\s_\\)+\\)"))
1383 (list (match-string 1) (match-string 2)))))
1384 ;; Following will match an un-named main program block; however
1385 ;; one needs to check if there is an actual PROGRAM statement after
1386 ;; point (and before any END program). Adding this will require
1387 ;; change to eg f90-calculate-indent.
1388 ;;; ((save-excursion
1389 ;;; (not (f90-previous-statement)))
1390 ;;; '("program" nil))))
1391
1392 (defsubst f90-looking-at-program-block-end ()
1393 "Return (KIND NAME) if a block with name NAME ends after point."
1394 (cond ((looking-at "end[ \t]*\\(interface\\)[ \t]*\\(\
1395 \\(?:assignment\\|operator\\|read\\|write\\)[ \t]*([^)\n]*)\\)")
1396 (list (match-string 1) (match-string 2)))
1397 ((looking-at (concat "end[ \t]*" f90-blocks-re
1398 "?\\([ \t]+\\(\\(?:\\sw\\|\\s_\\)+\\)\\)?\\_>"))
1399 (list (match-string 1) (match-string 3)))))
1400
1401 (defsubst f90-comment-indent ()
1402 "Return the indentation to be used for a comment starting at point.
1403 Used for `comment-indent-function' by F90 mode.
1404 \"!!!\", `f90-directive-comment-re', variable `f90-comment-region' return 0.
1405 `f90-indented-comment-re' (if not trailing code) calls `f90-calculate-indent'.
1406 All others return `comment-column', leaving at least one space after code."
1407 (cond ((looking-at "!!!") 0)
1408 ((and f90-directive-comment-re
1409 (looking-at f90-directive-comment-re)) 0)
1410 ((looking-at (regexp-quote f90-comment-region)) 0)
1411 ((and (looking-at f90-indented-comment-re)
1412 ;; Don't attempt to indent trailing comment as code.
1413 (save-excursion
1414 (skip-chars-backward " \t")
1415 (bolp)))
1416 (f90-calculate-indent))
1417 (t (save-excursion
1418 (skip-chars-backward " \t")
1419 (max (if (bolp) 0 (1+ (current-column))) comment-column)))))
1420
1421 (defsubst f90-present-statement-cont ()
1422 "Return continuation properties of present statement.
1423 Possible return values are:
1424 single - statement is not continued.
1425 begin - current line is the first in a continued statement.
1426 end - current line is the last in a continued statement
1427 middle - current line is neither first nor last in a continued statement.
1428 Comment lines embedded amongst continued lines return `middle'."
1429 (let (pcont cont)
1430 (save-excursion
1431 (setq pcont (if (f90-previous-statement) (f90-line-continued))))
1432 (setq cont (f90-line-continued))
1433 (cond ((and (not pcont) (not cont)) 'single)
1434 ((and (not pcont) cont) 'begin)
1435 ((and pcont (not cont)) 'end)
1436 ((and pcont cont) 'middle)
1437 (t (error "The impossible occurred")))))
1438
1439 (defsubst f90-indent-line-no ()
1440 "If `f90-leave-line-no' is nil, left-justify a line number.
1441 Leaves point at the first non-blank character after the line number.
1442 Call from beginning of line."
1443 (and (null f90-leave-line-no) (looking-at "[ \t]+[0-9]")
1444 (delete-horizontal-space))
1445 (skip-chars-forward " \t0-9"))
1446
1447 (defsubst f90-no-block-limit ()
1448 "Return nil if point is at the edge of a code block.
1449 Searches line forward for \"function\" or \"subroutine\",
1450 if all else fails."
1451 (save-excursion
1452 (not (or (looking-at "end")
1453 (looking-at "\\(do\\|if\\|else\\(if\\|where\\)?\
1454 \\|select[ \t]*\\(case\\|type\\)\\|case\\|where\\|forall\\|\
1455 block\\|critical\\|enum\\|associate\\)\\_>")
1456 (looking-at "\\(program\\|\\(?:sub\\)?module\\|\
1457 \\(?:abstract[ \t]*\\)?interface\\|block[ \t]*data\\)\\_>")
1458 (looking-at "\\(contains\\|\\(?:\\sw\\|\\s_\\)+[ \t]*:\\)")
1459 (looking-at f90-type-def-re)
1460 (re-search-forward "\\(function\\|subroutine\\)"
1461 (line-end-position) t)))))
1462
1463 (defsubst f90-update-line ()
1464 "Change case of current line as per `f90-auto-keyword-case'."
1465 (if f90-auto-keyword-case
1466 (f90-change-keywords f90-auto-keyword-case
1467 (line-beginning-position) (line-end-position))))
1468 \f
1469 (defun f90-electric-insert (&optional arg)
1470 "Change keyword case and auto-fill line as operators are inserted."
1471 (interactive "*p")
1472 (self-insert-command arg)
1473 (if auto-fill-function (f90-do-auto-fill) ; also updates line
1474 (f90-update-line)))
1475
1476 ;; Behave like self-insert-command for delete-selection-mode (bug#5593).
1477 (put 'f90-electric-insert 'delete-selection t)
1478
1479 (defun f90-get-correct-indent ()
1480 "Get correct indent for a line starting with line number.
1481 Does not check type and subprogram indentation."
1482 (let ((epnt (line-end-position)) icol)
1483 (save-excursion
1484 (while (and (f90-previous-statement)
1485 (or (memq (f90-present-statement-cont) '(middle end))
1486 (looking-at "[ \t]*[0-9]"))))
1487 (setq icol (current-indentation))
1488 (beginning-of-line)
1489 (when (re-search-forward "\\(if\\|do\\|select\\|where\\|forall\\)"
1490 (line-end-position) t)
1491 (beginning-of-line)
1492 (skip-chars-forward " \t")
1493 (cond ((f90-looking-at-do)
1494 (setq icol (+ icol f90-do-indent)))
1495 ((or (f90-looking-at-if-then)
1496 (f90-looking-at-where-or-forall)
1497 (f90-looking-at-select-case))
1498 (setq icol (+ icol f90-if-indent)))
1499 ;; FIXME this makes no sense, because this section/function is
1500 ;; only for if/do/select/where/forall ?
1501 ((f90-looking-at-associate)
1502 (setq icol (+ icol f90-associate-indent))))
1503 (end-of-line))
1504 (while (re-search-forward
1505 "\\(if\\|do\\|select\\|where\\|forall\\)" epnt t)
1506 (beginning-of-line)
1507 (skip-chars-forward " \t0-9")
1508 (cond ((f90-looking-at-do)
1509 (setq icol (+ icol f90-do-indent)))
1510 ((or (f90-looking-at-if-then)
1511 (f90-looking-at-where-or-forall)
1512 (f90-looking-at-select-case))
1513 (setq icol (+ icol f90-if-indent)))
1514 ;; FIXME this makes no sense, because this section/function is
1515 ;; only for if/do/select/where/forall ?
1516 ((f90-looking-at-associate)
1517 (setq icol (+ icol f90-associate-indent)))
1518 ((looking-at f90-end-if-re)
1519 (setq icol (- icol f90-if-indent)))
1520 ((looking-at f90-end-associate-re)
1521 (setq icol (- icol f90-associate-indent)))
1522 ((f90-looking-at-end-critical)
1523 (setq icol (- icol f90-critical-indent)))
1524 ((looking-at "end[ \t]*do\\_>")
1525 (setq icol (- icol f90-do-indent))))
1526 (end-of-line))
1527 icol)))
1528
1529 (defun f90-calculate-indent ()
1530 "Calculate the indent column based on previous statements."
1531 (interactive)
1532 (let (icol cont (case-fold-search t) (pnt (point)))
1533 (save-excursion
1534 (if (not (f90-previous-statement))
1535 ;; If f90-previous-statement returns nil, we must have been
1536 ;; called from on or before the first line of the first statement.
1537 (setq icol (if (or (save-excursion
1538 (goto-char pnt)
1539 (beginning-of-line)
1540 ;; Preprocessor line before code statement.
1541 (looking-at "[ \t]*#"))
1542 (progn
1543 ;; f90-previous-statement has moved us over
1544 ;; comment/blank lines, so we need to get
1545 ;; back to the first code statement.
1546 (when (looking-at "[ \t]*\\([!#]\\|$\\)")
1547 (f90-next-statement))
1548 (skip-chars-forward " \t0-9")
1549 (f90-looking-at-program-block-start)))
1550 0
1551 ;; No explicit PROGRAM start statement.
1552 f90-program-indent))
1553 (setq cont (f90-present-statement-cont))
1554 (if (eq cont 'end)
1555 (while (not (eq 'begin (f90-present-statement-cont)))
1556 (f90-previous-statement)))
1557 (cond ((eq cont 'begin)
1558 (setq icol (+ (f90-current-indentation)
1559 f90-continuation-indent)))
1560 ((eq cont 'middle) (setq icol (current-indentation)))
1561 (t (setq icol (f90-current-indentation))
1562 (skip-chars-forward " \t")
1563 (if (looking-at "[0-9]")
1564 (setq icol (f90-get-correct-indent))
1565 (cond ((or (f90-looking-at-if-then)
1566 (f90-looking-at-where-or-forall)
1567 (f90-looking-at-select-case)
1568 (looking-at f90-else-like-re))
1569 (setq icol (+ icol f90-if-indent)))
1570 ((f90-looking-at-do)
1571 (setq icol (+ icol f90-do-indent)))
1572 ((f90-looking-at-type-like)
1573 (setq icol (+ icol f90-type-indent)))
1574 ((f90-looking-at-associate)
1575 (setq icol (+ icol f90-associate-indent)))
1576 ((f90-looking-at-critical)
1577 (setq icol (+ icol f90-critical-indent)))
1578 ((or (f90-looking-at-program-block-start)
1579 (looking-at "contains[ \t]*\\($\\|!\\)"))
1580 (setq icol (+ icol f90-program-indent)))))
1581 (goto-char pnt)
1582 (beginning-of-line)
1583 (cond ((looking-at "[ \t]*$"))
1584 ((looking-at "[ \t]*#") ; check for cpp directive
1585 (setq icol 0))
1586 (t
1587 (skip-chars-forward " \t0-9")
1588 (cond ((or (looking-at f90-else-like-re)
1589 (looking-at f90-end-if-re))
1590 (setq icol (- icol f90-if-indent)))
1591 ((looking-at "end[ \t]*do\\_>")
1592 (setq icol (- icol f90-do-indent)))
1593 ((looking-at f90-end-type-re)
1594 (setq icol (- icol f90-type-indent)))
1595 ((looking-at f90-end-associate-re)
1596 (setq icol (- icol f90-associate-indent)))
1597 ((f90-looking-at-end-critical)
1598 (setq icol (- icol f90-critical-indent)))
1599 ((or (looking-at "contains[ \t]*\\(!\\|$\\)")
1600 (f90-looking-at-program-block-end))
1601 (setq icol (- icol f90-program-indent))))))))))
1602 icol))
1603 \f
1604 (defun f90-previous-statement ()
1605 "Move point to beginning of the previous F90 statement.
1606 If no previous statement is found (i.e. if called from the first
1607 statement in the buffer), move to the start of the buffer and
1608 return nil. A statement is a line which is neither blank nor a
1609 comment."
1610 (interactive)
1611 (let (not-first-statement)
1612 (beginning-of-line)
1613 (while (and (setq not-first-statement (zerop (forward-line -1)))
1614 (looking-at "[ \t0-9]*\\(!\\|$\\|#\\)")))
1615 not-first-statement))
1616
1617 (defun f90-next-statement ()
1618 "Move point to beginning of the next F90 statement.
1619 Return nil if no later statement is found."
1620 (interactive)
1621 (let (not-last-statement)
1622 (beginning-of-line)
1623 (while (and (setq not-last-statement
1624 (and (zerop (forward-line 1))
1625 (not (eobp))))
1626 (looking-at "[ \t0-9]*\\(!\\|$\\|#\\)")))
1627 not-last-statement))
1628
1629 (defun f90-beginning-of-subprogram ()
1630 "Move point to the beginning of the current subprogram.
1631 Return (TYPE NAME), or nil if not found."
1632 (interactive)
1633 (let ((count 1) (case-fold-search t) matching-beg)
1634 (beginning-of-line)
1635 (while (and (> count 0)
1636 (re-search-backward f90-program-block-re nil 'move))
1637 (beginning-of-line)
1638 (skip-chars-forward " \t0-9")
1639 ;; Check if in string in case using non-standard feature where
1640 ;; continued strings do not need "&" at start of continuations.
1641 (cond ((f90-in-string))
1642 ((setq matching-beg (f90-looking-at-program-block-start))
1643 (setq count (1- count)))
1644 ((f90-looking-at-program-block-end)
1645 (setq count (1+ count)))))
1646 (beginning-of-line)
1647 (if (zerop count)
1648 matching-beg
1649 ;; Note this includes the case of an un-named main program,
1650 ;; in which case we go to (point-min).
1651 (if (called-interactively-p 'interactive)
1652 (message "No beginning found"))
1653 nil)))
1654
1655 (defun f90-end-of-subprogram ()
1656 "Move point to the end of the current subprogram.
1657 Return (TYPE NAME), or nil if not found."
1658 (interactive)
1659 (let ((case-fold-search t)
1660 (count 1)
1661 matching-end)
1662 (end-of-line)
1663 (while (and (> count 0)
1664 (re-search-forward f90-program-block-re nil 'move))
1665 (beginning-of-line)
1666 (skip-chars-forward " \t0-9")
1667 (cond ((f90-in-string))
1668 ((f90-looking-at-program-block-start)
1669 (setq count (1+ count)))
1670 ((setq matching-end (f90-looking-at-program-block-end))
1671 (setq count (1- count))))
1672 (end-of-line))
1673 ;; This means f90-end-of-subprogram followed by f90-start-of-subprogram
1674 ;; has a net non-zero effect, which seems odd.
1675 ;;; (forward-line 1)
1676 (if (zerop count)
1677 matching-end
1678 (if (called-interactively-p 'interactive)
1679 (message "No end found"))
1680 nil)))
1681
1682
1683 (defun f90-end-of-block (&optional num)
1684 "Move point forward to the end of the current code block.
1685 With optional argument NUM, go forward that many balanced blocks.
1686 If NUM is negative, go backward to the start of a block. Checks
1687 for consistency of block types and labels (if present), and
1688 completes outermost block if `f90-smart-end' is non-nil.
1689 Interactively, pushes mark before moving point."
1690 (interactive "p")
1691 ;; Can move some distance.
1692 (if (called-interactively-p 'any) (push-mark (point) t))
1693 (and num (< num 0) (f90-beginning-of-block (- num)))
1694 (let ((f90-smart-end (if f90-smart-end 'no-blink)) ; for final match-end
1695 (case-fold-search t)
1696 (count (or num 1))
1697 start-list start-this start-type start-label end-type end-label)
1698 (end-of-line) ; probably want this
1699 (while (and (> count 0) (re-search-forward f90-blocks-re nil 'move))
1700 (beginning-of-line)
1701 (skip-chars-forward " \t0-9")
1702 (cond ((or (f90-in-string) (f90-in-comment)))
1703 ((setq start-this
1704 (or
1705 (f90-looking-at-do)
1706 (f90-looking-at-select-case)
1707 (f90-looking-at-type-like)
1708 (f90-looking-at-associate)
1709 (f90-looking-at-critical)
1710 (f90-looking-at-program-block-start)
1711 (f90-looking-at-if-then)
1712 (f90-looking-at-where-or-forall)))
1713 (setq start-list (cons start-this start-list) ; not add-to-list!
1714 count (1+ count)))
1715 ((looking-at (concat "end[ \t]*" f90-blocks-re
1716 "[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)?"))
1717 (setq end-type (match-string 1)
1718 end-label (match-string 2)
1719 count (1- count))
1720 ;; Check any internal blocks.
1721 (when start-list
1722 (setq start-this (car start-list)
1723 start-list (cdr start-list)
1724 start-type (car start-this)
1725 start-label (cadr start-this))
1726 (or (f90-equal-symbols start-type end-type)
1727 (error "End type `%s' does not match start type `%s'"
1728 end-type start-type))
1729 (or (f90-equal-symbols start-label end-label)
1730 (error "End label `%s' does not match start label `%s'"
1731 end-label start-label)))))
1732 (end-of-line))
1733 (if (> count 0) (error "Missing block end"))
1734 ;; Check outermost block.
1735 (when f90-smart-end
1736 (save-excursion
1737 (beginning-of-line)
1738 (skip-chars-forward " \t0-9")
1739 (f90-match-end)))))
1740
1741 (defun f90-beginning-of-block (&optional num)
1742 "Move point backwards to the start of the current code block.
1743 With optional argument NUM, go backward that many balanced blocks.
1744 If NUM is negative, go forward to the end of a block.
1745 Checks for consistency of block types and labels (if present).
1746 Does not check the outermost block, because it may be incomplete.
1747 Interactively, pushes mark before moving point."
1748 (interactive "p")
1749 (if (called-interactively-p 'any) (push-mark (point) t))
1750 (and num (< num 0) (f90-end-of-block (- num)))
1751 (let ((case-fold-search t)
1752 (count (or num 1))
1753 end-list end-this end-type end-label
1754 start-this start-type start-label)
1755 (beginning-of-line) ; probably want this
1756 (while (and (> count 0) (re-search-backward f90-blocks-re nil 'move))
1757 (beginning-of-line)
1758 (skip-chars-forward " \t0-9")
1759 (cond ((or (f90-in-string) (f90-in-comment)))
1760 ((looking-at (concat "end[ \t]*" f90-blocks-re
1761 "[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)?"))
1762 (setq end-list (cons (list (match-string 1) (match-string 2))
1763 end-list)
1764 count (1+ count)))
1765 ((setq start-this
1766 (or
1767 (f90-looking-at-do)
1768 (f90-looking-at-select-case)
1769 (f90-looking-at-type-like)
1770 (f90-looking-at-associate)
1771 (f90-looking-at-critical)
1772 (f90-looking-at-program-block-start)
1773 (f90-looking-at-if-then)
1774 (f90-looking-at-where-or-forall)))
1775 (setq start-type (car start-this)
1776 start-label (cadr start-this)
1777 count (1- count))
1778 ;; Check any internal blocks.
1779 (when end-list
1780 (setq end-this (car end-list)
1781 end-list (cdr end-list)
1782 end-type (car end-this)
1783 end-label (cadr end-this))
1784 (or (f90-equal-symbols start-type end-type)
1785 (error "Start type `%s' does not match end type `%s'"
1786 start-type end-type))
1787 (or (f90-equal-symbols start-label end-label)
1788 (error "Start label `%s' does not match end label `%s'"
1789 start-label end-label))))))
1790 ;; Includes an un-named main program block.
1791 (if (> count 0) (error "Missing block start"))))
1792
1793 (defun f90-next-block (&optional num)
1794 "Move point forward to the next end or start of a code block.
1795 With optional argument NUM, go forward that many blocks.
1796 If NUM is negative, go backwards.
1797 A block is a subroutine, if-endif, etc."
1798 (interactive "p")
1799 (let ((case-fold-search t)
1800 (count (if num (abs num) 1)))
1801 (while (and (> count 0)
1802 (if (> num 0) (re-search-forward f90-blocks-re nil 'move)
1803 (re-search-backward f90-blocks-re nil 'move)))
1804 (beginning-of-line)
1805 (skip-chars-forward " \t0-9")
1806 (cond ((or (f90-in-string) (f90-in-comment)))
1807 ((or
1808 (looking-at "end[ \t]*")
1809 (f90-looking-at-do)
1810 (f90-looking-at-select-case)
1811 (f90-looking-at-type-like)
1812 (f90-looking-at-associate)
1813 (f90-looking-at-critical)
1814 (f90-looking-at-program-block-start)
1815 (f90-looking-at-if-then)
1816 (f90-looking-at-where-or-forall))
1817 (setq count (1- count))))
1818 (if (> num 0) (end-of-line)
1819 (beginning-of-line)))))
1820
1821
1822 (defun f90-previous-block (&optional num)
1823 "Move point backward to the previous end or start of a code block.
1824 With optional argument NUM, go backward that many blocks.
1825 If NUM is negative, go forwards.
1826 A block is a subroutine, if-endif, etc."
1827 (interactive "p")
1828 (f90-next-block (- (or num 1))))
1829
1830
1831 (defun f90-mark-subprogram ()
1832 "Put mark at end of F90 subprogram, point at beginning, push mark."
1833 (interactive)
1834 (let ((pos (point)) program)
1835 (f90-end-of-subprogram)
1836 (push-mark)
1837 (goto-char pos)
1838 (setq program (f90-beginning-of-subprogram))
1839 (if (featurep 'xemacs)
1840 (zmacs-activate-region)
1841 (setq mark-active t
1842 deactivate-mark nil))
1843 program))
1844
1845 (defun f90-comment-region (beg-region end-region)
1846 "Comment/uncomment every line in the region.
1847 Insert the variable `f90-comment-region' at the start of every line
1848 in the region, or, if already present, remove it."
1849 (interactive "*r")
1850 (let ((end (copy-marker end-region)))
1851 (goto-char beg-region)
1852 (beginning-of-line)
1853 (if (looking-at (regexp-quote f90-comment-region))
1854 (delete-region (point) (match-end 0))
1855 (insert f90-comment-region))
1856 (while (and (zerop (forward-line 1))
1857 (< (point) end))
1858 (if (looking-at (regexp-quote f90-comment-region))
1859 (delete-region (point) (match-end 0))
1860 (insert f90-comment-region)))
1861 (set-marker end nil)))
1862
1863 (defun f90-indent-line (&optional no-update)
1864 "Indent current line as F90 code.
1865 Unless optional argument NO-UPDATE is non-nil, call `f90-update-line'
1866 after indenting."
1867 (interactive "*P")
1868 (let ((case-fold-search t)
1869 (pos (point-marker))
1870 indent no-line-number)
1871 (beginning-of-line) ; digits after & \n are not line-nos
1872 (if (not (save-excursion (and (f90-previous-statement)
1873 (f90-line-continued))))
1874 (f90-indent-line-no)
1875 (setq no-line-number t)
1876 (skip-chars-forward " \t"))
1877 ;; FIXME This means f90-calculate-indent gives different answers
1878 ;; for comments and preprocessor lines to this function.
1879 ;; Better to make f90-calculate-indent return the correct answer?
1880 (cond ((looking-at "!") (setq indent (f90-comment-indent)))
1881 ((looking-at "#") (setq indent 0))
1882 (t
1883 (and f90-smart-end (looking-at "end")
1884 (f90-match-end))
1885 (setq indent (f90-calculate-indent))))
1886 (or (= indent (current-column))
1887 (f90-indent-to indent no-line-number))
1888 ;; If initial point was within line's indentation,
1889 ;; position after the indentation. Else stay at same point in text.
1890 (and (< (point) pos)
1891 (goto-char pos))
1892 (if auto-fill-function
1893 ;; GM NO-UPDATE not honored, since this calls f90-update-line.
1894 (f90-do-auto-fill)
1895 (or no-update (f90-update-line)))
1896 (set-marker pos nil)))
1897
1898 (defun f90-indent-new-line ()
1899 "Re-indent current line, insert a newline and indent the newline.
1900 An abbrev before point is expanded if the variable `abbrev-mode' is non-nil.
1901 If run in the middle of a line, the line is not broken."
1902 (interactive "*")
1903 (if abbrev-mode (expand-abbrev))
1904 (beginning-of-line) ; reindent where likely to be needed
1905 (f90-indent-line) ; calls indent-line-no, update-line
1906 (end-of-line)
1907 (delete-horizontal-space) ; destroy trailing whitespace
1908 (let ((string (f90-in-string))
1909 (cont (f90-line-continued)))
1910 (and string (not cont) (insert "&"))
1911 (newline)
1912 (if (or string (and cont f90-beginning-ampersand)) (insert "&")))
1913 (f90-indent-line 'no-update)) ; nothing to update
1914
1915
1916 ;; TODO not add spaces to empty lines at the start.
1917 ;; Why is second line getting extra indent over first?
1918 (defun f90-indent-region (beg-region end-region)
1919 "Indent every line in region by forward parsing."
1920 (interactive "*r")
1921 (let ((end-region-mark (copy-marker end-region))
1922 (save-point (point-marker))
1923 (case-fold-search t)
1924 block-list ind-lev ind-curr ind-b cont struct beg-struct end-struct)
1925 (goto-char beg-region)
1926 ;; First find a line which is not a continuation line or comment.
1927 (beginning-of-line)
1928 (while (and (looking-at "[ \t]*[0-9]*\\(!\\|#\\|[ \t]*$\\)")
1929 (progn (f90-indent-line 'no-update)
1930 (zerop (forward-line 1)))
1931 (< (point) end-region-mark)))
1932 (setq cont (f90-present-statement-cont))
1933 (while (and (memq cont '(middle end))
1934 (f90-previous-statement))
1935 (setq cont (f90-present-statement-cont)))
1936 ;; Process present line for beginning of block.
1937 (setq f90-cache-position (point))
1938 (f90-indent-line 'no-update)
1939 (setq ind-lev (f90-current-indentation)
1940 ind-curr ind-lev)
1941 (beginning-of-line)
1942 (skip-chars-forward " \t0-9")
1943 (setq struct nil
1944 ind-b (cond ((setq struct (f90-looking-at-do)) f90-do-indent)
1945 ((or (setq struct (f90-looking-at-if-then))
1946 (setq struct (f90-looking-at-select-case))
1947 (setq struct (f90-looking-at-where-or-forall))
1948 (looking-at f90-else-like-re))
1949 f90-if-indent)
1950 ((setq struct (f90-looking-at-type-like))
1951 f90-type-indent)
1952 ((setq struct (f90-looking-at-associate))
1953 f90-associate-indent)
1954 ((setq struct (f90-looking-at-critical))
1955 f90-critical-indent)
1956 ((or (setq struct (f90-looking-at-program-block-start))
1957 (looking-at "contains[ \t]*\\($\\|!\\)"))
1958 f90-program-indent)))
1959 (if ind-b (setq ind-lev (+ ind-lev ind-b)))
1960 (if struct (setq block-list (cons struct block-list)))
1961 (while (and (f90-line-continued) (zerop (forward-line 1))
1962 (< (point) end-region-mark))
1963 (if (looking-at "[ \t]*!")
1964 (f90-indent-to (f90-comment-indent))
1965 (or (= (current-indentation)
1966 (+ ind-curr f90-continuation-indent))
1967 (f90-indent-to (+ ind-curr f90-continuation-indent) 'no-line-no))))
1968 ;; Process all following lines.
1969 (while (and (zerop (forward-line 1)) (< (point) end-region-mark))
1970 (beginning-of-line)
1971 (f90-indent-line-no)
1972 (setq f90-cache-position (point))
1973 (cond ((looking-at "[ \t]*$") (setq ind-curr 0))
1974 ((looking-at "[ \t]*#") (setq ind-curr 0))
1975 ((looking-at "!") (setq ind-curr (f90-comment-indent)))
1976 ((f90-no-block-limit) (setq ind-curr ind-lev))
1977 ((looking-at f90-else-like-re) (setq ind-curr
1978 (- ind-lev f90-if-indent)))
1979 ((looking-at "contains[ \t]*\\($\\|!\\)")
1980 (setq ind-curr (- ind-lev f90-program-indent)))
1981 ((setq ind-b
1982 (cond ((setq struct (f90-looking-at-do)) f90-do-indent)
1983 ((or (setq struct (f90-looking-at-if-then))
1984 (setq struct (f90-looking-at-select-case))
1985 (setq struct (f90-looking-at-where-or-forall)))
1986 f90-if-indent)
1987 ((setq struct (f90-looking-at-type-like))
1988 f90-type-indent)
1989 ((setq struct (f90-looking-at-associate))
1990 f90-associate-indent)
1991 ((setq struct (f90-looking-at-critical))
1992 f90-critical-indent)
1993 ((setq struct (f90-looking-at-program-block-start))
1994 f90-program-indent)))
1995 (setq ind-curr ind-lev)
1996 (if ind-b (setq ind-lev (+ ind-lev ind-b)))
1997 (setq block-list (cons struct block-list)))
1998 ((setq end-struct (f90-looking-at-program-block-end))
1999 (setq beg-struct (car block-list)
2000 block-list (cdr block-list))
2001 (if f90-smart-end
2002 (save-excursion
2003 (f90-block-match (car beg-struct) (cadr beg-struct)
2004 (car end-struct) (cadr end-struct))))
2005 (setq ind-b
2006 (cond ((looking-at f90-end-if-re) f90-if-indent)
2007 ((looking-at "end[ \t]*do\\_>") f90-do-indent)
2008 ((looking-at f90-end-type-re) f90-type-indent)
2009 ((looking-at f90-end-associate-re)
2010 f90-associate-indent)
2011 ((f90-looking-at-end-critical) f90-critical-indent)
2012 ((f90-looking-at-program-block-end)
2013 f90-program-indent)))
2014 (if ind-b (setq ind-lev (- ind-lev ind-b)))
2015 (setq ind-curr ind-lev))
2016 (t (setq ind-curr ind-lev)))
2017 ;; Do the indentation if necessary.
2018 (or (= ind-curr (current-column))
2019 (f90-indent-to ind-curr))
2020 (while (and (f90-line-continued) (zerop (forward-line 1))
2021 (< (point) end-region-mark))
2022 (cond ((looking-at "[ \t]*#") (f90-indent-to 0))
2023 ((looking-at "[ \t]*!") (f90-indent-to (f90-comment-indent)))
2024 (t
2025 (or (= (current-indentation)
2026 (+ ind-curr f90-continuation-indent))
2027 (f90-indent-to
2028 (+ ind-curr f90-continuation-indent) 'no-line-no))))))
2029 ;; Restore point, etc.
2030 (setq f90-cache-position nil)
2031 (goto-char save-point)
2032 (set-marker end-region-mark nil)
2033 (set-marker save-point nil)
2034 (if (featurep 'xemacs)
2035 (zmacs-deactivate-region)
2036 (deactivate-mark))))
2037
2038 (defun f90-indent-subprogram ()
2039 "Properly indent the subprogram containing point."
2040 (interactive "*")
2041 (save-excursion
2042 (let ((program (f90-mark-subprogram)))
2043 (if program
2044 (progn
2045 (message "Indenting %s %s..."
2046 (car program) (cadr program))
2047 (indent-region (point) (mark) nil)
2048 (message "Indenting %s %s...done"
2049 (car program) (cadr program)))
2050 (message "Indenting the whole file...")
2051 (indent-region (point) (mark) nil)
2052 (message "Indenting the whole file...done")))))
2053
2054 (defun f90-break-line (&optional no-update)
2055 "Break line at point, insert continuation marker(s) and indent.
2056 Unless in a string or comment, or if the optional argument NO-UPDATE
2057 is non-nil, call `f90-update-line' after inserting the continuation marker."
2058 (interactive "*P")
2059 (cond ((f90-in-string)
2060 (insert "&\n&"))
2061 ((f90-in-comment)
2062 (delete-horizontal-space) ; remove trailing whitespace
2063 (insert "\n" (f90-get-present-comment-type)))
2064 (t (insert "&")
2065 (or no-update (f90-update-line))
2066 (newline 1)
2067 ;; FIXME also need leading ampersand if split lexical token (eg ==).
2068 ;; Or respect f90-no-break-re.
2069 (if f90-beginning-ampersand (insert "&"))))
2070 (indent-according-to-mode))
2071
2072 (defun f90-find-breakpoint ()
2073 "From `fill-column', search backward for break-delimiter."
2074 ;; Commented text more likely than commented code.
2075 (if (f90-in-comment)
2076 (re-search-backward "\\s-" (line-beginning-position))
2077 (re-search-backward f90-break-delimiters (line-beginning-position))
2078 (if (not f90-break-before-delimiters)
2079 (forward-char (if (looking-at f90-no-break-re) 2 1))
2080 (backward-char)
2081 (or (looking-at f90-no-break-re)
2082 (forward-char)))))
2083
2084 (defun f90-do-auto-fill ()
2085 "Break line if non-white characters beyond `fill-column'.
2086 Update keyword case first."
2087 (interactive "*")
2088 ;; Break line before or after last delimiter (non-word char) if
2089 ;; position is beyond fill-column.
2090 ;; Will not break **, //, or => (as specified by f90-no-break-re).
2091 (f90-update-line)
2092 ;; Need this for `f90-electric-insert' and other f90- callers.
2093 (unless (and (boundp 'comment-auto-fill-only-comments)
2094 comment-auto-fill-only-comments
2095 (not (f90-in-comment)))
2096 (while (> (current-column) fill-column)
2097 (let ((pos-mark (point-marker)))
2098 (move-to-column fill-column)
2099 (or (f90-in-string) (f90-find-breakpoint))
2100 (f90-break-line)
2101 (goto-char pos-mark)
2102 (set-marker pos-mark nil)))))
2103
2104 (defun f90-join-lines (&optional arg)
2105 "Join current line to previous, fix whitespace, continuation, comments.
2106 With optional argument ARG, join current line to following line.
2107 Like `join-line', but handles F90 syntax."
2108 (interactive "*P")
2109 (beginning-of-line)
2110 (if arg (forward-line 1))
2111 (when (eq (preceding-char) ?\n)
2112 (skip-chars-forward " \t")
2113 (if (looking-at "&") (delete-char 1))
2114 (beginning-of-line)
2115 (delete-region (point) (1- (point)))
2116 (skip-chars-backward " \t")
2117 (and (eq (preceding-char) ?&) (delete-char -1))
2118 (and (f90-in-comment)
2119 (looking-at "[ \t]*!+")
2120 (replace-match ""))
2121 (or (f90-in-string)
2122 (fixup-whitespace))))
2123
2124 (defun f90-fill-region (beg-region end-region)
2125 "Fill every line in region by forward parsing. Join lines if possible."
2126 (interactive "*r")
2127 (let ((end-region-mark (copy-marker end-region))
2128 (go-on t)
2129 f90-smart-end f90-auto-keyword-case auto-fill-function)
2130 (goto-char beg-region)
2131 (while go-on
2132 ;; Join as much as possible.
2133 (while (progn
2134 (end-of-line)
2135 (skip-chars-backward " \t")
2136 (eq (preceding-char) ?&))
2137 (f90-join-lines 'forward))
2138 ;; Chop the line if necessary.
2139 (while (> (save-excursion (end-of-line) (current-column))
2140 fill-column)
2141 (move-to-column fill-column)
2142 (f90-find-breakpoint)
2143 (f90-break-line 'no-update))
2144 (setq go-on (and (< (point) end-region-mark)
2145 (zerop (forward-line 1)))
2146 f90-cache-position (point)))
2147 (setq f90-cache-position nil)
2148 (set-marker end-region-mark nil)
2149 (if (featurep 'xemacs)
2150 (zmacs-deactivate-region)
2151 (deactivate-mark))))
2152 \f
2153 (defconst f90-end-block-optional-name
2154 '("program" "module" "subroutine" "function" "type")
2155 "Block types where including the name in the end statement is optional.")
2156
2157 (defun f90-block-match (beg-block beg-name end-block end-name)
2158 "Match end-struct with beg-struct and complete end-block if possible.
2159 BEG-BLOCK is the type of block as indicated at the start (e.g., do).
2160 BEG-NAME is the block start name (may be nil).
2161 END-BLOCK is the type of block as indicated at the end (may be nil).
2162 END-NAME is the block end name (may be nil).
2163 If the block type matches `f90-end-block-optional-name', do not add
2164 an end name if `f90-smart-end-names' is nil, but always update an
2165 incorrect end name if there already was one.
2166 Leave point at the end of line."
2167 ;; Hack to deal with the case when this is called from
2168 ;; f90-indent-region on a program block without an explicit PROGRAM
2169 ;; statement at the start. Should really be an error (?).
2170 (or beg-block (setq beg-block "program"))
2171 (search-forward "end" (line-end-position))
2172 (catch 'no-match
2173 (if (and end-block (f90-equal-symbols beg-block end-block))
2174 (search-forward end-block)
2175 (if end-block
2176 (progn
2177 (message "END %s does not match %s." end-block beg-block)
2178 (end-of-line)
2179 (throw 'no-match nil))
2180 (message "Inserting %s." beg-block)
2181 (insert (concat " " beg-block))))
2182 (if (f90-equal-symbols beg-name end-name)
2183 (and end-name (search-forward end-name))
2184 (cond ((and beg-name (not end-name))
2185 (unless (and (not f90-smart-end-names)
2186 (member-ignore-case beg-block
2187 f90-end-block-optional-name))
2188 (message "Inserting %s." beg-name)
2189 (insert (concat " " beg-name))))
2190 ((and beg-name end-name)
2191 (message "Replacing %s with %s." end-name beg-name)
2192 (search-forward end-name)
2193 (replace-match beg-name))
2194 ((and (not beg-name) end-name)
2195 (message "Deleting %s." end-name)
2196 (search-forward end-name)
2197 (replace-match ""))))
2198 (or (looking-at "[ \t]*!") (delete-horizontal-space))))
2199
2200 (defun f90-match-end ()
2201 "From an end block statement, find the corresponding block and name."
2202 (interactive)
2203 (let ((count 1)
2204 (top-of-window (window-start))
2205 (end-point (point))
2206 (case-fold-search t)
2207 matching-beg beg-name end-name beg-block end-block end-struct)
2208 ;; Check if in string in case using non-standard feature where
2209 ;; continued strings do not need "&" at start of continuations.
2210 (when (save-excursion (beginning-of-line) (skip-chars-forward " \t0-9")
2211 (unless (f90-in-string)
2212 (setq end-struct
2213 (f90-looking-at-program-block-end))))
2214 (setq end-block (car end-struct)
2215 end-name (cadr end-struct))
2216 (save-excursion
2217 (beginning-of-line)
2218 (while (and (> count 0)
2219 (not (= (line-beginning-position) (point-min))))
2220 (re-search-backward f90-blocks-re nil 'move)
2221 (beginning-of-line)
2222 ;; GM not a line number if continued line.
2223 ;;; (skip-chars-forward " \t")
2224 ;;; (skip-chars-forward "0-9")
2225 (skip-chars-forward " \t0-9")
2226 (cond ((or (f90-in-string) (f90-in-comment)))
2227 ((setq matching-beg
2228 (or
2229 (f90-looking-at-do)
2230 (f90-looking-at-if-then)
2231 (f90-looking-at-where-or-forall)
2232 (f90-looking-at-select-case)
2233 (f90-looking-at-type-like)
2234 (f90-looking-at-associate)
2235 (f90-looking-at-critical)
2236 (f90-looking-at-program-block-start)
2237 ;; Interpret a single END without a block
2238 ;; start to be the END of a program block
2239 ;; without an initial PROGRAM line.
2240 (if (= (line-beginning-position) (point-min))
2241 '("program" nil))))
2242 (setq count (1- count)))
2243 ((looking-at (concat "end[ \t]*" f90-blocks-re))
2244 (setq count (1+ count)))))
2245 (if (> count 0)
2246 (message "No matching beginning.")
2247 (f90-update-line)
2248 (if (eq f90-smart-end 'blink)
2249 (if (< (point) top-of-window)
2250 (message "Matches %s: %s"
2251 (what-line)
2252 (buffer-substring
2253 (line-beginning-position)
2254 (line-end-position)))
2255 (sit-for blink-matching-delay)))
2256 (setq beg-block (car matching-beg)
2257 beg-name (cadr matching-beg))
2258 (goto-char end-point)
2259 (beginning-of-line)
2260 (f90-block-match beg-block beg-name end-block end-name))))))
2261
2262 (defun f90-insert-end ()
2263 "Insert a complete end statement matching beginning of present block."
2264 (interactive "*")
2265 (let ((f90-smart-end (or f90-smart-end 'blink)))
2266 (insert "end")
2267 (f90-indent-new-line)))
2268 \f
2269 ;; Abbrevs and keywords.
2270
2271 (defun f90-abbrev-start ()
2272 "Typing \\=`\\[help-command] or \\=`? lists all the F90 abbrevs.
2273 Any other key combination is executed normally."
2274 (interactive "*")
2275 (self-insert-command 1)
2276 (when abbrev-mode
2277 (set-transient-map
2278 (let ((map (make-sparse-keymap)))
2279 (define-key map [??] 'f90-abbrev-help)
2280 (define-key map (vector help-char) 'f90-abbrev-help)
2281 map))))
2282
2283 (defun f90-abbrev-help ()
2284 "List the currently defined abbrevs in F90 mode."
2285 (interactive)
2286 (message "Listing abbrev table...")
2287 (display-buffer (f90-prepare-abbrev-list-buffer))
2288 (message "Listing abbrev table...done"))
2289
2290 (defun f90-prepare-abbrev-list-buffer ()
2291 "Create a buffer listing the F90 mode abbreviations."
2292 (with-current-buffer (get-buffer-create "*Abbrevs*")
2293 (erase-buffer)
2294 (insert-abbrev-table-description 'f90-mode-abbrev-table t)
2295 (goto-char (point-min))
2296 (set-buffer-modified-p nil)
2297 (edit-abbrevs-mode))
2298 (get-buffer-create "*Abbrevs*"))
2299
2300 (defun f90-upcase-keywords ()
2301 "Upcase all F90 keywords in the buffer."
2302 (interactive "*")
2303 (f90-change-keywords 'upcase-word))
2304
2305 (defun f90-capitalize-keywords ()
2306 "Capitalize all F90 keywords in the buffer."
2307 (interactive "*")
2308 (f90-change-keywords 'capitalize-word))
2309
2310 (defun f90-downcase-keywords ()
2311 "Downcase all F90 keywords in the buffer."
2312 (interactive "*")
2313 (f90-change-keywords 'downcase-word))
2314
2315 (defun f90-upcase-region-keywords (beg end)
2316 "Upcase all F90 keywords in the region."
2317 (interactive "*r")
2318 (f90-change-keywords 'upcase-word beg end))
2319
2320 (defun f90-capitalize-region-keywords (beg end)
2321 "Capitalize all F90 keywords in the region."
2322 (interactive "*r")
2323 (f90-change-keywords 'capitalize-word beg end))
2324
2325 (defun f90-downcase-region-keywords (beg end)
2326 "Downcase all F90 keywords in the region."
2327 (interactive "*r")
2328 (f90-change-keywords 'downcase-word beg end))
2329
2330 ;; Change the keywords according to argument.
2331 (defun f90-change-keywords (change-word &optional beg end)
2332 "Change the case of F90 keywords in the region (if specified) or buffer.
2333 CHANGE-WORD should be one of `upcase-word', `downcase-word', `capitalize-word'."
2334 (save-excursion
2335 (setq beg (or beg (point-min))
2336 end (or end (point-max)))
2337 (let ((keyword-re
2338 (concat "\\("
2339 f90-keywords-re "\\|" f90-procedures-re "\\|"
2340 f90-hpf-keywords-re "\\|" f90-operators-re "\\)"))
2341 (ref-point (point-min))
2342 (modified (buffer-modified-p))
2343 state saveword back-point)
2344 (goto-char beg)
2345 (unwind-protect
2346 (while (re-search-forward keyword-re end t)
2347 (unless (progn
2348 (setq state (parse-partial-sexp ref-point (point)))
2349 (or (nth 3 state) (nth 4 state)
2350 ;; GM f90-directive-comment-re?
2351 (save-excursion ; check for cpp directive
2352 (beginning-of-line)
2353 (skip-chars-forward " \t0-9")
2354 (looking-at "#"))))
2355 (setq ref-point (point)
2356 ;; FIXME this does not work for constructs with
2357 ;; embedded space, eg "sync all".
2358 back-point (save-excursion (backward-word-strictly 1)
2359 (point))
2360 saveword (buffer-substring back-point ref-point))
2361 (funcall change-word -1)
2362 (or (string= saveword (buffer-substring back-point ref-point))
2363 (setq modified t))))
2364 (or modified (restore-buffer-modified-p nil))))))
2365
2366
2367 (defun f90-current-defun ()
2368 "Function to use for `add-log-current-defun-function' in F90 mode."
2369 (save-excursion
2370 (nth 1 (f90-beginning-of-subprogram))))
2371
2372 (defun f90-backslash-not-special (&optional all)
2373 "Make the backslash character (\\) be non-special in the current buffer.
2374 With optional argument ALL, change the default for all present
2375 and future F90 buffers. F90 mode normally treats backslash as an
2376 escape character."
2377 (or (derived-mode-p 'f90-mode)
2378 (user-error "This function should only be used in F90 buffers"))
2379 (when (equal (char-syntax ?\\ ) ?\\ )
2380 (or all (set-syntax-table (copy-syntax-table (syntax-table))))
2381 (modify-syntax-entry ?\\ ".")))
2382
2383
2384 (provide 'f90)
2385
2386 ;;; f90.el ends here