Emacs+Matlab快速配置

=================================前言,要马上装好的请跳过==============================================================

又是大乱斗。。。又要改.emacs。。。。恨死。。。能不能直接安装。。。。


找到以下中文博客(虽然有一篇用英文写的。。。):

matlab emacs  点击打开链接

Emacs的Matlab模式 点击打开链接

emacs之matlab配置 点击打开链接

都比较失望。。。改这个改那个的。。

然后google了一下,发现宝物了:

MATLAB-Emacs integration is back  点击打开链接

让人眼前一亮的就是安!装!包!,而且还可以替换Matlab内置的编辑器,09年的文章哈。。。。我打算重点弄一下这个,粗略一看,动用.emacs的部分,只加4句话,这个我太喜欢了。


无奈。。。项目好像停止了,去了SourceForge,一个文件也没有了。。。点击打开链接

但是从另外的地方找到了,CVS什么的,从这篇文章来的:matlab-shell in emacs 点击打开链接 ,下载链接点击打开链接

为了备用,我存一个代码片吧(太长,附在最后)。

=================================前言结束===================================================================================

1.把matlab.el(应该是经过编译的吧,我是在做Python的el时发现这个需要python-mode.el编译)放到主文件夹, 然后终端里输入

 sudo cp ~/matlab.el /usr/share/emacs/site-lisp

2.打开.emacs,在文件尾部加入以下语句(原封不动拷过去):

(autoload 'matlab-mode "matlab" "Enter MATLAB mode." t)
  (setq auto-mode-alist (cons '("\\.m\\'" . matlab-mode) auto-mode-alist))
  (autoload 'matlab-shell "matlab" "Interactive MATLAB mode." t)

3.重新打开Emacs,随便开个m文件,效果如下:


好了,Matlab模式了,成功~~~


===========================================附录===============================

我的.emacs文件(两段分别为:matrix主题;Matlab读取):

(add-to-list 'load-path "~/.emacs.d/")
      (require 'color-theme)
      (color-theme-initialize)
      (color-theme-matrix)

(autoload 'matlab-mode "matlab" "Enter MATLAB mode." t)
  (setq auto-mode-alist (cons '("\\.m\\'" . matlab-mode) auto-mode-alist))
  (autoload 'matlab-shell "matlab" "Interactive MATLAB mode." t)



matlab.el代码:

;;; matlab.el --- major mode for MATLAB(R) dot-m files
;;
;; Author: Matt Wette ,
;;         Eric M. Ludlam 
;; Maintainer: Eric M. Ludlam 
;; Created: 04 Jan 91
;; Keywords: MATLAB(R)
;; Version:

(defconst matlab-mode-version "3.3.2"
  "Current version of MATLAB(R) mode.")

;;
;; Copyright (C) 2004-2010 The Mathworks, Inc
;; Copyright (C) 1997-2004 Eric M. Ludlam: The MathWorks, Inc
;; Copyright (C) 1991-1997 Matthew R. Wette
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to
;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
;;
;;; Commentary:
;;
;; This major mode for GNU Emacs provides support for editing MATLAB(R) dot-m
;; files.  It automatically indents for block structures (including nested
;; functions), line continuations (e.g., ...), and comments.
;;
;; Additional features include auto-fill including auto-additions of
;; ellipsis for commands, and even strings.  Block/end construct
;; highlighting as you edit.  Primitive code-verification and
;; identification.  Templates and other code editing functions.
;; Advanced symbol completion.  Code highlighting via font-lock.
;; There are many navigation commands that let you move across blocks
;; of code at different levels.
;;
;; Lastly, there is support for running MATLAB(R) in an Emacs buffer,
;; with full shell history and debugger support (when used with the db
;; commands.)  The shell can be used as an online help while editing
;; code, providing help on functions, variables, or running arbitrary
;; blocks of code from the buffer you are editing.

;;; Code:

(require 'easymenu)
(require 'tempo)
(require 'derived)

;; compatibility
(if (string-match "X[Ee]macs" emacs-version)
    (progn
      (defalias 'matlab-make-overlay 'make-extent)
      (defalias 'matlab-overlay-put 'set-extent-property)
      (defalias 'matlab-overlay-get 'extent-property)
      (defalias 'matlab-delete-overlay 'delete-extent)
      (defalias 'matlab-overlay-start 'extent-start-position)
      (defalias 'matlab-overlay-end 'extent-end-position)
      (defalias 'matlab-previous-overlay-change 'previous-extent-change)
      (defalias 'matlab-next-overlay-change 'next-extent-change)
      (defalias 'matlab-overlays-at
	(lambda (pos) (extent-list nil pos pos)))
      (defalias 'matlab-cancel-timer 'delete-itimer)
      (defun matlab-run-with-idle-timer (secs repeat function &rest args)
	(condition-case nil
	    (apply 'start-itimer
		   "matlab" function secs
		   (if repeat secs nil) t
		   t (car args))
	  (error
	   ;; If the above doesn't work, then try this old version of
	   ;; start itimer.
	   (start-itimer "matlab" function secs (if repeat secs nil)))))
      )
  (defalias 'matlab-make-overlay 'make-overlay)
  (defalias 'matlab-overlay-put 'overlay-put)
  (defalias 'matlab-overlay-get 'overlay-get)
  (defalias 'matlab-delete-overlay 'delete-overlay)
  (defalias 'matlab-overlay-start 'overlay-start)
  (defalias 'matlab-overlay-end 'overlay-end)
  (defalias 'matlab-previous-overlay-change 'previous-overlay-change)
  (defalias 'matlab-next-overlay-change 'next-overlay-change)
  (defalias 'matlab-overlays-at 'overlays-at)
  (defalias 'matlab-cancel-timer 'cancel-timer)
  (defalias 'matlab-run-with-idle-timer 'run-with-idle-timer)
  )

(cond ((fboundp 'point-at-bol)
       (defalias 'matlab-point-at-bol 'point-at-bol)
       (defalias 'matlab-point-at-eol 'point-at-eol))
      ;; Emacs 20.4
      ((fboundp 'line-beginning-position)
       (defalias 'matlab-point-at-bol 'line-beginning-position)
       (defalias 'matlab-point-at-eol 'line-end-position))
      (t
       (defmacro matlab-point-at-bol ()
	 (save-excursion (beginning-of-line) (point)))
       (defmacro matlab-point-at-eol ()
	 (save-excursion (end-of-line) (point)))))

(defmacro matlab-run-in-matlab-mode-only (&rest body)
  "Execute BODY only if the active buffer is a MATLAB(R) M-file buffer."
  `(if (eq major-mode 'matlab-mode)
       (progn
	,@body)
     (error "This command works only in a MATLAB M-file buffer")))

(defun matlab-with-emacs-link ()
  "Return non-nil if Emacs Link is running and user wants to use it."
  (and (featurep 'matlab-eei)
       matlab-use-eei
       matlab-eei-process))
f
;;; User-changeable variables =================================================

;; Variables which the user can change
(defgroup matlab nil
  "MATLAB(R) mode."
  :prefix "matlab-"
  :group 'languages)

(defcustom matlab-indent-level 4
  "*The basic indentation amount in `matlab-mode'."
  :group 'matlab
  :type 'integer)

(defcustom matlab-cont-level 4
  "*Basic indentation after continuation if no other methods are found."
  :group 'matlab
  :type 'integer)

(defcustom matlab-cont-requires-ellipsis t
  "*Specify if ellipses are required at the end of a line for continuation.
Future versions of Matlab may not require ellipses ... , so a heuristic
determining if there is to be continuation is used instead."
  :group 'matlab
  :type 'integer)

(defcustom matlab-case-level '(2 . 2)
  "*How far to indent case/otherwise statements in a switch.
This can be an integer, which is the distance to indent the CASE and
OTHERWISE commands, and how far to indent commands appearing in CASE
and OTHERWISE blocks.  It can also be a cons cell which is of form
  (CASEINDENT . COMMANDINDENT)
where CASEINDENT is the indentation of the CASE and OTHERWISE
statements, and COMMANDINDENT is the indentation of commands appearing
after the CASE or OTHERWISE command.

Note: Currently a bug exists if:
  CASEINDENT+COMMANDINDENT != `matlab-indent-level'
so if you customize these variables, follow the above rule, and you
should be ok."
  :group 'matlab
  :type 'sexp)

(defcustom matlab-indent-function-body 'guess
  "*If non-nil, indent body of function.
If the global value is nil, do not indent function bodies.
If the global value is t, always indent function bodies.
If the global value is 'guess, then the local value will be set to
either nil or t when the MATLAB mode is started in a buffer based on the
file's current indentation.
If the global value is 'MathWorks-Standard, then the local value is not
changed, and functions are indented based on `matlab-functions-have-end'."
  :group 'matlab
  :type '(choice (const :tag "Always" t)
		 (const :tag "Never" nil)
		 (const :tag "Guess" 'guess)
                 (const :tag "MathWorks Standard"
                        'MathWorks-Standard))
  )

(make-variable-buffer-local 'matlab-indent-function-body)

(defcustom matlab-functions-have-end nil
  "*If non-nil, functions-have-end minor mode is on by default."
  :group 'matlab
  :type 'boolean)

(make-variable-buffer-local 'matlab-functions-have-end)

(defun matlab-toggle-functions-have-end ()
  (interactive)
  (matlab-toggle-functions-have-end-minor-mode))

;; The following minor mode is on if and only if the above variable is true;
(easy-mmode-define-minor-mode matlab-functions-have-end-minor-mode
  "Toggle functions-have-end minor mode, indicating function/end pairing."
  nil
  (condition-case nil ;; avoid parse error on xemacs
      (eval (read "#(\" function...end\" 0 15 (face (font-lock-keyword-face) fontified t))"))
    (error " function...end"))
  nil ; empty mode-map
  ;; body of matlab-functions-have-end-minor-mode
  (if matlab-functions-have-end-minor-mode
      (setq matlab-functions-have-end t)
    (setq matlab-functions-have-end nil)
    )
)

(defun matlab-do-functions-have-end-p ()
  "Non-nil if the first function in the current buffer terminates with end."
  (save-excursion
    (goto-char (point-min))
    (if (re-search-forward matlab-defun-regex nil t)
        (let ((matlab-functions-have-end t))
          (beginning-of-line)
          (condition-case nil
              (progn (matlab-forward-sexp) t)
            (error nil))
          )
      nil
      )
    ))

(defun matlab-toggle-functions-have-end-minor-mode ()
  (matlab-functions-have-end-minor-mode)
  (if (and matlab-functions-have-end-minor-mode (not (eq major-mode 'matlab-mode)))
      (progn
	(matlab-functions-have-end-minor-mode -1)
	(error "functions-have-end minor mode is only for MATLAB Major mode")))
  (setq matlab-functions-have-end matlab-functions-have-end-minor-mode))

(defun matlab-indent-function-body-p ()
  "Non-nil if functions bodies are indented. 
See `matlab-indent-function-body' variable."
  (if (eq matlab-indent-function-body 'MathWorks-Standard)
      ;; Dec '09
      ;; The MathWorks standard is the same as if functions have end.
      matlab-functions-have-end
    ;; Else, just return the variable.
    matlab-indent-function-body))

(defcustom matlab-indent-past-arg1-functions
  "[sg]et\\(_param\\)?\\|waitfor"
  "*Regex describing functions whose first arg is special.
This specialness means that all following parameters which appear on
continued lines should appear indented to line up with the second
argument, not the first argument."
  :group 'matlab
  :type 'string)

(defcustom matlab-arg1-max-indent-length 15
  "*The maximum length to indent when indenting past arg1.
If arg1 is exceptionally long, then only this number of characters
will be indented beyond the open paren starting the parameter list.")

(defcustom matlab-maximum-indents '(;; = is a convenience. Don't go too far
				    (?= . (10 . 4))
				    ;; Fns should provide hard limits
				    (?\( . 50)
				    ;; Matrix/Cell arrays
				    (?\[ . 20)
				    (?\{ . 20))
  "Alist of maximum indentations when lining up code.
Each element is of the form (CHAR . INDENT) where char is a character
the indent engine is using, and INDENT is the maximum indentation
allowed.  Indent could be of the form (MAXIMUM . INDENT), where
MAXIMUM is the maximum allowed calculated indent, and INDENT is the
amount to use if MAXIMUM is reached."
  :group 'matlab
  :type '(repeat (cons (character :tag "Open List Character")
		       (sexp :tag "Number (max) or cons (max indent)"))))

(defcustom matlab-handle-simulink t
  "*If true, add in a few simulink customizations.
This variable's state is mostly useful when set at load time when
simulink font lock keywords can be removed.  This will handle
additional cases as the need arrises."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-auto-fill t
  "*If true, set variable `auto-fill-function' to our function at startup."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-fill-fudge 10
  "Number of characters around `fill-column' we can fudge filling.
Basically, there are places that are very convenient to fill at, but
might not be the closest fill spot, or occur after `fill-column'.
If they occur within this fudge factor, we will use them.
Also, if none of the above occur, and we find a symbol to break at,
but an open paren (group) starts or ends within this fudge factor,
move there to boost the amount of fill leverage we can get."
  :group 'matlab
  :type 'integer)

(defcustom matlab-fill-fudge-hard-maximum 79
  "The longest line allowed when auto-filling code.
This overcomes situations where the `fill-column' plus the
`matlab-fill-fudge' is greater than some hard desired limit."
  :group 'matlab
  :type 'integer)

(defcustom matlab-elipsis-string "..."
  "Text used to perform continuation on code lines.
This is used to generate and identify continuation lines.")

(defcustom matlab-fill-code t
  "*If true, `auto-fill-mode' causes code lines to be automatically continued."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-fill-count-ellipsis-flag t
  "*Non-nil means to count the ellipsis when auto filling.
This effectively shortens the `fill-column' by the length of
`matlab-elipsis-string'.")

(defcustom matlab-fill-strings-flag t
  "*Non-nil means that when auto-fill is on, strings are broken across lines.
If `matlab-fill-count-ellipsis-flag' is non nil, this shortens the
`fill-column' by the length of `matlab-elipsis-string'.")

(defcustom matlab-comment-column 40
  "*The goal comment column in `matlab-mode' buffers."
  :group 'matlab
  :type 'integer)

(defcustom matlab-comment-anti-indent 0
  "*Amount of anti-indentation to use for comments in relation to code."
  :group 'matlab
  :type 'integer)

(defcustom matlab-comment-line-s "% "
  "*String to start comment on line by itself."
  :group 'matlab
  :type 'string)

(defcustom matlab-comment-on-line-s "% "
  "*String to start comment on line with code."
  :group 'matlab
  :type 'string)

(defcustom matlab-comment-region-s "% $$$ "
  "*String inserted by \\[matlab-comment-region] at start of each line in \
region."
  :group 'matlab
  :type 'string)

(defcustom matlab-verify-on-save-flag t
  "*Non-nil means to verify M whenever we save a file."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-mode-verify-fix-functions
  '(matlab-mode-vf-functionname)
  "List of function symbols which perform a verification and fix to M code.
Each function gets no arguments, and returns nothing.  They can move
point, but it will be restored for them."
  :group 'matlab
  :type '(repeat (choice :tag "Function: "
			 '(matlab-mode-vf-functionname
			   matlab-mode-vf-block-matches-forward
			   matlab-mode-vf-block-matches-backward
			   matlab-mode-vf-quiesce-buffer
			   ))))

(defcustom matlab-block-verify-max-buffer-size 50000
  "*Largest buffer size allowed for block verification during save."
  :group 'matlab
  :type 'integer)

;; It is time to disable this.
(defcustom matlab-vers-on-startup nil
  "*If non-nil, show the version number on startup."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-highlight-block-match-flag t
  "*Non-nil means to highlight the matching if/end/whatever.
The highlighting only occurs when the cursor is on a block start or end
keyword."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-show-periodic-code-details-flag nil
  "*Non-nil means to show code details in the minibuffer.
This will only work if `matlab-highlight-block-match-flag' is non-nil."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-use-eei t
  "*Use Emacs Link for save-and-go and run-region."
  :group 'matlab
  :type 'boolean)

(defcustom matlab-mode-hook nil
  "*List of functions to call on entry to MATLAB mode."
  :group 'matlab
  :type 'hook)

(defcustom matlab-completion-technique 'complete
  "*How the `matlab-complete-symbol' interfaces with the user.
Valid values are:

'increment - which means that new strings are tried with each
             successive call until all methods are exhausted.
             (Similar to `hippie-expand'.)
'complete  - Which means that if there is no single completion, then
             all possibilities are displayed in a completion buffer."
  :group 'matlab
  :type '(radio (const :tag "Incremental completion (hippie-expand)."
		       increment)
		(const :tag "Show completion buffer."
		       complete)))

(defcustom matlab-show-mlint-warnings nil
  "*If non-nil, show mlint warnings."
  :group 'matlab
  :type 'boolean)

(make-variable-buffer-local 'matlab-show-mlint-warnings)

(defcustom matlab-highlight-cross-function-variables nil
  "*If non-nil, highlight cross-function variables."
  :group 'matlab
  :type 'boolean)

(make-variable-buffer-local 'matlab-highlight-cross-function-variables)

(defcustom matlab-return-add-semicolon nil
  "*If non nil, check to see a semicolon is needed when RET is pressed."
  :group 'matlab
  :type 'boolean)

(make-variable-buffer-local 'matlab-return-add-semicolon)

;; Load in the region we use for highlighting stuff.
(if (and (featurep 'custom) (fboundp 'custom-declare-variable))

    (let ((l-region-face (if (facep 'region) 'region 'zmacs-region)))
      ;; If we have custom, we can make our own special face like this
      (defface matlab-region-face
	(list
	 (list t
	       (list :background (face-background l-region-face)
		     :foreground (face-foreground l-region-face))))
	"*Face used to highlight a matlab region."
	:group 'matlab))

  ;; If we do not, then we can fake it by copying 'region.
  (cond ((facep 'region)
	 (copy-face 'region 'matlab-region-face))
	(t
	 (copy-face 'zmacs-region 'matlab-region-face))))

(defvar matlab-unterminated-string-face 'matlab-unterminated-string-face
  "Self reference for unterminated string face.")

(defvar matlab-simulink-keyword-face 'matlab-simulink-keyword-face
  "Self reference for simulink keywords.")

(defvar matlab-nested-function-keyword-face 'matlab-nested-function-keyword-face
  "Self reference for nested function/end keywords.")

(defvar matlab-cross-function-variable-face 'matlab-cross-function-variable-face
  "Self reference for cross-function variables.")

(defvar matlab-cellbreak-face 'matlab-cellbreak-face
  "Self reference for cellbreaks.")

(defun matlab-font-lock-adjustments ()
  "Make adjustments for font lock.
If font lock is not loaded, lay in wait."
  (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
	
      (progn
	(defface matlab-unterminated-string-face
	  (list
	   (list t
		 (list :background (face-background font-lock-string-face)
		       :foreground (face-foreground font-lock-string-face)
		       :underline t)))
	  "*Face used to highlight unterminated strings."
	  :group 'matlab)
	(defface matlab-simulink-keyword-face
	  (list
	   (list t
		 (list :background (face-background font-lock-type-face)
		       :foreground (face-foreground font-lock-type-face)
		       :underline t)))
	  "*Face used to highlight simulink specific functions."
	  :group 'matlab)
        (defface matlab-nested-function-keyword-face
	  (list
	   (list t
		 (list :slant  'italic)))
          "*Face to use for cross-function variables.")
        (defface matlab-cross-function-variable-face
	  (list
	   (list t
		 (list :weight 'bold
                       :slant  'italic)))
          "*Face to use for cross-function variables."
	  :group 'matlab)
	(defface matlab-cellbreak-face
	  (list
	   (list t
		 (list :background (face-background font-lock-comment-face)
		       :foreground (face-foreground font-lock-comment-face)
		       :overline t
		       :bold t)))
	  "*Face to use for cellbreak %% lines.")
	)
      
    ;; Now, lets make the unterminated string face
    (cond ((facep 'font-lock-string-face)
	   (copy-face 'font-lock-string-face
		      'matlab-unterminated-string-face))
	  (t
	   (make-face 'matlab-unterminated-string-face)))
    (set-face-underline-p 'matlab-unterminated-string-face t)
    
    ;; Now make some simulink faces
    (cond ((facep 'font-lock-type-face)
	   (copy-face 'font-lock-type-face 'matlab-simulink-keyword-face))
	  (t
	   (make-face 'matlab-simulink-keyword-face)))
    (set-face-underline-p 'matlab-simulink-keyword-face t)
    
    ;; Now make some nested function/end keyword faces
    (cond ((facep 'font-lock-type-face)
	   (copy-face 'font-lock-type-face 'matlab-nested-function-keyword-face))
	  (t
	   (make-face 'matlab-nested-function-keyword-face)))
    
    ;; Now make some cross-function variable faces
    (cond ((facep 'font-lock-type-face)
	   (copy-face 'font-lock-type-face 'matlab-cross-function-variable-face))
	  (t
	   (make-face 'matlab-cross-function-variable-face)))
    (set-face-bold-p 'matlab-cross-function-variable-face t)

    ;; Now make some cellbreak variable faces
    (cond ((facep 'font-comment-face)
	   (copy-face 'font-lock-comment-face 'matlab-cellbreak-face))
	  (t
	   (make-face 'matlab-cellbreak-face)))
    (set-face-bold-p 'matlab-cellbreak-face t)
    (condition-case nil
	(set-face-attribute 'matlab-cellbreak-face nil :overline t)
      (error nil))
    )
  (remove-hook 'font-lock-mode-hook 'matlab-font-lock-adjustments))

;; Make the adjustments for font lock after it's loaded.
;; I found that eval-after-load was unreliable.
(if (featurep 'font-lock)
    (matlab-font-lock-adjustments)
  (add-hook 'font-lock-mode-hook 'matlab-font-lock-adjustments))

f
;;; MATLAB mode variables =====================================================

(defvar matlab-tempo-tags nil
  "List of templates used in MATLAB mode.")

;; syntax table
(defvar matlab-mode-syntax-table
  (let ((st (make-syntax-table (standard-syntax-table))))
    (modify-syntax-entry ?_  "_" st)
    (modify-syntax-entry ?%  "<" st)
    (modify-syntax-entry ?\n ">" st)
    (modify-syntax-entry ?\\ "." st)
    (modify-syntax-entry ?\t " " st)
    (modify-syntax-entry ?+  "." st)
    (modify-syntax-entry ?-  "." st)
    (modify-syntax-entry ?*  "." st)
    (modify-syntax-entry ?'  "." st)
    (modify-syntax-entry ?/  "." st)
    (modify-syntax-entry ?=  "." st)
    (modify-syntax-entry ?<  "." st)
    (modify-syntax-entry ?>  "." st)
    (modify-syntax-entry ?&  "." st)
    (modify-syntax-entry ?|  "." st)
    st)
  "The syntax table used in `matlab-mode' buffers.")

(defvar matlab-mode-special-syntax-table
  (let ((st (copy-syntax-table matlab-mode-syntax-table)))
    ;; Make _ a part of words so we can skip them better
    (modify-syntax-entry ?_  "w" st)
    st)
  "The syntax table used when navigating blocks.")

;; abbrev table
(defvar matlab-mode-abbrev-table nil
  "The abbrev table used in `matlab-mode' buffers.")

(define-abbrev-table 'matlab-mode-abbrev-table ())
f
;;; Keybindings ===============================================================

(defvar matlab-help-map
  (let ((km (make-sparse-keymap)))
    (define-key km "r" 'matlab-shell-run-command)
    (define-key km "f" 'matlab-shell-describe-command)
    (define-key km "a" 'matlab-shell-apropos)
    (define-key km "v" 'matlab-shell-describe-variable)
    (define-key km "t" 'matlab-shell-topic-browser)
    km)
  "The help key map for `matlab-mode' and `matlab-shell-mode'.")

(defvar matlab-insert-map
  (let ((km (make-sparse-keymap)))
    (define-key km "c" 'matlab-insert-next-case)
    (define-key km "e" 'matlab-insert-end-block)
    (define-key km "i" 'tempo-template-matlab-if)
    (define-key km "I" 'tempo-template-matlab-if-else)
    (define-key km "f" 'tempo-template-matlab-for)
    (define-key km "s" 'tempo-template-matlab-switch)
    (define-key km "t" 'tempo-template-matlab-try)
    (define-key km "w" 'tempo-template-matlab-while)
    (define-key km "F" 'tempo-template-matlab-function)
    (define-key km "'" 'matlab-stringify-region)
    ;; Not really inserts, but auto coding stuff
    (define-key km "\C-s" 'matlab-ispell-strings)
    (define-key km "\C-c" 'matlab-ispell-comments)
    km)
  "Keymap used for inserting simple texts based on context.")

;; mode map
(defvar matlab-mode-map
  (let ((km (make-sparse-keymap)))
    (define-key km [return] 'matlab-return)
    (define-key km "%" 'matlab-electric-comment)
    (define-key km "\C-c;" 'matlab-comment-region)
    (define-key km "\C-c:" 'matlab-uncomment-region)
    (define-key km [(control c) return] 'matlab-comment-return)
    (define-key km [(control c) (control c)] matlab-insert-map)
    (define-key km [(control c) (control f)] 'matlab-fill-comment-line)
    (define-key km [(control c) (control j)] 'matlab-justify-line)
    (define-key km [(control c) (control q)] 'matlab-fill-region)
    (define-key km [(control c) (control s)] 'matlab-shell-save-and-go)
    (define-key km [(control c) (control r)] 'matlab-shell-run-region)
    (define-key km [(meta control return)] 'matlab-shell-run-cell)
    (define-key km [(control c) (control t)] 'matlab-show-line-info)
    (define-key km [(control c) ?. ] 'matlab-find-file-on-path)
    (define-key km [(control h) (control m)] matlab-help-map)
    (define-key km [(control j)] 'matlab-linefeed)
    (define-key km "\M-\r" 'newline)
    (define-key km [(meta \;)] 'matlab-comment)
    (define-key km [(meta q)] 'matlab-fill-paragraph)
    (define-key km [(meta a)] 'matlab-beginning-of-command)
    (define-key km [(meta e)] 'matlab-end-of-command)
    (define-key km [(meta j)] 'matlab-comment-line-break-function)
    (define-key km [(meta s)] 'matlab-show-matlab-shell-buffer)
    (define-key km "\M-\t" 'matlab-complete-symbol)
    (define-key km [(meta control f)] 'matlab-forward-sexp)
    (define-key km [(meta control b)] 'matlab-backward-sexp)
    (define-key km [(meta control q)] 'matlab-indent-sexp)
    (define-key km [(meta control a)] 'matlab-beginning-of-defun)
    (define-key km [(meta control e)] 'matlab-end-of-defun)
    (if (string-match "XEmacs" emacs-version)
	(define-key km [(control meta button1)] 'matlab-find-file-click)
      (define-key km [(control meta mouse-2)] 'matlab-find-file-click))
    (substitute-key-definition 'comment-region 'matlab-comment-region
			       km) ; global-map ;torkel
    km)
  "The keymap used in `matlab-mode'.")
f
;;; Font locking keywords =====================================================

(defvar matlab-string-start-regexp "\\(^\\|[^]})a-zA-Z0-9_.']\\)"
  "Regexp used to represent the character before the string char '.
The ' character has restrictions on what starts a string which is needed
when attempting to understand the current context.")

;; To quote a quote, put two in a row, thus we need an anchored
;; first quote.  In addition, we don't want to color strings in comments.
(defvar matlab-string-end-regexp "[^'\n]*\\(''[^'\n]*\\)*'"
  "Regexp used to represent the character pattern for ending a string.
The ' character can be used as a transpose, and can transpose transposes.
Therefore, to end, we must check all that goop.")

(defun matlab-font-lock-string-match-normal (limit)
  "When font locking strings, call this function for normal strings.
Argument LIMIT is the maximum distance to scan."
  (matlab-font-lock-string-match-here
   (concat matlab-string-start-regexp
	   "\\('" matlab-string-end-regexp "\\)"
	   "\\([^']\\|$\\)")
   limit))

(defun matlab-font-lock-string-match-unterminated (limit)
  "When font locking strings, call this function for normal strings.
Argument LIMIT is the maximum distance to scan."
  (matlab-font-lock-string-match-here
   (concat matlab-string-start-regexp "\\('[^'\n]*\\(''[^'\n]*\\)*\\)$")
   limit))

(defun matlab-font-lock-string-match-here (regex limit)
  "When font-locking strings, call this function to determine a match.
Argument REGEX is the expression to scan for.  Match 2 must be the string.
Argument LIMIT is the maximum distance to scan."
  (let (e)
    (while (and (re-search-forward regex limit t)
		(progn
		  ;; This gets us out of a comment after the string.
		  (setq e (match-end 2))
		  (goto-char (match-beginning 2))
		  (prog1
		      (or (matlab-cursor-in-comment)
			  (if (bolp) nil
			    (save-excursion
			      (forward-char -1)
			      (matlab-cursor-in-string))))
		    (goto-char e))))
      (setq e nil))
    (if (not e)
	nil
      (goto-char e)
      t)))

(defun matlab-font-lock-comment-match (limit)
  "When font-locking comments, call this function to determine a match.
Argument LIMIT is the maximum distance to scan."
  (let (e)
    (while (and (re-search-forward "\\(%[^%\n]*\\)" limit t)
		(progn
		  (setq e (match-end 1))
		  (member (get-text-property (match-beginning 0) 'face)
			  '(font-lock-string-face
			    matlab-unterminated-string-face))))
      (setq e nil))
    (if (not e)
	nil
      (goto-char e)
      t)))

(defun matlab-find-unreachable-code (limit)
  "Find code that is if'd out with if(0) or if(false), and mark it as a comment.
The if(0) and else/end construct should be highlighted differently.
Argument LIMIT is the maximum distance to search."
  (if (and (< (point) limit)
	   (re-search-forward
	    "\\<\\(if\\>\\s-*(?\\s-*\\(0\\|false\\)\\s-*)?$\\)"
	    limit t))
      (let ((b1 (match-beginning 1))
	    (e1 (match-end 1))
	    (b2 nil) (e2 nil)
	    (b3 nil) (e3 nil))
	(goto-char b1)
	(condition-case nil
	    (progn
	      ;; Go forward over the matlab sexp.  Include scanning
	      ;; for ELSE since parts of the ELSE block are not
	      ;; `commented out'.
	      (matlab-forward-sexp t)
	      (forward-word -1)
	      ;; Is there an ELSE in this block?
	      (if (looking-at (matlab-block-mid-re))
		  (progn
		    (setq b3 (match-beginning 0)
			  e3 (match-end 0))
		    ;; Now find the REAL end.
		    (matlab-forward-sexp)
		    (forward-word -1)))
	      ;; End of block stuff
	      (if (looking-at (matlab-block-end-re))
		  (progn
		    (setq b2 (match-beginning 0)
			  e2 (match-end 0))
		    ;; make sure something exists...
		    (if (not b3) (setq b3 b2 e3 e2)))
		(error "Eh?"))
	      ;; Ok, build up some match data.
	      (set-match-data
	       (list b1 e2		;the real deal.
		     b1 e1		;if (0)
		     b2 e2		;end
		     b3 e3		;else (if applicable.)
		     b1 e3))		;body commented out.
	      t)
	  (error nil)))))

(defun matlab-font-lock-nested-function-keyword-match (limit)
  "Find next nested function/end keyword for font-lock.
Argument LIMIT is the maximum distance to search."
; Because of the way overlays are setup, the cursor will be sitting
; on either a "function" or "end" keyword.
  (catch 'result
    (let ((pos (point))
          overlays)
      (while (< pos limit)
        (setq overlays (matlab-overlays-at pos))
        (while overlays
          (let ((overlay (car overlays)))
	    (when (matlab-overlay-get overlay 'nested-function)
	      (when (= pos (matlab-overlay-start overlay))
		(goto-char pos)
		;; The following line presumably returns true.
		(throw 'result (re-search-forward "function" (+ pos 8) t)))
	      (let ((end-of-overlay (- (matlab-overlay-end overlay) 3)))
		(when (<= pos end-of-overlay)
		  (goto-char end-of-overlay)
		  (throw 'result
			 (re-search-forward "end" (+ end-of-overlay 3) t))))))
          (setq overlays (cdr overlays)))
        (setq pos (matlab-next-overlay-change pos)))
      nil ;; no matches, stop
      )))

(defun matlab-font-lock-cross-function-variables-match (limit)
  "Find next cross-function variable for font-lock.
Argument LIMIT is the maximum distance to search."
  (catch 'result
    (let ((pos (point))
          overlays variables)
      (while (< pos limit)
        (let ((overlays (matlab-overlays-at pos)))
	  (while overlays
	    (let ((overlay (car overlays)))
	      (setq variables (matlab-overlay-get
			       overlay 'cross-function-variables))
	      (if variables
		  (progn
		    (goto-char pos)
		    (setq pos (min limit (matlab-overlay-end overlay)))
		    (if (re-search-forward variables pos t)
			(progn
			  (throw 'result t))))))
	    (setq overlays (cdr overlays))))
        (setq pos (matlab-next-overlay-change pos)))
      nil ;; no matches, stop
      )))

(defun matlab-find-block-comments (limit)
  "Find code that is commented out with %{ until %}.
Argument LIMIT is the maximum distance to search."
  (if (and (< (point) limit)
	   (re-search-forward "%{" limit t))
      (let ((b1 (match-beginning 0))
	    (e1 (match-end 0))
	    (b2 nil) (e2 nil)
	    (b3 nil) (e3 nil))
	(goto-char b1)
	(forward-char -1)
	(when (not (matlab-cursor-in-comment))
	  (setq b2 (re-search-forward "%}" limit t))
	  (when b2
	    (setq b2 (match-beginning 0)
		  e2 (match-end 0))
	    (set-match-data
	     (list b1 e2  ; full match
		   b1 e2  ; the full comment
		   b1 e1  ; the block start
		   b2 e2  ; the block end
		   ))
	    t
	    )))))

(defcustom matlab-keyword-list '("global" "persistent" "for" "parfor" "while"
				 "spmd" "if" "elseif" "else"
				 "endfunction" "return" "break" "continue"
				 "switch" "case" "otherwise" "try"
				 "catch" "tic" "toc"
				 ;; MCOS keywords
				 "classdef" "properties" "methods" "enumeration"
				 )
  "List of keywords for MATLAB used in highlighting.
Customizing this variable is only useful if `regexp-opt' is available."
  :group 'matlab
  :type '(repeat (string :tag "Keyword: ")))

(defcustom matlab-handle-graphics-list '("figure" "axes" "axis" "line"
					"surface" "patch" "text" "light"
					"image" "set" "get" "uicontrol"
					"uimenu" "uitoolbar"
					"uitoggletool" "uipushtool"
					"uicontext" "uicontextmenu"
					"setfont" "setcolor")
  "List of handle graphics functions used in highlighting.
Customizing this variable is only useful if `regexp-opt' is available."
  :group 'matlab
  :type '(repeat (string :tag "HG Keyword: ")))

(defcustom matlab-debug-list '("dbstop" "dbclear" "dbcont" "dbdown" "dbmex"
			      "dbstack" "dbstatus" "dbstep" "dbtype" "dbup"
			      "dbquit")
  "List of debug commands used in highlighting.
Customizing this variable is only useful if `regexp-opt' is available."
  :group 'matlab
  :type '(repeat (string :tag "Debug Keyword: ")))

;; font-lock keywords
(defvar matlab-font-lock-keywords
  (list
   ;; String quote chars are also used as transpose, but only if directly
   ;; after characters, numbers, underscores, or closing delimiters.
   '(matlab-font-lock-string-match-normal 2 font-lock-string-face)
   ;; A string with no termination is not currently highlighted.
   ;; This will show that the string needs some attention.
   '(matlab-font-lock-string-match-unterminated
     2 matlab-unterminated-string-face)
   ;; Comments must occur after the string, that way we can check to see
   ;; if the comment start char has occurred inside our string. (EL)
   '(matlab-font-lock-comment-match 1 font-lock-comment-face)
   ;; Various pragmas should be in different colors.
   ;; I think pragmas are always lower case?
   '("%#\\([a-z]+\\)" (1 'bold prepend))
   ;; General keywords
   (list
    (if (fboundp 'regexp-opt)
	(concat "\\<\\(" (regexp-opt matlab-keyword-list) "\\)\\>")
      ;; Original hard-coded value for pre Emacs 20.1
      "\\<\\(break\\|ca\\(se\\|tch\\)\\|e\\(lse\\(\\|if\\)\\|ndfunction\\)\
\\|\\(par\\)?for\\|spmd\\|global\\|if\\|otherwise\\|return\\|switch\\|try\\|while\\|tic\\|toc\\)\\>")
    '(0 font-lock-keyword-face))
   ;; The end keyword is only a keyword when not used as an array
   ;; dereferencing part.
   '("\\(^\\|[;,]\\)[ \t]*\\(end\\)\\b"
     2 (if (matlab-valid-end-construct-p) font-lock-keyword-face nil))
   ;; How about unreachable code?  MUsT BE AFTER KEYWORDS in order to
   ;; get double-highlighting.
   '(matlab-find-unreachable-code
     (1 'underline prepend)		;if part
     (2 'underline prepend)		;end part
     (3 'underline prepend)		;else part (if applicable)
     (4 font-lock-comment-face prepend)	;commented out part.
     )
   ;; block comments need to be commented out too!
   '(matlab-find-block-comments
     (1 font-lock-comment-face prepend) ; commented out
     (2 'underline prepend)
     (3 'underline prepend)		;the comment parts
     )
   ;; Cell mode breaks get special treatment
   '("^\\s-*\\(%%[^\n]*\n\\)" (1 matlab-cellbreak-face append))
   ;; Highlight cross function variables
   '(matlab-font-lock-cross-function-variables-match
     (1 matlab-cross-function-variable-face prepend))
   ;; Highlight nested function/end keywords
   '(matlab-font-lock-nested-function-keyword-match
     (0 matlab-nested-function-keyword-face prepend))
   ;; The global keyword defines some variables.  Mark them.
   '("^\\s-*global\\s-+"
     ("\\(\\w+\\)\\(\\s-*=[^,; \t\n]+\\|[, \t;]+\\|$\\)"
      nil nil (1 font-lock-variable-name-face)))
   ;; Handle graphics stuff
   (list
    (if (fboundp 'regexp-opt)
	(concat "\\<\\(" (regexp-opt matlab-handle-graphics-list) "\\)\\>")
      ;; The original regular expression for pre Emacs 20.1
      "\\<\\(ax\\(es\\|is\\)\\|figure\\|get\\|image\\|li\\(ght\\|ne\\)\\|\
patch\\|s\\(et\\(\\|color\\|font\\)\\|urface\\)\\|text\\|\
ui\\(cont\\(ext\\(\\|menu\\)\\|rol\\)\\|menu\\|\
\\(toggle\\|push\\)tool\\|toolbar\\)\\)\\>")
    '(0 font-lock-type-face))
   )
  "Expressions to highlight in MATLAB mode.")

(defconst matlab-function-arguments
  "\\(([^)]*)\\)?\\s-*\\([,;\n%]\\|$\\)")
 
(defvar matlab-gaudy-font-lock-keywords
  (append
   matlab-font-lock-keywords
   (list
    ;; defining a function, a (possibly empty) list of assigned variables,
    ;; function name, and an optional (possibly empty) list of input variables
    (list (concat "^\\s-*\\(function\\)\\>[ \t\n.]*"
		  "\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*"
		  "=[ \t\n.]*\\(\\sw+\\)[ \t\n.]*"
                  matlab-function-arguments)
	  '(1 font-lock-keyword-face append)
	  '(2 font-lock-variable-name-face append)
	  '(3 font-lock-function-name-face append))
    ;; defining a function, a function name, and an optional (possibly
    ;; empty) list of input variables
    (list (concat "^\\s-*\\(function\\)[ \t\n.]+"
		  "\\(\\sw+\\)[ \t\n.]*"
                  matlab-function-arguments)
	  '(1 font-lock-keyword-face append)
	  '(2 font-lock-function-name-face append))
    ;; Anchor on the function keyword, highlight params
    (list (concat "^\\s-*function\\>[ \t\n.]*"
		  "\\(\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*=[ \t\n.]*\\)?"
		  "\\sw+\\s-*(")
	  '("\\s-*\\(\\sw+\\)\\s-*[,)]" nil nil
	    (1 font-lock-variable-name-face)))
    ;; I like variables for FOR loops
    '("\\<\\(for\\|parfor\\)\\s-+\\(\\sw+\\)\\s-*=\\s-*\
\\(\\([^\n,;%(]+\\|([^\n%)]+)\\)+\\)"
      (1 font-lock-keyword-face)
      (2 font-lock-variable-name-face append)
      (3 font-lock-reference-face append))
    ;; Items after a switch statements are cool
    '("\\<\\(case\\|switch\\)\\s-+\\({[^}\n]+}\\|[^,%\n]+\\)"
      (1 font-lock-keyword-face) (2 font-lock-reference-face))
    ;; How about a few matlab constants such as pi, infinity, and sqrt(-1)?
    ;; The ^>> is in case I use this in an interactive mode someday
    '("\\<\\(eps\\|pi\\|inf\\|Inf\\|NaN\\|nan\\|ans\\|i\\|j\\|^>>\\)\\>"
      1 font-lock-reference-face)
    '("\\<[0-9]\\.?\\(i\\|j\\)\\>" 1 font-lock-reference-face)
    ;; Define these as variables since this is about as close
    ;; as matlab gets to variables
    (list (concat "\\<" matlab-indent-past-arg1-functions "\\s-*")
	  '("(\\s-*\\(\\w+\\)\\s-*\\(,\\|)\\)" nil nil
	    (1 font-lock-variable-name-face)))
    ))
  "Expressions to highlight in MATLAB mode.")

(defvar matlab-really-gaudy-font-lock-keywords
  (append
   matlab-gaudy-font-lock-keywords
   (list
    ;; Since it's a math language, how bout dem symbols?
    '("\\([<>~]=?\\|\\.[/*^']\\|==\\|\\\\|[-!^&|*+\\/~:]\\)"
      1 font-lock-type-face)
    ;; How about references in the HELP text.
    (list (concat "^" matlab-comment-line-s "\\s-*"
		  "\\(\\([A-Z]+\\s-*=\\s-+\\|\\[[^]]+]\\s-*=\\s-+\\|\\)"
		  "\\([A-Z][0-9A-Z]+\\)\\(([^)\n]+)\\| \\)\\)")
	  '(1 font-lock-reference-face prepend))
    (list (concat "^" matlab-comment-line-s "\\s-*"
		  "See also\\s-+")
	  '("\\([A-Z][A-Z0-9]+\\)\\([,.]\\| and\\|$\\) *" nil nil
	    (1 font-lock-reference-face prepend)))
    (list (concat "^" matlab-comment-line-s "\\s-*"
		  "\\(\\$" "Revision" "[^\n$]+\\$\\)")
	  '(1 font-lock-reference-face prepend))
    ;; continuation ellipsis.
    '("[^.]\\(\\.\\.\\.+\\)\\([^\n]*\\)" (1 'underline)
      (2 font-lock-comment-face))
    ;; How about debugging statements?
    ;;'("\\<\\(db\\sw+\\)\\>" 1 'bold)
    (list
     (if (fboundp 'regexp-opt)
	 (concat "\\<\\(" (regexp-opt matlab-debug-list) "\\)\\>")
       ;; pre-regexp-opt days.
       "\\<\\(db\\(c\\(lear\\|ont\\)\\|down\\|mex\\|quit\\|\
st\\(a\\(ck\\|tus\\)\\|ep\\|op\\)\\|type\\|up\\)\\)\\>")
     '(0 'bold)))
   (if matlab-handle-simulink
       ;; Simulink functions, but only if the user wants it.
       (list (list (concat "\\<\\(\\([sg]et_param\\|sim\\([gs]et\\)?\\|"
			   "\\(mld\\|ss\\)[A-Z]\\w+\\)\\|"
			   "\\(new\\|open\\|close\\|save\\|find\\)_system\\|"
			   "\\(add\\|delete\\|replace\\)_\\(block\\|line\\)\\|"
			   "simulink\\|bd\\(root\\|close\\)"
			   "\\)\\>")
		   1 matlab-simulink-keyword-face))
     nil))
  "Expressions to highlight in MATLAB mode.")

(defvar matlab-shell-font-lock-keywords
  (list
   ;; How about Errors?
   '("^\\(Error in\\|Syntax error in\\)\\s-+==>\\s-+\\(.+\\)$"
     (1 font-lock-comment-face) (2 font-lock-string-face))
   ;; and line numbers
   '("^\\(On line [0-9]+\\)" 1 font-lock-comment-face)
   ;; User beep things
   '("\\(\\?\\?\\?[^\n]+\\)" 1 font-lock-comment-face)
   ;; Useful user commands, but not useful programming constructs
   '("\\<\\(demo\\|whatsnew\\|info\\|subscribe\\|help\\|doc\\|lookfor\\|what\
\\|whos?\\|cd\\|clear\\|load\\|save\\|helpdesk\\|helpwin\\)\\>"
     1 font-lock-keyword-face)
   ;; Various notices
   '(" M A T L A B " 0 'underline)
   '("All Rights Reserved" 0 'italic)
   '("\\((c)\\s-+Copyright[^\n]+\\)" 1 font-lock-comment-face)
   '("\\(Version\\)\\s-+\\([^\n]+\\)"
     (1 font-lock-function-name-face) (2 font-lock-variable-name-face))
   )
  "Additional keywords used by MATLAB when reporting errors in interactive\
mode.")

;; Imenu support.
(defvar matlab-imenu-generic-expression
  '((nil "^\\s-*function\\>[ \t\n.]*\\(\\(\\[[^]]*\\]\\|\\sw+\\)[ \t\n.]*\
< =\[ \t\n.]*\\)?\\([a-zA-Z0-9_]+\\)" 3))
  "Expressions which find function headings in MATLAB M files.")

f
;;; MATLAB mode entry point ==================================================

;;;###autoload
(add-to-list 'auto-mode-alist '("\\.m$" . matlab-mode))

;;;###autoload
(defun matlab-mode ()
  "MATLAB(R) mode is a major mode for editing MATLAB dot-m files.
\\
Convenient editing commands are:
 \\[matlab-comment-region]   - Comment/Uncomment out a region of code.
 \\[matlab-fill-comment-line] - Fill the current comment line.
 \\[matlab-fill-region] - Fill code and comments in region.
 \\[matlab-fill-paragraph]     - Refill the current command or comment.
 \\[matlab-complete-symbol]   - Symbol completion of matlab symbols\
based on the local syntax.
 \\[matlab-indent-sexp] - Indent syntactic block of code.

Convenient navigation commands are:
 \\[matlab-beginning-of-command]   - Move to the beginning of a command.
 \\[matlab-end-of-command]   - Move to the end of a command.
 \\[matlab-beginning-of-defun] - Move to the beginning of a function.
 \\[matlab-end-of-defun] - Move do the end of a function.
 \\[matlab-forward-sexp] - Move forward over a syntactic block of code.
 \\[matlab-backward-sexp] - Move backwards over a syntactic block of code.

Convenient template insertion commands:
 \\[tempo-template-matlab-function] - Insert a function definition.
 \\[tempo-template-matlab-if] - Insert an IF END block.
 \\[tempo-template-matlab-for] - Insert a FOR END block.
 \\[tempo-template-matlab-switch] - Insert a SWITCH END statement.
 \\[matlab-insert-next-case] - Insert the next CASE condition in a SWITCH.
 \\[matlab-insert-end-block] - Insert a matched END statement.  With \
optional ARG, reindent.
 \\[matlab-stringify-region] - Convert plaintext in region to a string \
with correctly quoted chars.

Variables:
  `matlab-indent-level'		Level to indent blocks.
  `matlab-cont-level'		Level to indent continuation lines.
  `matlab-cont-requires-ellipsis' Does your MATLAB support implied elipsis.
  `matlab-case-level'		Level to unindent case statements.
  `matlab-indent-past-arg1-functions'
                                Regexp of functions to indent past the first
                                  argument on continuation lines.
  `matlab-maximum-indents'      List of maximum indents during lineups.
  `matlab-comment-column'       Goal column for on-line comments.
  `fill-column'			Column used in auto-fill.
  `matlab-indent-function-body' If non-nil, indents body of MATLAB functions.
  `matlab-functions-have-end'	If non-nil, MATLAB functions terminate with end.
  `matlab-return-function'	Customize RET handling with this function.
  `matlab-auto-fill'            Non-nil, do auto-fill at startup.
  `matlab-fill-code'            Non-nil, auto-fill code.
  `matlab-fill-strings'         Non-nil, auto-fill strings.
  `matlab-verify-on-save-flag'  Non-nil, enable code checks on save.
  `matlab-highlight-block-match-flag'
                                Enable matching block begin/end keywords.
  `matlab-vers-on-startup'	If t, show version on start-up.
  `matlab-handle-simulink'      If t, enable simulink keyword highlighting.

All Key Bindings:
\\{matlab-mode-map}"
  (interactive)
  (kill-all-local-variables)
  (use-local-map matlab-mode-map)
  (setq major-mode 'matlab-mode)
  (setq mode-name "MATLAB")
  (if (boundp 'whitespace-modes)
      (add-to-list 'whitespace-modes 'matlab-mode))
  (setq local-abbrev-table matlab-mode-abbrev-table)
  (set-syntax-table matlab-mode-syntax-table)
  (setq indent-tabs-mode nil)
  (make-local-variable 'indent-line-function)
  (setq indent-line-function 'matlab-indent-line)
  (make-local-variable 'paragraph-start)
  (setq paragraph-start (concat "^$\\|" page-delimiter))
  (make-local-variable 'paragraph-separate)
  (setq paragraph-separate paragraph-start)
  (make-local-variable 'paragraph-ignore-fill-prefix)
  (setq paragraph-ignore-fill-prefix t)
  (make-local-variable 'comment-start-skip)
  (setq comment-start-skip "%\\s-+")
  (make-local-variable 'comment-start)
  (setq comment-start "%")
  (make-local-variable 'page-delimiter)
  (setq page-delimiter "^\\(\f\\|%%\\(\\s-\\|\n\\)\\)")
  (make-local-variable 'comment-column)
  (setq comment-column matlab-comment-column)
  (make-local-variable 'comment-indent-function)
  (setq comment-indent-function 'matlab-comment-indent)
  (make-local-variable 'add-log-current-defun-function)
  (setq add-log-current-defun-function 'matlab-current-defun)
  (make-local-variable 'fill-column)
  (setq fill-column default-fill-column)
  (make-local-variable 'auto-fill-function)
  (if matlab-auto-fill (setq auto-fill-function 'matlab-auto-fill))
  ;; Emacs 20 supports this variable.  This lets users turn auto-fill
  ;; on and off and still get the right fill function.
  (make-local-variable 'normal-auto-fill-function)
  (setq normal-auto-fill-function 'matlab-auto-fill)
  (make-local-variable 'fill-prefix)
  (make-local-variable 'imenu-generic-expression)
  (setq imenu-generic-expression matlab-imenu-generic-expression)
  ;; Save hook for verifying src.  This lets us change the name of
  ;; the function in `write-file' and have the change be saved.
  ;; It also lets us fix mistakes before a `save-and-go'.
  (make-local-variable 'write-contents-hooks)
  (add-hook 'write-contents-hooks 'matlab-mode-verify-fix-file-fn)
  ;; Tempo tags
  (make-local-variable 'tempo-local-tags)
  (setq tempo-local-tags (append matlab-tempo-tags tempo-local-tags))
  ;; give each file it's own parameter history
  (make-local-variable 'matlab-shell-save-and-go-history)
  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults '((matlab-font-lock-keywords
			      matlab-gaudy-font-lock-keywords
			      matlab-really-gaudy-font-lock-keywords
			      )
			     t ; do not do string/comment highlighting
			     nil ; keywords are case sensitive.
			     ;; This puts _ as a word constituent,
			     ;; simplifying our keywords significantly
			     ((?_ . "w"))))
  (matlab-enable-block-highlighting 1)
  (if window-system (matlab-frame-init))

  ;; If first function is terminated with an end statement, then functions have
  ;; ends.
  (if (matlab-do-functions-have-end-p)
      (matlab-functions-have-end-minor-mode 1)
    (matlab-functions-have-end-minor-mode -1)
    )

  ;; When matlab-indent-function-body is set to 'MathWorks-Standard,
  ;;    - we indent all functions that terminate with an end statement
  ;;    - old style functions (those without end statements) are not
  ;;      indented.
  ;; It is desired that all code be terminate with an end statement.
  ;;
  ;; When matlab-indent-function-body is set to 'guess,
  ;;    - look at the first line of code and if indented, keep indentation
  ;;      otherwise use MathWorks-Standard
  ;;
  (cond
   ((eq matlab-indent-function-body 'MathWorks-Standard)
    )

   ((eq matlab-indent-function-body 'guess)
    (save-excursion
      (goto-char (point-max))

      (if (re-search-backward matlab-defun-regex nil t)
	  (let ((beg (point))
		end			; filled in later
		(cc (current-column))
		)
	    (setq end (if matlab-functions-have-end
			  (progn (forward-line 0) (point))
			(point-max)))
	    (goto-char beg)
	    (catch 'done
	      (while (progn (forward-line 1) (< (point) end))
		(if (looking-at "\\s-*\\(%\\|$\\)")
		    nil			; go on to next line
		  (looking-at "\\s-*")
		  (goto-char (match-end 0))
		  (setq matlab-indent-function-body (> (current-column) cc))
		  (throw 'done nil))))
	    )
	(setq matlab-indent-function-body 'MathWorks-Standard)
	))
    )
    
   (t)
   )


  (if (or (featurep 'mlint)
	  matlab-show-mlint-warnings
	  matlab-highlight-cross-function-variables)
      ;; Some users may not feel like getting all the extra stuff
      ;; needed for mlint working.  Do this only if we can get
      ;; mlint loaded ok.
      (condition-case nil
	  (mlint-minor-mode
	   (if (or matlab-show-mlint-warnings matlab-highlight-cross-function-variables)
	       1
	     0))
	;; If there is an error loading the stuff, don't
	;; continue.
	(error nil)))
  (save-excursion
    (goto-char (point-min))
    (run-hooks 'matlab-mode-hook))
  (if matlab-vers-on-startup (matlab-show-version)))
f
;;; Utilities =================================================================

(defun matlab-show-version ()
  "Show the version number in the minibuffer."
  (interactive)
  (message "matlab-mode, version %s" matlab-mode-version))

(defun matlab-find-prev-line ()
  "Recurse backwards until a code line is found."
  (if (= -1 (forward-line -1)) nil
    (if (or (matlab-ltype-empty)
	    (matlab-ltype-comm-ignore))
	(matlab-find-prev-line) t)))

(defun matlab-prev-line ()
  "Go to the previous line of code.  Return nil if not found."
  (interactive)
  (let ((old-point (point)))
    (if (matlab-find-prev-line) t (goto-char old-point) nil)))

(defun matlab-uniquafy-list (lst)
  "Return a list that is a subset of LST where all elements are unique."
  (let ((nlst nil))
    (while lst
      (if (and (car lst) (not (member (car lst) nlst)))
	  (setq nlst (cons (car lst) nlst)))
      (setq lst (cdr lst)))
    (nreverse nlst)))

; Aki Vehtari  recommends this: (19.29 required)
;(require 'backquote)
;(defmacro matlab-navigation-syntax (&rest body)
;  "Evaluate BODY with the matlab-mode-special-syntax-table"
;  '(let	((oldsyntax (syntax-table)))
;    (unwind-protect
;	(progn
;	  (set-syntax-table matlab-mode-special-syntax-table)
;	   ,@body)
;      (set-syntax-table oldsyntax))))

(defmacro matlab-navigation-syntax (&rest forms)
  "Set the current environment for syntax-navigation and execute FORMS."
  (list 'let '((oldsyntax (syntax-table))
	       (case-fold-search nil))
	 (list 'unwind-protect
		(list 'progn
		       '(set-syntax-table matlab-mode-special-syntax-table)
			(cons 'progn forms))
		'(set-syntax-table oldsyntax))))

(put 'matlab-navigation-syntax 'lisp-indent-function 0)
(add-hook 'edebug-setup-hook
	  (lambda ()
	    (def-edebug-spec matlab-navigation-syntax def-body)))

(defun matlab-up-list (count &optional restrict)
  "Move forwards or backwards up a list by COUNT.
Optional argument RESTRICT is where to restrict the search."
  ;; MATLAB syntax table has no disabling strings or comments.
  (let ((dir (if (> 0 count) -1 +1))
	(origin (point))
	(ms nil))
    ;; Make count positive
    (setq count (* count dir))
    (if (= dir -1)
	(while (/= count 0)
	  ;; Search till we find an unstrung paren object.
	  (setq ms (re-search-backward "\\s(\\|\\s)" restrict t))
	  (while (and (save-match-data (matlab-cursor-in-string-or-comment))
		      (setq ms (re-search-backward "\\s(\\|\\s)" restrict t))))
	  (if (not ms)
	      (progn
		(goto-char origin)
		(error "Scan Error: List missmatch")))
	  ;; View it's match.
	  (let ((s (match-string 0)))
	    (if (string-match "\\s(" s)
		(setq count (1- count))
	      (setq count (1+ count)))))
      (error "Not implemented"))
    ms))

(defun matlab-valid-end-construct-p ()
  "Return non-nil if the end after point terminates a block.
Return nil if it is being used to dereference an array."
  (let ((p (point))
	(err1 t))
    (condition-case nil
	(save-restriction
	  ;; Restrict navigation only to the current command line
	  (save-excursion
	    (matlab-beginning-of-command)
	    (narrow-to-region (point)
			      (save-excursion
				(goto-char p)
				(matlab-point-at-eol))))
	    ;; This used to add some sort of protection, but I don't know what
	    ;; the condition was, or why the simple case doesn't handle it.
	    ;;
	    ;; The above replacement fixes a case where a continuation in an array
	    ;; befuddles the indenter.
	    ;;		      (progn ;;(matlab-end-of-command (point))
	    ;;			(end-of-line)
	    ;;			(if (> p (point))
	    ;;			    (progn
	    ;;			      (setq err1 nil)
	    ;;			      (error)))
	    ;;    		(point))))
	  (save-excursion
	    ;; beginning of param list
	    (matlab-up-list -1)
	    ;; backup over the parens.  If that fails
	    (condition-case nil
		(progn
		  (forward-sexp 1)
		  ;; If we get here, the END is inside parens, which is not a
		  ;; valid location for the END keyword.  As such it is being
		  ;; used to dereference array parameters
		  nil)
	      ;; This error means that we have an unterminated paren
	      ;; block, so this end is currently invalid.
	      (error nil))))
      ;; an error means the list navigation failed, which also means we are
      ;; at the top-level
      (error err1))))
f
;;; Regexps for MATLAB language ===============================================

;; "-pre" means "partial regular expression"
;; "-if" and "-no-if" means "[no] Indent Function"

(defconst matlab-defun-regex "^\\(\\s-*function\\|classdef\\)[ \t.[]"
  "Regular expression defining the beginning of a MATLAB function.")

(defconst matlab-mcos-regexp "\\|classdef\\|properties\\|methods\\|enumeration"
  "Keywords which mark the beginning of mcos blocks.")

(defcustom matlab-block-indent-tic-toc-flag nil
  "*Non-nil means that tic,toc should indent like a if,end block.
This variable should be set before loading matlab.el"
  :group 'matlab
  :type 'boolean)

(defconst matlab-block-beg-pre-if
  (if matlab-block-indent-tic-toc-flag
      (concat "function\\|parfor\\|spmd\\|for\\|while\\|if\\|switch\\|try\\|tic"
	      matlab-mcos-regexp)
    (concat "function\\|parfor\\|spmd\\|for\\|while\\|if\\|switch\\|try"
	    matlab-mcos-regexp))
  "Keywords which mark the beginning of an indented block.
Includes function.")

(defconst matlab-block-beg-pre-no-if
  (if matlab-block-indent-tic-toc-flag
      (concat "parfor\\|for\\|spmd\\|while\\|if\\|switch\\|try\\|tic"
	      matlab-mcos-regexp)
    (concat "parfor\\|for\\|spmd\\|while\\|if\\|switch\\|try"
	    matlab-mcos-regexp))
  "Keywords which mark the beginning of an indented block.
Excludes function.")

(defun matlab-block-beg-pre ()
  "Partial regular expression to recognize MATLAB block-begin keywords."
  (if matlab-functions-have-end
      matlab-block-beg-pre-if
    matlab-block-beg-pre-no-if))

(defconst matlab-block-mid-pre
  "elseif\\|else\\|catch"
  "Partial regular expression to recognize MATLAB mid-block keywords.")

(defconst matlab-block-end-pre-if
  (if matlab-block-indent-tic-toc-flag
      "end\\(function\\)?\\|function\\|\\(\\sw+\\s-*\\((.*)\\)?\\s-*=\\s-*\\)?toc"
    "end\\(function\\)?\\|function")
  "Partial regular expression to recognize MATLAB block-end keywords.")

(defconst matlab-block-end-pre-no-if
  (if matlab-block-indent-tic-toc-flag
      "end\\|\\(\\sw+\\s-*\\((.*)\\)?\\s-*=\\s-*\\)?toc"
    "end")
  "Partial regular expression to recognize MATLAB block-end keywords.")

(defun matlab-block-end-pre ()
  "Partial regular expression to recognize MATLAB block-end keywords."
  (if matlab-functions-have-end
      matlab-block-end-pre-if
    matlab-block-end-pre-no-if))

;; Not used.
;;(defconst matlab-other-pre
;;  "function\\|return"
;;  "Partial regular express to recognize MATLAB non-block keywords.")

(defconst matlab-endless-blocks
  "case\\|otherwise"
  "Keywords which initialize new blocks, but don't have explicit ends.
Thus, they are endless.  A new case or otherwise will end a previous
endless block, and and end will end this block, plus any outside normal
blocks.")

(defun matlab-block-re ()
  "Regular expression for keywords which begin MATLAB blocks."
  (concat "\\(^\\|[;,]\\)\\s-*\\("
 	  (matlab-block-beg-pre) "\\|"
  	  matlab-block-mid-pre "\\|"
 	  (matlab-block-end-pre) "\\|"
 	  matlab-endless-blocks "\\)\\b"))
  
(defun matlab-block-scan-re ()
  "Expression used to scan over matching pairs of begin/ends."
  (concat "\\(^\\|[;,]\\)\\s-*\\("
 	  (matlab-block-beg-pre) "\\|"
 	  (matlab-block-end-pre) "\\)\\b"))

(defun matlab-block-beg-re ()
  "Expression used to find the beginning of a block."
  (concat "\\(" (matlab-block-beg-pre) "\\)"))

(defun matlab-block-mid-re ()
  "Expression used to find block center parts (like else)."
  (concat "\\(" matlab-block-mid-pre "\\)"))

(defun matlab-block-end-re ()
  "Expression used to end a block.  Usually just `end'."
  (concat "\\(" (matlab-block-end-pre) "\\)"))

(defun matlab-block-end-no-function-re ()
  "Expression representing and end if functions are excluded."
  (concat "\\<\\(" matlab-block-end-pre-no-if "\\)\\>"))

(defun matlab-endless-blocks-re ()
  "Expression of block starters that do not have associated ends."
  (concat "\\(" matlab-endless-blocks "\\)"))

(defun matlab-match-function-re ()
  "Expression to match a function start line.
There are no reliable numeric matches in this expression.
Know that `match-end' of 0 is the end of the functin name."
  ;; old function was too unstable.
  ;;"\\(^function\\s-+\\)\\([^=\n]+=[ \t\n.]*\\)?\\(\\sw+\\)"
  (concat "\\(^\\s-*function\\b[ \t\n.]*\\)\\(\\(\\[[^]]*\\]\\|\\sw+\\)"
	  "[ \t\n.]*=[ \t\n.]*\\|\\(\\)\\)\\(\\sw+\\)"))

(defconst matlab-cline-start-skip "[ \t]*%[ \t]*"
  "*The regular expression for skipping comment start.")

;;; Lists for matlab keywords =================================================

(defvar matlab-keywords-solo
  '("break" "case" "else" "elseif" "end" "for" "parfor" "function" "if" "tic" "toc"
    "otherwise" "profile" "switch" "while" "try" "catch" "spmd")
  "Keywords that appear on a line by themselves.")
(defvar matlab-keywords-return
  '("acos" "acosh" "acot" "acoth" "acsch" "asech" "asin" "asinh"
    "atan" "atan2" "atanh" "cos" "cosh" "coth" "csc" "csch" "exp"
    "log" "log10" "log2" "sec" "sech" "sin" "sinh" "tanh"
    "abs" "sign" "sqrt" )
  "List of MATLAB keywords that have return arguments.
This list still needs lots of help.")
(defvar matlab-keywords-boolean
  '("all" "any" "exist" "isempty" "isequal" "ishold" "isfinite" "isglobal"
    "isinf" "isletter" "islogical" "isnan" "isprime" "isreal" "isspace"
    "logical" "isa")
  "List of keywords that are typically used as boolean expressions.")

(defvar matlab-core-properties
  '("ButtonDownFcn" "Children" "Clipping" "CreateFcn" "DeleteFcn"
    "BusyAction" "HandleVisibility" "HitTest" "Interruptible"
    "Parent" "Selected" "SelectionHighlight" "Tag" "Type"
    "UIContextMenu" "UserData" "Visible")
  "List of properties belonging to all HG objects.")

(defvar matlab-property-lists
  '(("root" .
     ("CallbackObject" "Language" "CurrentFigure" "Diary" "DiaryFile"
      "Echo" "ErrorMessage" "Format" "FormatSpacing" "PointerLocation"
      "MonitorPositions"
      "PointerWindow" "Profile" "ProfileFile" "ProfileCount"
      "ProfileInterval" "RecursionLimit" "ScreenDepth" "ScreenSize"
      "ShowHiddenHandles" "TerminalHideGraphCommand" "TerminalOneWindow"
      "TerminalDimensions" "TerminalProtocol" "TerminalShowGraphCommand"
      "Units" "AutomaticFileUpdates" ))
    ("axes" .
     ("AmbientLightColor" "Box" "CameraPosition" "CameraPositionMode"
      "CameraTarget" "CameraTargetMode" "CameraUpVector"
      "CameraUpVectorMode" "CameraViewAngle" "CameraViewAngleMode" "CLim"
      "CLimMode" "Color" "CurrentPoint" "ColorOrder" "DataAspectRatio"
      "DataAspectRatioMode" "DrawMode" "FontAngle" "FontName" "FontSize"
      "FontUnits" "FontWeight" "GridLineStyle" "Layer" "LineStyleOrder"
      "LineWidth" "NextPlot" "PlotBoxAspectRatio" "PlotBoxAspectRatioMode"
      "Projection" "Position" "TickLength" "TickDir" "TickDirMode" "Title"
      "Units" "View" "XColor" "XDir" "XGrid" "XLabel" "XAxisLocation" "XLim"
      "XLimMode" "XScale" "XTick" "XTickLabel" "XTickLabelMode" "XTickMode"
      "YColor" "YDir" "YGrid" "YLabel" "YAxisLocation" "YLim" "YLimMode"
      "YScale" "YTick" "YTickLabel" "YTickLabelMode" "YTickMode" "ZColor"
      "ZDir" "ZGrid" "ZLabel" "ZLim" "ZLimMode" "ZScale" "ZTick"
      "ZTickLabel" "ZTickLabelMode" "ZTickMode"))
    ("figure" .
     ("BackingStore" "CloseRequestFcn" "Color" "Colormap"
      "CurrentAxes" "CurrentCharacter" "CurrentObject" "CurrentPoint"
      "Dithermap" "DithermapMode" "FixedColors" "IntegerHandle"
      "InvertHardcopy" "KeyPressFcn" "MenuBar" "MinColormap" "Name"
      "NextPlot" "NumberTitle" "PaperUnits" "PaperOrientation"
      "PaperPosition" "PaperPositionMode" "PaperSize" "PaperType"
      "Pointer" "PointerShapeCData" "PointerShapeHotSpot" "Position"
      "Renderer" "RendererMode" "Resize" "ResizeFcn" "SelectionType"
      "ShareColors" "Units" "WindowButtonDownFcn"
      "WindowButtonMotionFcn" "WindowButtonUpFcn" "WindowStyle"))
    ("image" . ("CData" "CDataMapping" "EraseMode" "XData" "YData"))
    ("light" . ("Position" "Color" "Style"))
    ("line" .
     ("Color" "EraseMode" "LineStyle" "LineWidth" "Marker" "LineSmoothing"
      "MarkerSize" "MarkerEdgeColor" "MarkerFaceColor" "XData" "YData"
      "ZData"))
    ("patch" .
     ("CData" "CDataMapping" "FaceVertexCData" "EdgeColor" "EraseMode"
      "FaceColor" "Faces" "LineStyle" "LineWidth" "Marker" "LineSmoothing"
      "MarkerEdgeColor" "MarkerFaceColor" "MarkerSize" "Vertices"
      "XData" "YData" "ZData" "FaceLighting" "EdgeLighting"
      "BackFaceLighting" "AmbientStrength" "DiffuseStrength"
      "SpecularStrength" "SpecularExponent" "SpecularColorReflectance"
      "VertexNormals" "NormalMode"))
    ("surface" .
     ("CData" "CDataMapping" "EdgeColor" "EraseMode" "FaceColor"
      "LineStyle" "LineWidth" "Marker" "MarkerEdgeColor" "LineSmoothing"
      "MarkerFaceColor" "MarkerSize" "MeshStyle" "XData" "YData"
      "ZData" "FaceLighting" "EdgeLighting" "BackFaceLighting"
      "AmbientStrength" "DiffuseStrength" "SpecularStrength"
      "SpecularExponent" "SpecularColorReflectance" "VertexNormals"
      "NormalMode"))
    ("text\\|title\\|xlabel\\|ylabel\\|zlabel" .
     ("Color" "EraseMode" "Editing" "Extent" "FontAngle" "FontName"
      "FontSize" "FontUnits" "FontWeight" "HorizontalAlignment"
      "BackgroundColor" "EdgeColor" "Margin"
      "Position" "Rotation" "String" "Units" "Interpreter"
      "VerticalAlignment"))
    ("uicontextmenu" . ("Callback"))
    ("uicontrol" .
     ("BackgroundColor" "Callback" "CData" "Enable" "Extent"
      "FontAngle" "FontName" "FontSize" "FontUnits" "FontWeight"
      "ForegroundColor" "HorizontalAlignment" "ListboxTop" "Max" "Min"
      "Position" "String" "Style" "SliderStep" "TooltipString" "Units"
      "Value"))
    ("uimenu" .
     ("Accelerator" "Callback" "Checked" "Enable" "ForegroundColor"
      "Label" "Position" "Separator"))
    ;; Flesh this out more later.
    ("uipushtool\\|uitoggletool\\|uitoolbar" .
     ("Cdata" "Callback" "Separator" "Visible"))
    )
  "List of property lists on a per object type basis.")

(defvar matlab-unknown-type-commands
  "[gs]et\\|findobj\\|waitfor"
  "Expression for commands that have unknown types.")

(defun matlab-all-known-properties ()
  "Return a list of all properties."
  (let ((lst matlab-core-properties)
	(tl matlab-property-li


你可能感兴趣的:(Matlab)