home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / modes / pascal.el < prev    next >
Encoding:
Text File  |  1995-03-25  |  52.3 KB  |  1,524 lines

  1. ;;; pascal.el  -  Major mode for editing pascal source in emacs.
  2.  
  3. ;;; Copyright (C) 1993, 1994 Free Software Foundation, Inc.
  4.  
  5. ;;; Author: Espen Skoglund (espensk@stud.cs.uit.no)
  6. ;;; Keywords: languages
  7.  
  8. ;; This file is part of XEmacs.
  9.  
  10. ;; XEmacs is free software; you can redistribute it and/or modify it
  11. ;; under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation; either version 2, or (at your option)
  13. ;; any later version.
  14.  
  15. ;; XEmacs is distributed in the hope that it will be useful, but
  16. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  18. ;; General Public License for more details.
  19.  
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with XEmacs; see the file COPYING.  If not, write to the Free
  22. ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  23.  
  24. ;;; Commentary:
  25.  
  26. ;;; USAGE
  27. ;;; =====
  28.  
  29. ;;; Emacs should enter Pascal mode when you find a Pascal source file.
  30. ;;; When you have entered Pascal mode, you may get more info by pressing
  31. ;;; C-h m. You may also get online help describing various functions by:
  32. ;;; C-h f <Name of function you want described>
  33.  
  34. ;;; If you want to customize Pascal mode to fit you better, you may add
  35. ;;; these lines (the values of the variables presented here are the defaults):
  36. ;;;
  37. ;;; ;; User customization for Pascal mode
  38. ;;; (setq pascal-indent-level       3
  39. ;;;       pascal-case-indent        2
  40. ;;;       pascal-auto-newline       nil
  41. ;;;       pascal-tab-always-indent  t
  42. ;;;       pascal-auto-endcomments   t
  43. ;;;       pascal-auto-lineup        '(all)
  44. ;;;       pascal-toggle-completions nil
  45. ;;;       pascal-type-keywords      '("array" "file" "packed" "char" 
  46. ;;;                       "integer" "real" "string" "record")
  47. ;;;       pascal-start-keywords     '("begin" "end" "function" "procedure"
  48. ;;;                       "repeat" "until" "while" "read" "readln"
  49. ;;;                       "reset" "rewrite" "write" "writeln")
  50. ;;;       pascal-separator-keywords '("downto" "else" "mod" "div" "then"))
  51.  
  52. ;;; KNOWN BUGS / BUGREPORTS
  53. ;;; =======================
  54. ;;; As far as I know, there are no bugs in the current version of this
  55. ;;; package.  This may not be true however, since I never use this mode
  56. ;;; myself and therefore would never notice them anyway.   If you do
  57. ;;; find any bugs, you may submit them to: espensk@stud.cs.uit.no
  58. ;;; as well as to bug-gnu-emacs@prep.ai.mit.edu.
  59.  
  60. ;;; Code:
  61.  
  62. (defconst pascal-mode-version "2.4"
  63.   "Version of `pascal.el'.")
  64.  
  65. (defvar pascal-mode-abbrev-table nil
  66.   "Abbrev table in use in Pascal-mode buffers.")
  67. (define-abbrev-table 'pascal-mode-abbrev-table ())
  68.  
  69. (defvar pascal-mode-map ()
  70.   "Keymap used in Pascal mode.")
  71. (if pascal-mode-map
  72.     ()
  73.   (setq pascal-mode-map (make-sparse-keymap))
  74.   (define-key pascal-mode-map ";"        'electric-pascal-semi-or-dot)
  75.   (define-key pascal-mode-map "."        'electric-pascal-semi-or-dot)
  76.   (define-key pascal-mode-map ":"        'electric-pascal-colon)
  77.   (define-key pascal-mode-map "="        'electric-pascal-equal)
  78.   (define-key pascal-mode-map "#"        'electric-pascal-hash)
  79.   (define-key pascal-mode-map "\r"       'electric-pascal-terminate-line)
  80.   (define-key pascal-mode-map "\t"       'electric-pascal-tab)
  81.   (define-key pascal-mode-map "\M-\t"    'pascal-complete-word)
  82.   (define-key pascal-mode-map "\M-?"     'pascal-show-completions)
  83.   (define-key pascal-mode-map "\177"     'backward-delete-char-untabify)
  84.   (define-key pascal-mode-map "\M-\C-h"  'pascal-mark-defun)
  85.   (define-key pascal-mode-map "\C-c\C-b" 'pascal-insert-block)
  86.   (define-key pascal-mode-map "\M-*"     'pascal-star-comment)
  87.   (define-key pascal-mode-map "\C-c\C-c" 'pascal-comment-area)
  88.   (define-key pascal-mode-map "\C-c\C-u" 'pascal-uncomment-area)
  89.   (define-key pascal-mode-map "\M-\C-a"  'pascal-beg-of-defun)
  90.   (define-key pascal-mode-map "\M-\C-e"  'pascal-end-of-defun)
  91.   (define-key pascal-mode-map "\C-c\C-d" 'pascal-goto-defun)
  92.   (define-key pascal-mode-map "\C-c\C-o" 'pascal-outline)
  93. ;;; A command to change the whole buffer won't be used terribly
  94. ;;; often, so no need for a key binding.
  95. ;  (define-key pascal-mode-map "\C-cd"    'pascal-downcase-keywords)
  96. ;  (define-key pascal-mode-map "\C-cu"    'pascal-upcase-keywords)
  97. ;  (define-key pascal-mode-map "\C-cc"    'pascal-capitalize-keywords)
  98.   )
  99.   
  100. (defvar pascal-keywords
  101.   '("and" "array" "begin" "case" "const" "div" "do" "downto" "else" "end" 
  102.     "file" "for" "function" "goto" "if" "in" "label" "mod" "nil" "not" "of" 
  103.     "or" "packed" "procedure" "program" "record" "repeat" "set" "then" "to" 
  104.     "type" "until" "var" "while" "with"
  105.     ;; The following are not standard in pascal, but widely used.
  106.     "get" "put" "input" "output" "read" "readln" "reset" "rewrite" "write"
  107.     "writeln"))
  108.  
  109. ;;;
  110. ;;; Regular expressions used to calculate indent, etc.
  111. ;;;
  112. (defconst pascal-symbol-re      "\\<[a-zA-Z_][a-zA-Z_0-9.]*\\>")
  113. (defconst pascal-beg-block-re   "\\<\\(begin\\|case\\|record\\|repeat\\)\\>")
  114. (defconst pascal-end-block-re   "\\<\\(end\\|until\\)\\>")
  115. (defconst pascal-declaration-re "\\<\\(const\\|label\\|type\\|var\\)\\>")
  116. (defconst pascal-defun-re       "\\<\\(function\\|procedure\\|program\\)\\>")
  117. (defconst pascal-sub-block-re   "\\<\\(if\\|else\\|for\\|while\\|with\\)\\>")
  118. (defconst pascal-noindent-re    "\\<\\(begin\\|end\\|until\\|else\\)\\>")
  119. (defconst pascal-nosemi-re      "\\<\\(begin\\|repeat\\|then\\|do\\|else\\)\\>")
  120. (defconst pascal-autoindent-lines-re
  121.   "\\<\\(label\\|var\\|type\\|const\\|until\\|end\\|begin\\|repeat\\|else\\)\\>")
  122.  
  123. ;;; Strings used to mark beginning and end of excluded text
  124. (defconst pascal-exclude-str-start "{-----\\/----- EXCLUDED -----\\/-----")
  125. (defconst pascal-exclude-str-end " -----/\\----- EXCLUDED -----/\\-----}")
  126.  
  127. (defvar pascal-mode-syntax-table nil
  128.   "Syntax table in use in Pascal-mode buffers.")
  129.  
  130. (if pascal-mode-syntax-table
  131.     ()
  132.   (setq pascal-mode-syntax-table (make-syntax-table))
  133.   (modify-syntax-entry ?\\ "\\"  pascal-mode-syntax-table)
  134.   (modify-syntax-entry ?( "()1"  pascal-mode-syntax-table)  
  135.   (modify-syntax-entry ?) ")(4"  pascal-mode-syntax-table)
  136.   (modify-syntax-entry ?* ". 23" pascal-mode-syntax-table)
  137.   (modify-syntax-entry ?{ "<"    pascal-mode-syntax-table)
  138.   (modify-syntax-entry ?} ">"    pascal-mode-syntax-table)
  139.   (modify-syntax-entry ?+ "."    pascal-mode-syntax-table)
  140.   (modify-syntax-entry ?- "."    pascal-mode-syntax-table)
  141.   (modify-syntax-entry ?= "."    pascal-mode-syntax-table)
  142.   (modify-syntax-entry ?% "."    pascal-mode-syntax-table)
  143.   (modify-syntax-entry ?< "."    pascal-mode-syntax-table)
  144.   (modify-syntax-entry ?> "."    pascal-mode-syntax-table)
  145.   (modify-syntax-entry ?& "."    pascal-mode-syntax-table)
  146.   (modify-syntax-entry ?| "."    pascal-mode-syntax-table)
  147.   (modify-syntax-entry ?_ "w"    pascal-mode-syntax-table)
  148.   (modify-syntax-entry ?\' "\""  pascal-mode-syntax-table))
  149.  
  150. ;; XEmacs - moved pascal-font-lock-keywords to packages/font-lock.el
  151.  
  152. (defvar pascal-indent-level 3
  153.   "*Indentation of Pascal statements with respect to containing block.")
  154.  
  155. (defvar pascal-case-indent 2
  156.   "*Indentation for case statements.")
  157.  
  158. (defvar pascal-auto-newline nil
  159.   "*Non-nil means automatically newline after simcolons and the punctation mark
  160. after an end.")
  161.  
  162. (defvar pascal-tab-always-indent t
  163.   "*Non-nil means TAB in Pascal mode should always reindent the current line,
  164. regardless of where in the line point is when the TAB command is used.")
  165.  
  166. (defvar pascal-auto-endcomments t
  167.   "*Non-nil means a comment { ... } is set after the ends which ends cases and
  168. functions. The name of the function or case will be set between the braces.")
  169.  
  170. (defvar pascal-auto-lineup '(all)
  171.   "*List of contexts where auto lineup of :'s or ='s should be done.
  172. Elements can be of type: 'paramlist', 'declaration' or 'case', which will
  173. do auto lineup in parameterlist, declarations or case-statements
  174. respectively. The word 'all' will do all lineups. '(case paramlist) for
  175. instance will do lineup in case-statements and parameterlist, while '(all)
  176. will do all lineups.")
  177.  
  178. (defvar pascal-toggle-completions nil
  179.   "*Non-nil means that \\<pascal-mode-map>\\[pascal-complete-label] should \
  180. not display a completion buffer when
  181. the label couldn't be completed, but instead toggle the possible completions
  182. with repeated \\[pascal-complete-label]'s.")
  183.  
  184. (defvar pascal-type-keywords
  185.   '("array" "file" "packed" "char" "integer" "real" "string" "record")
  186.   "*Keywords for types used when completing a word in a declaration or parmlist.
  187. \(eg. integer, real, char.)  The types defined within the Pascal program
  188. will be completed runtime, and should not be added to this list.")
  189.  
  190. (defvar pascal-start-keywords
  191.   '("begin" "end" "function" "procedure" "repeat" "until" "while"
  192.     "read" "readln" "reset" "rewrite" "write" "writeln")
  193.   "*Keywords to complete when standing at the first word of a statement.
  194. \(eg. begin, repeat, until, readln.)
  195. The procedures and variables defined within the Pascal program
  196. will be completed runtime and should not be added to this list.")
  197.  
  198. (defvar pascal-separator-keywords
  199.   '("downto" "else" "mod" "div" "then")
  200.   "*Keywords to complete when NOT standing at the first word of a statement.
  201. \(eg. downto, else, mod, then.) 
  202. Variables and function names defined within the
  203. Pascal program are completed runtime and should not be added to this list.")
  204.  
  205. ;;;
  206. ;;;  Macros
  207. ;;;
  208.  
  209. (defsubst pascal-get-beg-of-line (&optional arg)
  210.   (save-excursion
  211.     (beginning-of-line arg)
  212.     (point)))
  213.  
  214. (defsubst pascal-get-end-of-line (&optional arg)
  215.   (save-excursion
  216.     (end-of-line arg)
  217.     (point)))
  218.  
  219. (defun pascal-declaration-end ()
  220.   (let ((nest 1))
  221.     (while (and (> nest 0)
  222.         (re-search-forward 
  223.          "[:=]\\|\\(\\<record\\>\\)\\|\\(\\<end\\>\\)" 
  224.          (save-excursion (end-of-line 2) (point)) t))
  225.       (cond ((match-beginning 1) (setq nest (1+ nest)))
  226.         ((match-beginning 2) (setq nest (1- nest)))))))
  227.  
  228.  
  229. (defun pascal-declaration-beg ()
  230.   (let ((nest 1))
  231.     (while (and (> nest 0)
  232.         (re-search-backward "[:=]\\|\\<\\(type\\|var\\|label\\|const\\)\\>\\|\\(\\<record\\>\\)\\|\\(\\<end\\>\\)" (pascal-get-beg-of-line 0) t))
  233.       (cond ((match-beginning 1) (setq nest 0))
  234.         ((match-beginning 2) (setq nest (1- nest)))
  235.         ((match-beginning 3) (setq nest (1+ nest)))))
  236.     (= nest 0)))
  237.  
  238.   
  239. (defsubst pascal-within-string ()
  240.   (save-excursion
  241.     (nth 3 (parse-partial-sexp (pascal-get-beg-of-line) (point)))))
  242.  
  243.  
  244. ;;;###autoload
  245. (defun pascal-mode ()
  246.   "Major mode for editing Pascal code. \\<pascal-mode-map>
  247. TAB indents for Pascal code.  Delete converts tabs to spaces as it moves back.
  248.  
  249. \\[pascal-complete-word] completes the word around current point with respect \
  250. to position in code
  251. \\[pascal-show-completions] shows all possible completions at this point.
  252.  
  253. Other useful functions are:
  254.  
  255. \\[pascal-mark-defun]\t- Mark function.
  256. \\[pascal-insert-block]\t- insert begin ... end;
  257. \\[pascal-star-comment]\t- insert (* ... *)
  258. \\[pascal-comment-area]\t- Put marked area in a comment, fixing nested comments.
  259. \\[pascal-uncomment-area]\t- Uncomment an area commented with \
  260. \\[pascal-comment-area].
  261. \\[pascal-beg-of-defun]\t- Move to beginning of current function.
  262. \\[pascal-end-of-defun]\t- Move to end of current function.
  263. \\[pascal-goto-defun]\t- Goto function prompted for in the minibuffer.
  264. \\[pascal-outline]\t- Enter pascal-outline-mode (see also pascal-outline).
  265.  
  266. Variables controlling indentation/edit style:
  267.  
  268.  pascal-indent-level      (default 3)
  269.     Indentation of Pascal statements with respect to containing block.
  270.  pascal-case-indent       (default 2)
  271.     Indentation for case statements.
  272.  pascal-auto-newline      (default nil)
  273.     Non-nil means automatically newline after simcolons and the punctation mark
  274.     after an end.
  275.  pascal-tab-always-indent (default t)
  276.     Non-nil means TAB in Pascal mode should always reindent the current line,
  277.     regardless of where in the line point is when the TAB command is used.
  278.  pascal-auto-endcomments  (default t)
  279.     Non-nil means a comment { ... } is set after the ends which ends cases and
  280.     functions. The name of the function or case will be set between the braces.
  281.  pascal-auto-lineup       (default t)
  282.     List of contexts where auto lineup of :'s or ='s hould be done.
  283.  
  284. See also the user variables pascal-type-keywords, pascal-start-keywords and
  285. pascal-separator-keywords.
  286.  
  287. Turning on Pascal mode calls the value of the variable pascal-mode-hook with
  288. no args, if that value is non-nil."
  289.   (interactive)
  290.   (kill-all-local-variables)
  291.   (use-local-map pascal-mode-map)
  292.   (setq major-mode 'pascal-mode)
  293.   (setq mode-name "Pascal")
  294.   (setq local-abbrev-table pascal-mode-abbrev-table)
  295.   (set-syntax-table pascal-mode-syntax-table)
  296.   (make-local-variable 'indent-line-function)
  297.   (setq indent-line-function 'pascal-indent-line)
  298.   (setq comment-indent-function 'pascal-indent-comment)
  299.   (make-local-variable 'parse-sexp-ignore-comments)
  300.   (setq parse-sexp-ignore-comments nil)
  301.   (make-local-variable 'case-fold-search)
  302.   (setq case-fold-search t)
  303.   (make-local-variable 'comment-start-skip)
  304.   (setq comment-start-skip "(\\*+ *\\|{ *")
  305.   (make-local-variable 'comment-end)
  306.   (setq comment-end "}")
  307.   ;; XEmacs - font-lock now takes care of this
  308.   ;;  (make-local-variable 'font-lock-defaults)
  309.   ;;  (setq font-lock-defaults '(pascal-font-lock-keywords nil t))
  310.   (run-hooks 'pascal-mode-hook))
  311.  
  312.  
  313.  
  314. ;;;
  315. ;;;  Electric functions
  316. ;;;
  317. (defun electric-pascal-terminate-line ()
  318.   "Terminate line and indent next line."
  319.   (interactive)
  320.   ;; First, check if current line should be indented
  321.   (save-excursion
  322.     (beginning-of-line)
  323.     (skip-chars-forward " \t")
  324.     (if (looking-at pascal-autoindent-lines-re)
  325.     (pascal-indent-line)))
  326.   (delete-horizontal-space) ; Removes trailing whitespaces
  327.   (newline)
  328.   ;; Indent next line
  329.   (pascal-indent-line)
  330.   ;; Maybe we should set some endcomments
  331.   (if pascal-auto-endcomments
  332.       (pascal-set-auto-comments))
  333.   ;; Check if we shall indent inside comment
  334.   (let ((setstar nil))
  335.     (save-excursion
  336.       (forward-line -1)
  337.       (skip-chars-forward " \t")
  338.       (cond ((looking-at "\\*[ \t]+)")
  339.          ;; Delete region between `*' and `)' if there is only whitespaces.
  340.          (forward-char 1)
  341.          (delete-horizontal-space))
  342.         ((and (looking-at "(\\*\\|\\*[^)]")
  343.           (not (save-excursion
  344.              (search-forward "*)" (pascal-get-end-of-line) t))))
  345.          (setq setstar t))))
  346.     ;; If last line was a star comment line then this one shall be too.
  347.     (if (null setstar)    
  348.     (pascal-indent-line)
  349.       (insert "*  "))))
  350.  
  351.  
  352. (defun electric-pascal-semi-or-dot ()
  353.   "Insert `;' or `.' character and reindent the line."
  354.   (interactive)
  355.   (insert last-command-char)
  356.   (save-excursion
  357.     (beginning-of-line)
  358.     (pascal-indent-line))
  359.   (if pascal-auto-newline
  360.       (electric-pascal-terminate-line)))
  361.  
  362. (defun electric-pascal-colon ()
  363.   "Insert `:' and do all indentions except line indent on this line."
  364.   (interactive)
  365.   (insert last-command-char)
  366.   ;; Do nothing if within string.
  367.   (if (pascal-within-string)
  368.       ()
  369.     (save-excursion
  370.       (beginning-of-line)
  371.       (pascal-indent-line))
  372.     (let ((pascal-tab-always-indent nil))
  373.       (pascal-indent-command))))
  374.  
  375. (defun electric-pascal-equal ()
  376.   "Insert `=', and do indention if within type declaration."
  377.   (interactive)
  378.   (insert last-command-char)
  379.   (if (eq (car (pascal-calculate-indent)) 'declaration)
  380.       (let ((pascal-tab-always-indent nil))
  381.     (pascal-indent-command))))
  382.  
  383. (defun electric-pascal-hash ()
  384.   "Insert `#', and indent to coulmn 0 if this is a CPP directive."
  385.   (interactive)
  386.   (insert last-command-char)
  387.   (if (save-excursion (beginning-of-line) (looking-at "^[ \t]*#"))
  388.       (save-excursion (beginning-of-line)
  389.               (delete-horizontal-space))))
  390.  
  391. (defun electric-pascal-tab ()
  392.   "Function called when TAB is pressed in Pascal mode."
  393.   (interactive)
  394.   ;; Do nothing if within a string or in a CPP directive.
  395.   (if (or (pascal-within-string)
  396.       (and (not (bolp))
  397.            (save-excursion (beginning-of-line) (eq (following-char) ?#))))
  398.       (insert "\t")
  399.     ;; If pascal-tab-always-indent, indent the beginning of the line.
  400.     (if pascal-tab-always-indent
  401.     (save-excursion
  402.       (beginning-of-line)
  403.       (pascal-indent-line))
  404.       (insert "\t"))
  405.     (pascal-indent-command)))
  406.  
  407.  
  408.  
  409. ;;;
  410. ;;; Interactive functions
  411. ;;;
  412. (defun pascal-insert-block ()
  413.   "Insert Pascal begin ... end; block in the code with right indentation."
  414.   (interactive)
  415.   (pascal-indent-line)
  416.   (insert "begin")
  417.   (electric-pascal-terminate-line)
  418.   (save-excursion
  419.     (electric-pascal-terminate-line)
  420.     (insert "end;")
  421.     (beginning-of-line)
  422.     (pascal-indent-line)))
  423.  
  424. (defun pascal-star-comment ()
  425.   "Insert Pascal star comment at point."
  426.   (interactive)
  427.   (pascal-indent-line)
  428.   (insert "(*")
  429.   (electric-pascal-terminate-line)
  430.   (save-excursion
  431.     (electric-pascal-terminate-line)
  432.     (delete-horizontal-space)
  433.     (insert ")"))
  434.   (insert "  "))
  435.  
  436. (defun pascal-mark-defun ()
  437.   "Mark the current pascal function (or procedure).
  438. This puts the mark at the end, and point at the beginning."
  439.   (interactive)
  440.   (push-mark (point))
  441.   (pascal-end-of-defun)
  442.   (push-mark (point))
  443.   (pascal-beg-of-defun)
  444.   (if (fboundp 'zmacs-activate-region)
  445.       (zmacs-activate-region)))
  446.  
  447. (defun pascal-comment-area (start end)
  448.   "Put the region into a Pascal comment.
  449. The comments that are in this area are \"deformed\":
  450. `*)' becomes `!(*' and `}' becomes `!{'.
  451. These deformed comments are returned to normal if you use
  452. \\[pascal-uncomment-area] to undo the commenting.
  453.  
  454. The commented area starts with `pascal-exclude-str-start', and ends with
  455. `pascal-include-str-end'.  But if you change these variables,
  456. \\[pascal-uncomment-area] won't recognize the comments."
  457.   (interactive "r")
  458.   (save-excursion
  459.     ;; Insert start and endcomments
  460.     (goto-char end)
  461.     (if (and (save-excursion (skip-chars-forward " \t") (eolp))
  462.          (not (save-excursion (skip-chars-backward " \t") (bolp))))
  463.     (forward-line 1)
  464.       (beginning-of-line))
  465.     (insert pascal-exclude-str-end)
  466.     (setq end (point))
  467.     (newline)
  468.     (goto-char start)
  469.     (beginning-of-line)
  470.     (insert pascal-exclude-str-start)
  471.     (newline)
  472.     ;; Replace end-comments within commented area
  473.     (goto-char end)
  474.     (save-excursion
  475.       (while (re-search-backward "\\*)" start t)
  476.     (replace-match "!(*" t t)))
  477.     (save-excursion
  478.       (while (re-search-backward "}" start t)
  479.     (replace-match "!{" t t)))))
  480.  
  481. (defun pascal-uncomment-area ()
  482.   "Uncomment a commented area; change deformed comments back to normal.
  483. This command does nothing if the pointer is not in a commented
  484. area.  See also `pascal-comment-area'."
  485.   (interactive)
  486.   (save-excursion
  487.     (let ((start (point))
  488.       (end (point)))
  489.       ;; Find the boundaries of the comment
  490.       (save-excursion
  491.     (setq start (progn (search-backward pascal-exclude-str-start nil t)
  492.                (point)))
  493.     (setq end (progn (search-forward pascal-exclude-str-end nil t)
  494.              (point))))
  495.       ;; Check if we're really inside a comment
  496.       (if (or (equal start (point)) (<= end (point)))
  497.       (message "Not standing within commented area.")
  498.     (progn
  499.       ;; Remove endcomment
  500.       (goto-char end)
  501.       (beginning-of-line)
  502.       (let ((pos (point)))
  503.         (end-of-line)
  504.         (delete-region pos (1+ (point))))
  505.       ;; Change comments back to normal
  506.       (save-excursion
  507.         (while (re-search-backward "!{" start t)
  508.           (replace-match "}" t t)))
  509.       (save-excursion
  510.         (while (re-search-backward "!(\\*" start t)
  511.           (replace-match "*)" t t)))
  512.       ;; Remove startcomment
  513.       (goto-char start)
  514.       (beginning-of-line)
  515.       (let ((pos (point)))
  516.         (end-of-line)
  517.         (delete-region pos (1+ (point)))))))))
  518.  
  519. (defun pascal-beg-of-defun ()
  520.   "Move backward to the beginning of the current function or procedure."
  521.   (interactive)
  522.   (catch 'found
  523.     (if (not (looking-at (concat "\\s \\|\\s)\\|" pascal-defun-re)))
  524.     (forward-sexp 1))
  525.     (let ((nest 0) (max -1) (func 0)
  526.       (reg (concat pascal-beg-block-re "\\|" 
  527.                pascal-end-block-re "\\|"
  528.                pascal-defun-re)))
  529.       (while (re-search-backward reg nil 'move)
  530.     (cond ((let ((state (save-excursion
  531.                   (parse-partial-sexp (point-min) (point)))))
  532.          (or (nth 3 state) (nth 4 state))) ; Inside string or comment
  533.            ())
  534.           ((match-end 1)                       ; begin|case|record|repeat
  535.            (if (and (looking-at "\\<record\\>") (>= max 0))
  536.            (setq func (1- func)))
  537.            (setq nest (1+ nest)
  538.              max (max nest max)))
  539.           ((match-end 2)                       ; end|until
  540.            (if (and (= nest max) (>= max 0))
  541.            (setq func (1+ func)))
  542.            (setq nest (1- nest)))
  543.           ((match-end 3)                       ; function|procedure
  544.            (if (= 0 func)
  545.            (throw 'found t)
  546.          (setq func (1- func)))))))
  547.     nil))
  548.  
  549. (defun pascal-end-of-defun ()
  550.   "Move forward to the end of the current function or procedure."
  551.   (interactive)
  552.   (if (looking-at "\\s ")
  553.       (forward-sexp 1))
  554.   (if (not (looking-at pascal-defun-re))
  555.       (pascal-beg-of-defun))
  556.   (forward-char 1)
  557.   (let ((nest 0) (func 1)
  558.     (reg (concat pascal-beg-block-re "\\|" 
  559.              pascal-end-block-re "\\|"
  560.              pascal-defun-re)))
  561.     (while (and (/= func 0)
  562.         (re-search-forward reg nil 'move))
  563.       (cond ((let ((state (save-excursion
  564.                   (parse-partial-sexp (point-min) (point)))))
  565.          (or (nth 3 state) (nth 4 state))) ; Inside string or comment
  566.            ())
  567.         ((match-end 1)
  568.          (setq nest (1+ nest))
  569.          (if (save-excursion
  570.            (goto-char (match-beginning 0))
  571.            (looking-at "\\<record\\>"))
  572.          (setq func (1+ func))))
  573.         ((match-end 2)
  574.          (setq nest (1- nest))
  575.          (if (= nest 0)
  576.          (setq func (1- func))))
  577.         ((match-end 3)
  578.          (setq func (1+ func))))))
  579.   (forward-line 1))
  580.  
  581. (defun pascal-end-of-statement ()
  582.   "Move forward to end of current statement."
  583.   (interactive)
  584.   (let ((nest 0) pos
  585.     (regexp (concat "\\(" pascal-beg-block-re "\\)\\|\\("
  586.             pascal-end-block-re "\\)")))
  587.     (if (not (looking-at "[ \t\n]")) (forward-sexp -1))
  588.     (or (looking-at pascal-beg-block-re)
  589.     ;; Skip to end of statement
  590.     (setq pos (catch 'found
  591.             (while t
  592.               (forward-sexp 1)
  593.               (cond ((looking-at "[ \t]*;")
  594.                  (skip-chars-forward "^;")
  595.                  (forward-char 1)
  596.                  (throw 'found (point)))
  597.                 ((save-excursion
  598.                    (forward-sexp -1)
  599.                    (looking-at pascal-beg-block-re))
  600.                  (goto-char (match-beginning 0))
  601.                  (throw 'found nil))
  602.                 ((eobp)
  603.                  (throw 'found (point))))))))
  604.     (if (not pos)
  605.     ;; Skip a whole block
  606.     (catch 'found
  607.       (while t
  608.         (re-search-forward regexp nil 'move)
  609.         (setq nest (if (match-end 1) 
  610.                (1+ nest)
  611.              (1- nest)))
  612.         (cond ((eobp)
  613.            (throw 'found (point)))
  614.           ((= 0 nest)
  615.            (throw 'found (pascal-end-of-statement))))))
  616.       pos)))
  617.  
  618. (defun pascal-downcase-keywords ()
  619.   "Downcase all Pascal keywords in the buffer."
  620.   (interactive)
  621.   (pascal-change-keywords 'downcase-word))
  622.  
  623. (defun pascal-upcase-keywords ()
  624.   "Upcase all Pascal keywords in the buffer."
  625.   (interactive)
  626.   (pascal-change-keywords 'upcase-word))
  627.  
  628. (defun pascal-capitalize-keywords ()
  629.   "Capitalize all Pascal keywords in the buffer."
  630.   (interactive)
  631.   (pascal-change-keywords 'capitalize-word))
  632.  
  633. ;; Change the keywords according to argument.
  634. (defun pascal-change-keywords (change-word)
  635.   (save-excursion
  636.     (let ((keyword-re (concat "\\<\\("
  637.                   (mapconcat 'identity pascal-keywords "\\|")
  638.                   "\\)\\>")))
  639.       (goto-char (point-min))
  640.       (while (re-search-forward keyword-re nil t)
  641.     (funcall change-word -1)))))
  642.  
  643.  
  644.  
  645. ;;;
  646. ;;; Other functions
  647. ;;;
  648. (defun pascal-set-auto-comments ()
  649.   "Insert `{ case }' or `{ NAME }' on this line if appropriate.
  650. Insert `{ case }' if there is an `end' on the line which
  651. ends a case block.  Insert `{ NAME }' if there is an `end'
  652. on the line which ends a function or procedure named NAME."
  653.   (save-excursion
  654.     (forward-line -1)
  655.     (skip-chars-forward " \t")
  656.     (if (and (looking-at "\\<end;")
  657.          (not (save-excursion
  658.             (end-of-line)
  659.             (search-backward "{" (pascal-get-beg-of-line) t))))
  660.     (let ((type (car (pascal-calculate-indent))))
  661.       (if (eq type 'declaration)
  662.           ()
  663.         (if (eq type 'case)
  664.         ;; This is a case block
  665.         (progn
  666.           (end-of-line)
  667.           (delete-horizontal-space)
  668.           (insert " { case }"))
  669.           (let ((nest 1))
  670.         ;; Check if this is the end of a function
  671.         (save-excursion
  672.           (while (not (or (looking-at pascal-defun-re) (bobp)))
  673.             (backward-sexp 1)
  674.             (cond ((looking-at pascal-beg-block-re)
  675.                (setq nest (1- nest)))
  676.               ((looking-at pascal-end-block-re)
  677.                (setq nest (1+ nest)))))
  678.           (if (bobp)
  679.               (setq nest 1)))
  680.         (if (zerop nest)
  681.             (progn
  682.               (end-of-line)
  683.               (delete-horizontal-space)
  684.               (insert " { ")
  685.               (let (b e)
  686.             (save-excursion
  687.               (setq b (progn (pascal-beg-of-defun)
  688.                      (skip-chars-forward "^ \t")
  689.                      (skip-chars-forward " \t")
  690.                      (point))
  691.                 e (progn (skip-chars-forward "a-zA-Z0-9_")
  692.                      (point))))
  693.             (insert-buffer-substring (current-buffer) b e))
  694.               (insert " }"))))))))))
  695.  
  696.  
  697.  
  698. ;;;
  699. ;;; Indentation
  700. ;;;
  701. (defconst pascal-indent-alist
  702.   '((block . (+ ind pascal-indent-level))
  703.     (case . (+ ind pascal-case-indent))
  704.     (caseblock . ind) (cpp . 0)
  705.     (declaration . (+ ind pascal-indent-level))
  706.     (paramlist . (pascal-indent-paramlist t))
  707.     (comment . (pascal-indent-comment t))
  708.     (defun . ind) (contexp . ind)
  709.     (unknown . 0) (string . 0)))
  710.  
  711. (defun pascal-indent-command ()
  712.   "Indent for special part of code."
  713.   (let* ((indent-str (pascal-calculate-indent))
  714.      (type (car indent-str))
  715.      (ind (car (cdr indent-str))))
  716.     (cond ((and (eq type 'paramlist)
  717.         (or (memq 'all pascal-auto-lineup)
  718.             (memq 'paramlist pascal-auto-lineup)))
  719.        (pascal-indent-paramlist)
  720.        (pascal-indent-paramlist))
  721.       ((and (eq type 'declaration)
  722.         (or (memq 'all pascal-auto-lineup)
  723.             (memq 'declaration  pascal-auto-lineup)))
  724.        (pascal-indent-declaration))
  725.       ((and (eq type 'case) (not (looking-at "^[ \t]*$"))
  726.         (or (memq 'all pascal-auto-lineup)
  727.             (memq 'case pascal-auto-lineup)))
  728.        (pascal-indent-case)))
  729.     (if (looking-at "[ \t]+$")
  730.     (skip-chars-forward " \t"))))
  731.  
  732. (defun pascal-indent-line ()
  733.   "Indent current line as a Pascal statement."
  734.   (let* ((indent-str (pascal-calculate-indent))
  735.      (type (car indent-str))
  736.      (ind (car (cdr indent-str))))
  737.     (if (looking-at "^[0-9a-zA-Z]+[ \t]*:[^=]")
  738.     (search-forward ":" nil t))
  739.     (delete-horizontal-space)
  740.     ;; Some things should not be indented
  741.     (if (or (and (eq type 'declaration) (looking-at pascal-declaration-re))
  742.         (eq type 'cpp)
  743.         (looking-at pascal-defun-re))
  744.     ()
  745.       ;; Other things should have no extra indent
  746.       (if (looking-at pascal-noindent-re)
  747.       (indent-to ind)
  748.     ;; But most lines are treated this way:
  749.     (indent-to (eval (cdr (assoc type pascal-indent-alist))))
  750.     ))))
  751.  
  752. (defun pascal-calculate-indent ()
  753.   "Calculate the indent of the current Pascal line.
  754. Return a list of two elements: (INDENT-TYPE INDENT-LEVEL)."
  755.   (save-excursion
  756.     (let* ((oldpos (point))
  757.        (state (save-excursion (parse-partial-sexp (point-min) (point))))
  758.        (nest 0) (par 0) (complete (looking-at "[ \t]*end\\>"))
  759.        (elsed (looking-at "[ \t]*else\\>"))
  760.        (type (catch 'nesting
  761.            ;; Check if inside a string, comment or parenthesis
  762.            (cond ((nth 3 state) (throw 'nesting 'string))
  763.              ((nth 4 state) (throw 'nesting 'comment))
  764.              ((> (car state) 0)
  765.               (goto-char (scan-lists (point) -1 (car state)))
  766.               (setq par (1+ (current-column))))
  767.              ((save-excursion (beginning-of-line)
  768.                       (eq (following-char) ?#))
  769.               (throw 'nesting 'cpp)))
  770.            ;; Loop until correct indent is found
  771.            (while t
  772.              (backward-sexp 1)
  773.              (cond (;--Escape from case statements
  774.                 (and (looking-at "[A-Za-z0-9]+[ \t]*:[^=]")
  775.                  (not complete)
  776.                  (save-excursion (skip-chars-backward " \t")
  777.                          (bolp))
  778.                  (= (save-excursion
  779.                       (end-of-line) (backward-sexp) (point))
  780.                     (point))
  781.                  (> (save-excursion (goto-char oldpos)
  782.                             (beginning-of-line)
  783.                             (point))
  784.                     (point)))
  785.                 (throw 'nesting 'caseblock))
  786.                (;--Nest block outwards
  787.                 (looking-at pascal-beg-block-re)
  788.                 (if (= nest 0)
  789.                 (cond ((looking-at "case\\>")
  790.                        (throw 'nesting 'case))
  791.                       ((looking-at "record\\>")
  792.                        (throw 'nesting 'declaration))
  793.                       (t (throw 'nesting 'block)))
  794.                   (setq nest (1- nest))))
  795.                (;--Nest block inwards
  796.                 (looking-at pascal-end-block-re)
  797.                 (if (and (looking-at "end\\s ")
  798.                      elsed (not complete))
  799.                 (throw 'nesting 'block))
  800.                 (setq complete t
  801.                   nest (1+ nest)))
  802.                (;--Defun (or parameter list)
  803.                 (looking-at pascal-defun-re)
  804.                 (if (= 0 par)
  805.                 (throw 'nesting 'defun)
  806.                   (setq par 0)
  807.                   (let ((n 0))
  808.                 (while (re-search-forward
  809.                     "\\(\\<record\\>\\)\\|\\<end\\>"
  810.                     oldpos t)
  811.                   (if (match-end 1)
  812.                       (setq n (1+ n)) (setq n (1- n))))
  813.                 (if (> n 0)
  814.                     (throw 'nesting 'declaration)
  815.                   (throw 'nesting 'paramlist)))))
  816.                (;--Declaration part
  817.                 (looking-at pascal-declaration-re)
  818.                 (if (save-excursion
  819.                   (goto-char oldpos)
  820.                   (forward-line -1)
  821.                   (looking-at "^[ \t]*$"))
  822.                 (throw 'nesting 'unknown)
  823.                   (throw 'nesting 'declaration)))
  824.                (;--If, else or while statement
  825.                 (and (not complete)
  826.                  (looking-at pascal-sub-block-re))
  827.                 (throw 'nesting 'block))
  828.                (;--Found complete statement
  829.                 (save-excursion (forward-sexp 1)
  830.                         (= (following-char) ?\;))
  831.                 (setq complete t))
  832.                (;--No known statements
  833.                 (bobp)
  834.                 (throw 'nesting 'unknown))
  835.                )))))
  836.  
  837.       ;; Return type of block and indent level.
  838.       (if (> par 0)                               ; Unclosed Parenthesis 
  839.       (list 'contexp par)
  840.     (list type (pascal-indent-level))))))
  841.  
  842. (defun pascal-indent-level ()
  843.   "Return the indent-level the current statement has.
  844. Do not count labels, case-statements or records."
  845.   (save-excursion
  846.     (beginning-of-line)
  847.     (if (looking-at "[ \t]*[0-9a-zA-Z]+[ \t]*:[^=]")
  848.     (search-forward ":" nil t)
  849.       (if (looking-at ".*=[ \t]*record\\>")
  850.       (search-forward "=" nil t)))
  851.     (skip-chars-forward " \t")
  852.     (current-column)))
  853.  
  854. (defun pascal-indent-comment (&optional arg)
  855.   "Indent current line as comment.
  856. If optional arg is non-nil, just return the
  857. column number the line should be indented to."
  858.     (let* ((stcol (save-excursion
  859.             (re-search-backward "(\\*\\|{" nil t)
  860.             (1+ (current-column)))))
  861.       (if arg stcol
  862.     (delete-horizontal-space)
  863.     (indent-to stcol))))
  864.  
  865. (defun pascal-indent-case ()
  866.   "Indent within case statements."
  867.   (skip-chars-forward ": \t")
  868.   (let ((end (prog2
  869.          (end-of-line)
  870.          (point-marker)
  871.            (re-search-backward "\\<case\\>" nil t)))
  872.     (beg (point)) oldpos
  873.     (ind 0))
  874.     ;; Get right indent
  875.     (while (< (point) (marker-position end))
  876.       (if (re-search-forward 
  877.        "^[ \t]*[^ \t,:]+[ \t]*\\(,[ \t]*[^ \t,:]+[ \t]*\\)*:"
  878.        (marker-position end) 'move)
  879.       (forward-char -1))
  880.       (delete-horizontal-space)
  881.       (if (> (current-column) ind)
  882.       (setq ind (current-column)))
  883.       (pascal-end-of-statement))
  884.     (goto-char beg)
  885.     (setq oldpos (marker-position end))
  886.     ;; Indent all case statements
  887.     (while (< (point) (marker-position end))
  888.       (if (re-search-forward
  889.        "^[ \t]*[^][ \t,\\.:]+[ \t]*\\(,[ \t]*[^ \t,:]+[ \t]*\\)*:"
  890.        (marker-position end) 'move)
  891.       (forward-char -1))
  892.       (indent-to (1+ ind))
  893.       (if (/= (following-char) ?:)
  894.       ()
  895.     (forward-char 1)
  896.     (delete-horizontal-space)
  897.     (insert " "))
  898.       (setq oldpos (point))
  899.       (pascal-end-of-statement))
  900.     (goto-char oldpos)))
  901.  
  902. (defun pascal-indent-paramlist (&optional arg)
  903.   "Indent current line in parameterlist.
  904. If optional arg is non-nil, just return the
  905. indent of the current line in parameterlist."
  906.   (save-excursion
  907.     (let* ((oldpos (point))
  908.        (stpos (progn (goto-char (scan-lists (point) -1 1)) (point)))
  909.        (stcol (1+ (current-column)))
  910.        (edpos (progn (pascal-declaration-end) 
  911.              (search-backward ")" (pascal-get-beg-of-line) t)
  912.              (point)))
  913.        (usevar (re-search-backward "\\<var\\>" stpos t)))
  914.       (if arg (progn
  915.         ;; If arg, just return indent
  916.         (goto-char oldpos)
  917.         (beginning-of-line)
  918.         (if (or (not usevar) (looking-at "[ \t]*var\\>"))
  919.             stcol (+ 4 stcol)))
  920.     (goto-char stpos)
  921.     (forward-char 1)
  922.     (delete-horizontal-space)
  923.     (if (and usevar (not (looking-at "var\\>")))
  924.         (indent-to (+ 4 stcol)))
  925.     (pascal-indent-declaration nil stpos edpos)))))
  926.  
  927. (defun pascal-indent-declaration (&optional arg start end)
  928.   "Indent current lines as declaration, lining up the `:'s or `='s."
  929.   (let ((pos (point-marker)))
  930.     (if (and (not (or arg start)) (not (pascal-declaration-beg)))
  931.     ()
  932.       (let ((lineup (if (or (looking-at "\\<var\\>\\|\\<record\\>") arg start) 
  933.             ":" "="))
  934.         (stpos (if start start
  935.                (forward-word 2) (backward-word 1) (point)))
  936.         (edpos (set-marker (make-marker)
  937.                    (if end end
  938.                  (max (progn (pascal-declaration-end)
  939.                          (point))
  940.                       pos))))
  941.         ind)
  942.  
  943.     (goto-char stpos)
  944.     ;; Indent lines in record block
  945.     (if arg
  946.         (while (<= (point) (marker-position edpos))
  947.           (beginning-of-line)
  948.           (delete-horizontal-space)
  949.           (if (looking-at "end\\>")
  950.           (indent-to arg)
  951.         (indent-to (+ arg pascal-indent-level)))
  952.           (forward-line 1)))
  953.  
  954.     ;; Do lineup
  955.     (setq ind (pascal-get-lineup-indent stpos edpos lineup))
  956.     (goto-char stpos)
  957.     (while (<= (point) (marker-position edpos))
  958.       (if (search-forward lineup (pascal-get-end-of-line) 'move)
  959.           (forward-char -1))
  960.       (delete-horizontal-space)
  961.       (indent-to ind)
  962.       (if (not (looking-at lineup))
  963.           (forward-line 1) ; No more indent if there is no : or =
  964.         (forward-char 1)
  965.         (delete-horizontal-space)
  966.         (insert " ")
  967.         ;; Indent record block
  968.         (if (looking-at "record\\>")
  969.         (pascal-indent-declaration (current-column)))
  970.         (forward-line 1)))))
  971.  
  972.     ;; If arg - move point
  973.     (if arg (forward-line -1)
  974.       (goto-char (marker-position pos)))))
  975.  
  976. ;  "Return the indent level that will line up several lines within the region
  977. ;from b to e nicely. The lineup string is str."
  978. (defun pascal-get-lineup-indent (b e str)
  979.   (save-excursion
  980.     (let ((ind 0)
  981.       (reg (concat str "\\|\\(\\<record\\>\\)"))
  982.       nest)
  983.       (goto-char b)
  984.       ;; Get rightmost position
  985.       (while (< (point) e)
  986.     (setq nest 1)
  987.     (if (re-search-forward reg (min e (pascal-get-end-of-line 2)) 'move)
  988.         (progn
  989.           ;; Skip record blocks
  990.           (if (match-beginning 1)
  991.           (pascal-declaration-end)
  992.         (progn
  993.           (goto-char (match-beginning 0))
  994.           (skip-chars-backward " \t")
  995.           (if (> (current-column) ind)
  996.               (setq ind (current-column)))
  997.           (goto-char (match-end 0)))))))
  998.       ;; In case no lineup was found
  999.       (if (> ind 0)
  1000.       (1+ ind)
  1001.     ;; No lineup-string found
  1002.     (goto-char b)
  1003.     (end-of-line)
  1004.     (skip-chars-backward " \t")
  1005.     (1+ (current-column))))))
  1006.     
  1007.  
  1008.  
  1009. ;;;
  1010. ;;; Completion
  1011. ;;;
  1012. (defvar pascal-str nil)
  1013. (defvar pascal-all nil)
  1014. (defvar pascal-pred nil)
  1015. (defvar pascal-buffer-to-use nil)
  1016. (defvar pascal-flag nil)
  1017.  
  1018. (defun pascal-string-diff (str1 str2)
  1019.   "Return index of first letter where STR1 and STR2 differs."
  1020.   (catch 'done
  1021.     (let ((diff 0))
  1022.       (while t
  1023.     (if (or (> (1+ diff) (length str1))
  1024.         (> (1+ diff) (length str2)))
  1025.         (throw 'done diff))
  1026.     (or (equal (aref str1 diff) (aref str2 diff))
  1027.         (throw 'done diff))
  1028.     (setq diff (1+ diff))))))
  1029.  
  1030. ;; Calculate all possible completions for functions if argument is `function',
  1031. ;; completions for procedures if argument is `procedure' or both functions and
  1032. ;; procedures otherwise.
  1033.  
  1034. (defun pascal-func-completion (type)
  1035.   ;; Build regular expression for function/procedure names
  1036.   (if (string= pascal-str "")
  1037.       (setq pascal-str "[a-zA-Z_]"))
  1038.   (let ((pascal-str (concat (cond
  1039.                  ((eq type 'procedure) "\\<\\(procedure\\)\\s +")
  1040.                  ((eq type 'function) "\\<\\(function\\)\\s +")
  1041.                  (t "\\<\\(function\\|procedure\\)\\s +"))
  1042.                 "\\<\\(" pascal-str "[a-zA-Z0-9_.]*\\)\\>"))
  1043.     match)
  1044.     
  1045.     (if (not (looking-at "\\<\\(function\\|procedure\\)\\>"))
  1046.     (re-search-backward "\\<\\(function\\|procedure\\)\\>" nil t))
  1047.     (forward-char 1)
  1048.  
  1049.     ;; Search through all reachable functions
  1050.     (while (pascal-beg-of-defun)
  1051.       (if (re-search-forward pascal-str (pascal-get-end-of-line) t)
  1052.       (progn (setq match (buffer-substring (match-beginning 2)
  1053.                            (match-end 2)))
  1054.          (if (or (null pascal-pred)
  1055.              (funcall pascal-pred match))
  1056.              (setq pascal-all (cons match pascal-all)))))
  1057.       (goto-char (match-beginning 0)))))
  1058.  
  1059. (defun pascal-get-completion-decl ()
  1060.   ;; Macro for searching through current declaration (var, type or const)
  1061.   ;; for matches of `str' and adding the occurence tp `all'
  1062.   (let ((end (save-excursion (pascal-declaration-end)
  1063.                  (point)))
  1064.     match)
  1065.     ;; Traverse lines
  1066.     (while (< (point) end)
  1067.       (if (re-search-forward "[:=]" (pascal-get-end-of-line) t)
  1068.       ;; Traverse current line
  1069.       (while (and (re-search-backward 
  1070.                (concat "\\((\\|\\<\\(var\\|type\\|const\\)\\>\\)\\|" 
  1071.                    pascal-symbol-re)
  1072.                (pascal-get-beg-of-line) t)
  1073.               (not (match-end 1)))
  1074.         (setq match (buffer-substring (match-beginning 0) (match-end 0)))
  1075.         (if (string-match (concat "\\<" pascal-str) match)
  1076.         (if (or (null pascal-pred)
  1077.             (funcall pascal-pred match))
  1078.             (setq pascal-all (cons match pascal-all))))))
  1079.       (if (re-search-forward "\\<record\\>" (pascal-get-end-of-line) t)
  1080.       (pascal-declaration-end)
  1081.     (forward-line 1)))))
  1082.  
  1083. (defun pascal-type-completion ()
  1084.   "Calculate all possible completions for types."
  1085.   (let ((start (point))
  1086.     goon)
  1087.     ;; Search for all reachable type declarations
  1088.     (while (or (pascal-beg-of-defun)
  1089.            (setq goon (not goon)))
  1090.       (save-excursion
  1091.     (if (and (< start (prog1 (save-excursion (pascal-end-of-defun)
  1092.                          (point))
  1093.                 (forward-char 1)))
  1094.          (re-search-forward
  1095.           "\\<type\\>\\|\\<\\(begin\\|function\\|procedure\\)\\>"
  1096.           start t)
  1097.          (not (match-end 1)))
  1098.         ;; Check current type declaration
  1099.         (pascal-get-completion-decl))))))
  1100.  
  1101. (defun pascal-var-completion ()
  1102.   "Calculate all possible completions for variables (or constants)."
  1103.   (let ((start (point))
  1104.     goon twice)
  1105.     ;; Search for all reachable var declarations
  1106.     (while (or (pascal-beg-of-defun)
  1107.            (setq goon (not goon)))
  1108.       (save-excursion
  1109.     (if (> start (prog1 (save-excursion (pascal-end-of-defun)
  1110.                         (point))))
  1111.         () ; Declarations not reacable
  1112.       (if (search-forward "(" (pascal-get-end-of-line) t)
  1113.           ;; Check parameterlist
  1114.         (pascal-get-completion-decl))
  1115.       (setq twice 2)
  1116.       (while (>= (setq twice (1- twice)) 0)
  1117.         (cond ((and (re-search-forward
  1118.              (concat "\\<\\(var\\|const\\)\\>\\|"
  1119.                  "\\<\\(begin\\|function\\|procedure\\)\\>")
  1120.              start t)
  1121.             (not (match-end 2)))
  1122.            ;; Check var/const declarations
  1123.            (pascal-get-completion-decl))
  1124.           ((match-end 2)
  1125.            (setq twice 0)))))))))
  1126.  
  1127.  
  1128. (defun pascal-keyword-completion (keyword-list)
  1129.   "Give list of all possible completions of keywords in KEYWORD-LIST."
  1130.   (mapcar '(lambda (s) 
  1131.          (if (string-match (concat "\\<" pascal-str) s)
  1132.          (if (or (null pascal-pred)
  1133.              (funcall pascal-pred s))
  1134.              (setq pascal-all (cons s pascal-all)))))
  1135.       keyword-list))
  1136.  
  1137. ;; Function passed to completing-read, try-completion or
  1138. ;; all-completions to get completion on STR. If predicate is non-nil,
  1139. ;; it must be a function to be called for every match to check if this
  1140. ;; should really be a match. If flag is t, the function returns a list
  1141. ;; of all possible completions. If it is nil it returns a string, the
  1142. ;; longest possible completion, or t if STR is an exact match. If flag
  1143. ;; is 'lambda, the function returns t if STR is an exact match, nil
  1144. ;; otherwise.
  1145.  
  1146. (defun pascal-completion (pascal-str pascal-pred pascal-flag)
  1147.   (save-excursion
  1148.     (let ((pascal-all nil))
  1149.       ;; Set buffer to use for searching labels. This should be set
  1150.       ;; within functins which use pascal-completions
  1151.       (set-buffer pascal-buffer-to-use)
  1152.  
  1153.       ;; Determine what should be completed
  1154.       (let ((state (car (pascal-calculate-indent))))
  1155.     (cond (;--Within a declaration or parameterlist
  1156.            (or (eq state 'declaration) (eq state 'paramlist)
  1157.            (and (eq state 'defun)
  1158.             (save-excursion
  1159.               (re-search-backward ")[ \t]*:"
  1160.                           (pascal-get-beg-of-line) t))))
  1161.            (if (or (eq state 'paramlist) (eq state 'defun))
  1162.            (pascal-beg-of-defun))
  1163.            (pascal-type-completion)
  1164.            (pascal-keyword-completion pascal-type-keywords))
  1165.           (;--Starting a new statement
  1166.            (and (not (eq state 'contexp))
  1167.             (save-excursion
  1168.               (skip-chars-backward "a-zA-Z0-9_.")
  1169.               (backward-sexp 1)
  1170.               (or (looking-at pascal-nosemi-re)
  1171.               (progn
  1172.                 (forward-sexp 1)
  1173.                 (looking-at "\\s *\\(;\\|:[^=]\\)")))))
  1174.            (save-excursion (pascal-var-completion))
  1175.            (pascal-func-completion 'procedure)
  1176.            (pascal-keyword-completion pascal-start-keywords))
  1177.           (t;--Anywhere else
  1178.            (save-excursion (pascal-var-completion))
  1179.            (pascal-func-completion 'function)
  1180.            (pascal-keyword-completion pascal-separator-keywords))))
  1181.       
  1182.       ;; Now we have built a list of all matches. Give response to caller
  1183.       (pascal-completion-response))))
  1184.  
  1185. (defun pascal-completion-response ()
  1186.   (cond ((or (equal pascal-flag 'lambda) (null pascal-flag))
  1187.      ;; This was not called by all-completions
  1188.      (if (null pascal-all)
  1189.          ;; Return nil if there was no matching label
  1190.          nil
  1191.        ;; Get longest string common in the labels
  1192.        (let* ((elm (cdr pascal-all))
  1193.           (match (car pascal-all))
  1194.           (min (length match))
  1195.           exact tmp)
  1196.          (if (string= match pascal-str)
  1197.          ;; Return t if first match was an exact match
  1198.          (setq match t)
  1199.            (while (not (null elm))
  1200.          ;; Find longest common string
  1201.          (if (< (setq tmp (pascal-string-diff match (car elm))) min)
  1202.              (progn
  1203.                (setq min tmp)
  1204.                (setq match (substring match 0 min))))
  1205.          ;; Terminate with match=t if this is an exact match
  1206.          (if (string= (car elm) pascal-str)
  1207.              (progn
  1208.                (setq match t)
  1209.                (setq elm nil))
  1210.            (setq elm (cdr elm)))))
  1211.          ;; If this is a test just for exact match, return nil ot t
  1212.          (if (and (equal pascal-flag 'lambda) (not (equal match 't)))
  1213.          nil
  1214.            match))))
  1215.     ;; If flag is t, this was called by all-completions. Return
  1216.     ;; list of all possible completions
  1217.     (pascal-flag
  1218.      pascal-all)))
  1219.  
  1220. (defvar pascal-last-word-numb 0)
  1221. (defvar pascal-last-word-shown nil)
  1222. (defvar pascal-last-completions nil)
  1223.  
  1224. (defun pascal-complete-word ()
  1225.   "Complete word at current point.
  1226. \(See also `pascal-toggle-completions', `pascal-type-keywords',
  1227. `pascal-start-keywords' and `pascal-separator-keywords'.)"
  1228.   (interactive)
  1229.   (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
  1230.      (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
  1231.      (pascal-str (buffer-substring b e))
  1232.      ;; The following variable is used in pascal-completion
  1233.      (pascal-buffer-to-use (current-buffer))
  1234.      (allcomp (if (and pascal-toggle-completions
  1235.                (string= pascal-last-word-shown pascal-str))
  1236.               pascal-last-completions
  1237.             (all-completions pascal-str 'pascal-completion)))
  1238.      (match (if pascal-toggle-completions
  1239.             "" (try-completion
  1240.             pascal-str (mapcar '(lambda (elm)
  1241.                           (cons elm 0)) allcomp)))))
  1242.     ;; Delete old string
  1243.     (delete-region b e)
  1244.  
  1245.     ;; Toggle-completions inserts whole labels
  1246.     (if pascal-toggle-completions
  1247.     (progn
  1248.       ;; Update entry number in list
  1249.       (setq pascal-last-completions allcomp
  1250.         pascal-last-word-numb 
  1251.         (if (>= pascal-last-word-numb (1- (length allcomp)))
  1252.             0
  1253.           (1+ pascal-last-word-numb)))
  1254.       (setq pascal-last-word-shown (elt allcomp pascal-last-word-numb))
  1255.       ;; Display next match or same string if no match was found
  1256.       (if (not (null allcomp))
  1257.           (insert "" pascal-last-word-shown)
  1258.         (insert "" pascal-str)
  1259.         (message "(No match)")))
  1260.       ;; The other form of completion does not necessarly do that.
  1261.  
  1262.       ;; Insert match if found, or the original string if no match
  1263.       (if (or (null match) (equal match 't))
  1264.       (progn (insert "" pascal-str)
  1265.          (message "(No match)"))
  1266.     (insert "" match))
  1267.       ;; Give message about current status of completion
  1268.       (cond ((equal match 't)
  1269.          (if (not (null (cdr allcomp)))
  1270.          (message "(Complete but not unique)")
  1271.            (message "(Sole completion)")))
  1272.         ;; Display buffer if the current completion didn't help 
  1273.         ;; on completing the label.
  1274.         ((and (not (null (cdr allcomp))) (= (length pascal-str)
  1275.                         (length match)))
  1276.          (with-output-to-temp-buffer "*Completions*"
  1277.            (display-completion-list allcomp))
  1278.          ;; Wait for a keypress. Then delete *Completion*  window
  1279.          (momentary-string-display "" (point))
  1280.          (delete-window (get-buffer-window (get-buffer "*Completions*")))
  1281.          )))))
  1282.  
  1283. (defun pascal-show-completions ()
  1284.   "Show all possible completions at current point."
  1285.   (interactive)
  1286.   (let* ((b (save-excursion (skip-chars-backward "a-zA-Z0-9_") (point)))
  1287.      (e (save-excursion (skip-chars-forward "a-zA-Z0-9_") (point)))
  1288.      (pascal-str (buffer-substring b e))
  1289.      ;; The following variable is used in pascal-completion
  1290.      (pascal-buffer-to-use (current-buffer))
  1291.      (allcomp (if (and pascal-toggle-completions
  1292.                (string= pascal-last-word-shown pascal-str))
  1293.               pascal-last-completions
  1294.             (all-completions pascal-str 'pascal-completion))))
  1295.     ;; Show possible completions in a temporary buffer.
  1296.     (with-output-to-temp-buffer "*Completions*"
  1297.       (display-completion-list allcomp))
  1298.     ;; Wait for a keypress. Then delete *Completion*  window
  1299.     (momentary-string-display "" (point))
  1300.     (delete-window (get-buffer-window (get-buffer "*Completions*")))))
  1301.  
  1302.  
  1303. (defun pascal-get-default-symbol ()
  1304.   "Return symbol around current point as a string."
  1305.   (save-excursion
  1306.     (buffer-substring (progn
  1307.             (skip-chars-backward " \t")
  1308.             (skip-chars-backward "a-zA-Z0-9_")
  1309.             (point))
  1310.               (progn
  1311.             (skip-chars-forward "a-zA-Z0-9_")
  1312.             (point)))))
  1313.  
  1314. (defun pascal-build-defun-re (str &optional arg)
  1315.   "Return function/procedure starting with STR as regular expression.
  1316. With optional second arg non-nil, STR is the complete name of the instruction."
  1317.   (if arg
  1318.       (concat "^\\(function\\|procedure\\)[ \t]+\\(" str "\\)\\>")
  1319.     (concat "^\\(function\\|procedure\\)[ \t]+\\(" str "[a-zA-Z0-9_]*\\)\\>")))
  1320.  
  1321. ;; Function passed to completing-read, try-completion or
  1322. ;; all-completions to get completion on any function name. If
  1323. ;; predicate is non-nil, it must be a function to be called for every
  1324. ;; match to check if this should really be a match. If flag is t, the
  1325. ;; function returns a list of all possible completions. If it is nil
  1326. ;; it returns a string, the longest possible completion, or t if STR
  1327. ;; is an exact match. If flag is 'lambda, the function returns t if
  1328. ;; STR is an exact match, nil otherwise.
  1329.  
  1330. (defun pascal-comp-defun (pascal-str pascal-pred pascal-flag)
  1331.   (save-excursion
  1332.     (let ((pascal-all nil)
  1333.       match)
  1334.  
  1335.       ;; Set buffer to use for searching labels. This should be set
  1336.       ;; within functins which use pascal-completions
  1337.       (set-buffer pascal-buffer-to-use)
  1338.  
  1339.       (let ((pascal-str pascal-str))
  1340.     ;; Build regular expression for functions
  1341.     (if (string= pascal-str "")
  1342.         (setq pascal-str (pascal-build-defun-re "[a-zA-Z_]"))
  1343.       (setq pascal-str (pascal-build-defun-re pascal-str)))
  1344.     (goto-char (point-min))
  1345.       
  1346.     ;; Build a list of all possible completions
  1347.     (while (re-search-forward pascal-str nil t)
  1348.       (setq match (buffer-substring (match-beginning 2) (match-end 2)))
  1349.       (if (or (null pascal-pred)
  1350.           (funcall pascal-pred match))
  1351.           (setq pascal-all (cons match pascal-all)))))
  1352.  
  1353.       ;; Now we have built a list of all matches. Give response to caller
  1354.       (pascal-completion-response))))
  1355.  
  1356. (defun pascal-goto-defun ()
  1357.   "Move to specified Pascal function/procedure.
  1358. The default is a name found in the buffer around point."
  1359.   (interactive)
  1360.   (let* ((default (pascal-get-default-symbol))
  1361.      ;; The following variable is used in pascal-comp-function
  1362.      (pascal-buffer-to-use (current-buffer))
  1363.      (default (if (pascal-comp-defun default nil 'lambda)
  1364.               default ""))
  1365.      (label (if (not (string= default ""))
  1366.             ;; Do completion with default
  1367.             (completing-read (concat "Label: (default " default ") ")
  1368.                      'pascal-comp-defun nil t "")
  1369.           ;; There is no default value. Complete without it
  1370.           (completing-read "Label: "
  1371.                    'pascal-comp-defun nil t ""))))
  1372.     ;; If there was no response on prompt, use default value
  1373.     (if (string= label "")
  1374.     (setq label default))
  1375.     ;; Goto right place in buffer if label is not an empty string
  1376.     (or (string= label "")
  1377.     (progn
  1378.       (goto-char (point-min))
  1379.       (re-search-forward (pascal-build-defun-re label t))
  1380.       (beginning-of-line)))))
  1381.  
  1382.  
  1383.  
  1384. ;;;
  1385. ;;; Pascal-outline-mode
  1386. ;;;
  1387. (defvar pascal-outline-map nil "Keymap used in Pascal Outline mode.")
  1388.  
  1389. (if pascal-outline-map
  1390.     nil
  1391.   (if (boundp 'set-keymap-name)
  1392.       (set-keymap-name pascal-outline-map 'pascal-outline-map))
  1393.   (if (not (boundp 'set-keymap-parent))
  1394.       (setq pascal-outline-map (copy-keymap pascal-mode-map))
  1395.     (setq pascal-outline-map (make-sparse-keymap))
  1396.     (set-keymap-parent pascal-outline-map pascal-mode-map))
  1397.   (define-key pascal-outline-map "\M-\C-a"  'pascal-outline-prev-defun)
  1398.   (define-key pascal-outline-map "\M-\C-e"  'pascal-outline-next-defun)
  1399.   (define-key pascal-outline-map "\C-c\C-d" 'pascal-outline-goto-defun)
  1400.   (define-key pascal-outline-map "\C-c\C-s" 'pascal-show-all)
  1401.   (define-key pascal-outline-map "\C-c\C-h" 'pascal-hide-other-defuns))
  1402.  
  1403. (defvar pascal-outline-mode nil "Non-nil while using Pascal Outline mode.")
  1404. (make-variable-buffer-local 'pascal-outline-mode)
  1405. (set-default 'pascal-outline-mode nil)
  1406. (if (not (assoc 'pascal-outline-mode minor-mode-alist))
  1407.     (setq minor-mode-alist (append minor-mode-alist
  1408.                    (list '(pascal-outline-mode " Outl")))))
  1409.  
  1410. (defun pascal-outline (&optional arg)
  1411.   "Outline-line minor mode for Pascal mode.
  1412. When in Pascal Outline mode, portions
  1413. of the text being edited may be made invisible. \\<pascal-outline-map>
  1414.  
  1415. Pascal Outline mode provides some additional commands.
  1416.  
  1417. \\[pascal-outline-prev-defun]\
  1418. \t- Move to previous function/procedure, hiding everything else.
  1419. \\[pascal-outline-next-defun]\
  1420. \t- Move to next function/procedure, hiding everything else.
  1421. \\[pascal-outline-goto-defun]\
  1422. \t- Goto function/procedure prompted for in minibuffer,
  1423. \t  hide all other functions.
  1424. \\[pascal-show-all]\t- Show the whole buffer.
  1425. \\[pascal-hide-other-defuns]\
  1426. \t- Hide everything but the current function (function under the cursor).
  1427. \\[pascal-outline]\t- Leave pascal-outline-mode."
  1428.   (interactive "P")
  1429.   (setq pascal-outline-mode
  1430.     (if (null arg) (not pascal-outline-mode) t))
  1431.   (if (boundp 'redraw-mode-line)
  1432.       (redraw-mode-line))
  1433.   (if pascal-outline-mode
  1434.       (progn
  1435.     (setq selective-display t)
  1436.     (use-local-map pascal-outline-map))
  1437.     (progn
  1438.       (setq selective-display nil)
  1439.       (pascal-show-all)
  1440.       (use-local-map pascal-mode-map))))
  1441.  
  1442. (defun pascal-outline-change (b e pascal-flag)
  1443.   (let ((modp (buffer-modified-p)))
  1444.     (unwind-protect
  1445.     (subst-char-in-region b e (if (= pascal-flag ?\n) 
  1446.                       ?\^M ?\n) pascal-flag)
  1447.       (set-buffer-modified-p modp))))
  1448.  
  1449. (defun pascal-show-all ()
  1450.   "Show all of the text in the buffer."
  1451.   (interactive)
  1452.   (pascal-outline-change (point-min) (point-max) ?\n))
  1453.  
  1454. (defun pascal-hide-other-defuns ()
  1455.   "Show only the current defun."
  1456.   (interactive)
  1457.   (save-excursion
  1458.     (let ((beg (progn (if (not (looking-at "\\(function\\|procedure\\)\\>"))
  1459.               (pascal-beg-of-defun))
  1460.               (point)))
  1461.       (end (progn (pascal-end-of-defun)
  1462.               (backward-sexp 1)
  1463.               (search-forward "\n\\|\^M" nil t)
  1464.               (point)))
  1465.       (opoint (point-min)))
  1466.       (goto-char (point-min))
  1467.  
  1468.       ;; Hide all functions before current function
  1469.       (while (re-search-forward "^\\(function\\|procedure\\)\\>" beg 'move)
  1470.     (pascal-outline-change opoint (1- (match-beginning 0)) ?\^M)
  1471.     (setq opoint (point))
  1472.     ;; Functions may be nested
  1473.     (if (> (progn (pascal-end-of-defun) (point)) beg)
  1474.         (goto-char opoint)))
  1475.       (if (> beg opoint)
  1476.       (pascal-outline-change opoint (1- beg) ?\^M))
  1477.  
  1478.       ;; Show current function
  1479.       (pascal-outline-change beg end ?\n)
  1480.       ;; Hide nested functions
  1481.       (forward-char 1)
  1482.       (while (re-search-forward "^\\(function\\|procedure\\)\\>" end 'move)
  1483.     (setq opoint (point))
  1484.     (pascal-end-of-defun)
  1485.     (pascal-outline-change opoint (point) ?\^M))
  1486.  
  1487.       (goto-char end)
  1488.       (setq opoint end)
  1489.  
  1490.       ;; Hide all function after current function
  1491.       (while (re-search-forward "^\\(function\\|procedure\\)\\>" nil 'move)
  1492.     (pascal-outline-change opoint (1- (match-beginning 0)) ?\^M)
  1493.     (setq opoint (point))
  1494.     (pascal-end-of-defun))
  1495.       (pascal-outline-change opoint (point-max) ?\^M)
  1496.  
  1497.       ;; Hide main program
  1498.       (if (< (progn (forward-line -1) (point)) end)
  1499.       (progn
  1500.         (goto-char beg)
  1501.         (pascal-end-of-defun)
  1502.         (backward-sexp 1)
  1503.         (pascal-outline-change (point) (point-max) ?\^M))))))
  1504.  
  1505. (defun pascal-outline-next-defun ()
  1506.   "Move to next function/procedure, hiding all others."
  1507.   (interactive)
  1508.   (pascal-end-of-defun)
  1509.   (pascal-hide-other-defuns))
  1510.  
  1511. (defun pascal-outline-prev-defun ()
  1512.   "Move to previous function/procedure, hiding all others."
  1513.   (interactive)
  1514.   (pascal-beg-of-defun)
  1515.   (pascal-hide-other-defuns))
  1516.  
  1517. (defun pascal-outline-goto-defun ()
  1518.   "Move to specified function/procedure, hiding all others."
  1519.   (interactive)
  1520.   (pascal-goto-defun)
  1521.   (pascal-hide-other-defuns))
  1522.  
  1523. ;;; pascal.el ends here
  1524.