;;; php-mode.el --- major mode for editing PHP code

;; This is a version of the php-mode from that
;; fixes a few bugs which make using php-mode much more palatable, namely:
;; 1. New customisation options for some of the syntax highlighting
;;   features. I personally use the 'Gauchy' level of syntax
;;   highlighting -- I want variables and function calls fontified --
;;   but there were several very annoying "features" in this level of
;;   syntax highlighting, particularly the ones that warn you about
;;   perfectly valid code. I've added:
;;   * `php-mode-dollar-property-warning', which, if non-nil, warns on
;;     $foo->$bar. (Default is nil.)
;;   * `php-mode-dot-property-warning', which, if non-nil, warns on
;;     $ (Default is nil.)
;;   * `php-mode-warn-on-unmatches', which, if non-nil, warns on
;;     "everything else". (Default is nil.)
;;   * `php-mode-warn-if-mumamo-off', which, if nil, suppresses the
;;     once-per-file warning about indenting with mumamo-mode turned
;;     off. (Default is t)
;; 2. Bugfix in `php-show-arglist': this function no longer jumps to the
;;   function definition if that definition is in the current buffer.
;; 3. Bugfix: 'class' keywords at the beginning of a line are now
;;   correctly fontified.
;; This has been submitted to the php-mode maintainer, but I've not yet had a
;; response.
;; This was branched from the php-mode in nxhtml-mode, so if you have problems,
;; download the latest nxhtml-mode, and replace related/php-mode.el in the
;; nxhtml distribution with this file.
;; -- David House,

;; Copyright (C) 1999, 2000, 2001, 2003, 2004 Turadg Aleahmad
;;               2008 Aaron S. Hawley

;; Maintainer: Aaron S. Hawley <ashawley at>
;; Author: Turadg Aleahmad, 1999-2004
;; Keywords: php languages oop
;; Created: 1999-05-17
;; Modified: 2008-01-25T22:25:26+0100 Fri
;; X-URL:

(defconst php-mode-version-number "1.4.1a-nxhtml"
  "PHP Mode version number.")

;;; License

;; This file 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 3
;; of the License, or (at your option) any later version.

;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this file; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301, USA.

;;; Usage

;; Put this file in your Emacs lisp path (eg. site-lisp) and add to
;; your .emacs file:
;;   (require 'php-mode)

;; To use abbrev-mode, add lines like this:
;;   (add-hook 'php-mode-hook
;;     '(lambda () (define-abbrev php-mode-abbrev-table "ex" "extends")))

;; To make php-mode compatible with html-mode, see

;; Many options available under Help:Customize
;; Options specific to php-mode are in
;;  Programming/Languages/Php
;; Since it inherits much functionality from c-mode, look there too
;;  Programming/Languages/C

;;; Commentary:

;; PHP mode is a major mode for editing PHP 3 and 4 source code.  It's
;; an extension of C mode; thus it inherits all C mode's navigation
;; functionality.  But it colors according to the PHP grammar and indents
;; according to the PEAR coding guidelines.  It also includes a couple
;; handy IDE-type features such as documentation search and a source
;; and class browser.

;;; Contributors: (in chronological order)

;; Juanjo, Torsten Martinsen, Vinai Kopp, Sean Champ, Doug Marcey,
;; Kevin Blake, Rex McMaster, Mathias Meyer, Boris Folgmann, Roland
;; Rosenfeld, Fred Yankowski, Craig Andrews, John Keller, Ryan
;; Sammartino, ppercot, Valentin Funk, Stig Bakken, Gregory Stark,
;; Chris Morris, Nils Rennebarth, Gerrit Riessen, Eric Mc Sween,
;; Ville Skytta, Giacomo Tesio, Lennart Borgman, Stefan Monnier,
;; Aaron S. Hawley, Ian Eure, Bill Lovett, David House

;;; Changelog:

;; 1.4.1a-nxhtml
;;   Made underscore be part of identifiers.
;; 1.4.1-nxhtml
;;   Added php-mode-to-use.

;; 1.4.1
;;   Modified `php-check-html-for-indentation' to check for multiple
;;   mode support libraries. (Lennart Borgman)
;; 1.4
;;   Updated GNU GPL to version 3.  Ported to Emacs 22 (CC mode
;;   5.31). M-x php-mode-version shows version.  Provide end-of-defun
;;   beginning-of-defun functionality. Support add-log library.
;;   Fix __CLASS__ constant (Ian Eure).  Allow imenu to see visibility
;;   declarations -- "private", "public", "protected". (Bill Lovett)
;; 1.3
;;   Changed the definition of # using a tip from Stefan
;;   Monnier to correct highlighting and indentation. (Lennart Borgman)
;;   Changed the highlighting of the HTML part. (Lennart Borgman)
;; 1.2
;;   Implemented php-show-arglist, C-. (Engelke Eschner)
;;   Implemented php-complete-function, M-tab (Engelke Eschner)
;;   Re-enabled # comment detection in GNU Emacs (Urban Müller)
;;   Fixed some keybindings and default settings (Engelke Eschner)
;; 1.1
;;   Added PHP5 support (Giacomo Tesio)
;;     known problem: doesn't highlight after first 'implements'
;;   Better XEmacs compatibility (imenu, regexp, and comments!) (Ville Skytta)
;;   Improvement to php-conditional-key regexp (Eric Mc Sween)

;; 1.05
;;   Incorporated speedbar defs by Gerrit Riessen
;;   Add "foreach" to conditional introducing keywords (Nils Rennebarth)
;;   Cleared the Changelog
;;   Moved contribution credits into comments above

;;; Code:

(require 'speedbar)
(require 'font-lock)
(require 'cc-mode)
(require 'custom)
(require 'etags)
  (require 'regexp-opt))
;; Local variables
(defgroup php nil
  "Major mode `php-mode' for editing PHP code."
  :prefix "php-"
  :group 'languages)

(defcustom php-default-face 'default
  "Default face in `php-mode' buffers."
  :type 'face
  :group 'php)

(defcustom php-speedbar-config t
  "When set to true automatically configures Speedbar to observe PHP files.\
Ignores php-file patterns option; fixed to expression \"\\.\\(inc\\|php[s34]?\\)\""
  :type 'boolean
  :set (lambda (sym val)
         (set-default sym val)
         (if (and val (boundp 'speedbar))
  :group 'php)

(defcustom php-mode-speedbar-open nil
  "Normally `php-mode' starts with the speedbar closed.\
Turning this on will open it whenever `php-mode' is loaded."
  :type 'boolean
  :set (lambda (sym val)
         (set-default sym val)
         (when val
             (speedbar 1)))
  :group 'php)

(defcustom php-manual-url ""
  "URL at which to find PHP manual.\
You can replace \"en\" with your ISO language code."
  :type 'string
  :group 'php)

(defcustom php-search-url ""
  "URL at which to search for documentation on a word"
  :type 'string
  :group 'php)

(defcustom php-completion-file ""
  "Path to the file which contains the function names known to PHP"
  :type 'string
  :group 'php)

(defcustom php-manual-path ""
  "Path to the directory which contains the PHP manual"
  :type 'string
  :group 'php)

(defcustom php-mode-to-use
    (require 'mumamo nil t)
    (if (fboundp 'nxhtml-mumamo-turn-on)
      (if (fboundp 'html-mumamo-turn-on)
  "Major mode turn on function to use for php files."
  :type 'function
  :group 'php)

(defcustom php-file-patterns '("\\.php[s34]?\\'" "\\.phtml\\'" "\\.inc\\'")
  "List of file patterns for which to automatically invoke `php-mode'."
  :type '(repeat (regexp :tag "Pattern"))
  :set-after '(php-mode-to-use)
  :set (lambda (sym val)
         (set-default sym val)
         (let ((php-file-patterns-temp val))
           (while php-file-patterns-temp
             (add-to-list 'auto-mode-alist
                          (cons (car php-file-patterns-temp) php-mode-to-use))
             (setq php-file-patterns-temp (cdr php-file-patterns-temp)))))
  :group 'php)

(defcustom php-mode-hook nil
  "List of functions to be executed on entry to `php-mode'."
  :type 'hook
  :group 'php)

(defcustom php-mode-pear-hook nil
  "Hook called when a PHP PEAR file is opened with `php-mode'."
  :type 'hook
  :group 'php)

(defcustom php-mode-force-pear nil
  "Normally PEAR coding rules are enforced only when the filename contains \"PEAR\"\
Turning this on will force PEAR rules on all PHP files."
  :type 'boolean
  :group 'php)

(defcustom php-mode-dollar-property-warning nil
  "If non-`nil', warn about expressions like $foo->$bar where you
might have meant $foo->bar. Defaults to `nil' since this is valid
  :type 'boolean
  :group 'php)

(defcustom php-mode-dot-property-warning nil
  "If non-`nil', wan about expressions like $, which could
be a valid concatenation (if bar were a constant, or interpreted
as an unquoted string), but it's more likely you meant $foo->bar."
  :type 'boolean
  :group 'php)

(defcustom php-mode-warn-on-unmatched nil
  "If non-`nil', use `font-lock-warning-face' on any expression
that isn't matched by the other font lock regular expressions."
  :type 'boolean
  :group 'php)

(defcustom php-warn-if-mumamo-off t
  "Warn once per buffer if you try to indent a buffer without
mumamo-mode turned on. Detects if there are any HTML tags in the
buffer before warning, but this is not very smart; e.g. if you
have any tags inside a PHP string, it will be fooled."
  :type '(choice (const :tag "Warn" t) (const "Don't warn" nil))
  :group 'php)

  (defconst php-mode-modified
       (re-search-backward "^;; Modified: \\(.*\\)" nil 'noerror)
       (match-string-no-properties 1)))
    "PHP Mode version number."))

(defun php-mode-version ()
  "Display string describing the version of PHP mode"
  (message "PHP mode %s of %s"
           php-mode-version-number php-mode-modified))

(defconst php-beginning-of-defun-regexp
  "^\\s *function\\s +&?\\(\\(\\sw\\|\\s_\\)+\\)\\s *("
  "Regular expression for a PHP function.")

(defun php-beginning-of-defun (&optional arg)
  "Move to the beginning of the ARGth PHP function from point.
Implements PHP version of `beginning-of-defun-function'."
  (interactive "p")
  (let ((arg (or arg 1)))
    (while (> arg 0)
      (re-search-backward php-beginning-of-defun-regexp
                          nil 'noerror)
      (setq arg (1- arg)))
    (while (< arg 0)
      (end-of-line 1)
      (let ((opoint (point)))
        (beginning-of-defun 1)
        (forward-list 2)
        (forward-line 1)
        (if (eq opoint (point))
            (re-search-forward php-beginning-of-defun-regexp
                               nil 'noerror))
	(setq arg (1+ arg))))))

(defun php-end-of-defun (&optional arg)
  "Move the end of the ARGth PHP function from point.
Implements PHP befsion of `end-of-defun-function'

See `php-beginning-of-defun'."
  (interactive "p")
  (php-beginning-of-defun (- (or arg 1))))

(defvar php-completion-table nil
  "Obarray of tag names defined in current tags table and functions know to PHP.")

(defvar php-warned-bad-indent nil)
;;(make-variable-buffer-local 'php-warned-bad-indent)

;; Do it but tell it is not good if html tags in buffer.
(defun php-check-html-for-indentation ()
  (let ((html-tag-re "</?\\sw+.*?>")
        (here (point)))
    (if (not (or (re-search-forward html-tag-re (+ (point) 1000) t)
                 (re-search-backward html-tag-re (- (point) 1000) t)))
      (goto-char here)
      (setq php-warned-bad-indent t)
      ;;(setq php-warned-bad-indent nil)
      (let* ((known-multi-libs '(("mumamo" mumamo (lambda () (nxhtml-mumamo)))
                                 ("mmm-mode" mmm-mode (lambda () (mmm-mode 1)))
                                 ("multi-mode" multi-mode (lambda () (multi-mode 1)))))
             (known-names (mapcar (lambda (lib) (car lib)) known-multi-libs))
             (available-multi-libs (delq nil
                                          (lambda (lib)
                                            (when (locate-library (car lib)) lib))
             (available-names (mapcar (lambda (lib) (car lib)) available-multi-libs))
               "Indentation fails badly with mixed HTML/PHP in plaín\n"
               "`php-mode'.  To get indentation to work you must use an Emacs\n"
               "library that supports 'multiple major modes' in a buffer.  Parts\n"
               "of the buffer will then be in `php-mode' and parts in for example\n"
               "`html-mode'.  Known such libraries are:\n\t"
               (mapconcat 'identity known-names ", ")
               (if available-multi-libs
                    "You have these available in your `load-path':\n\t"
                    (mapconcat 'identity available-names ", ")
                    "Do you want to turn any of those on? ")
                 "You do not have any of those in your `load-path'.")))
              (catch 'is-using
                (dolist (lib available-multi-libs)
                  (when (and (boundp (cadr lib))
                             (symbol-value (cadr lib)))
                    (throw 'is-using t))))))
        (unless is-using-multi
          (if available-multi-libs
              (if (not (y-or-n-p base-msg))
                  (message "Did not do indentation, but you can try again now if you want")
                (let* ((name
                        (if (= 1 (length available-multi-libs))
                            (car available-names)
                          ;; Minibuffer window is more than one line, fix that first:
                          (message "")
                          (completing-read "Choose multiple major mode support library: "
                                           available-names nil t
                                           (car available-names)
                                           '(available-names . 1)
                       (mode (when name
                               (caddr (assoc name available-multi-libs)))))
                  (when mode
                    ;; Minibuffer window is more than one line, fix that first:
                    (message "")
                    (load name)
                    (funcall mode))))
            (lwarn 'php-indent :warning base-msg)))

(defun php-cautious-indent-region (start end &optional quiet)
  (if (or (not php-warn-if-mumamo-off)
      (funcall 'c-indent-region start end quiet)))

(defun php-cautious-indent-line ()
  (if (or (not php-warn-if-mumamo-off)
      (funcall 'c-indent-line)))

(define-derived-mode php-mode c-mode "PHP"
  "Major mode for editing PHP code.\n\n\\{php-mode-map}"
;;   (c-add-language 'php-mode 'c-mode)

;;   (c-lang-defconst c-block-stmt-1-kwds
;;     php php-block-stmt-1-kwds)
  (set (make-local-variable 'c-block-stmt-1-key) php-block-stmt-1-key)

;;   (c-lang-defconst c-block-stmt-2-kwds
;;     php php-block-stmt-2-kwds)
  (set (make-local-variable 'c-block-stmt-2-key) php-block-stmt-2-key)
  ;; Specify that cc-mode recognize Javadoc comment style
  (set (make-local-variable 'c-doc-comment-style)
    '((php-mode . javadoc)))

;;   (c-lang-defconst c-class-decl-kwds
;;     php php-class-decl-kwds)
  (set (make-local-variable 'c-class-key) php-class-key)

  ;; this line makes $ into punctuation instead of a word constituent
  ;; it used to be active, but it killed indenting of case lines that
  ;; begin with '$' (many do).  If anyone has a solution to this
  ;; problem, please let me know.  Of course, you're welcome to
  ;; uncomment this line in your installation.
;  (modify-syntax-entry ?$ "." php-mode-syntax-table)

  ;; The above causes XEmacs to handle shell-style comments correctly,
  ;; but fails to work in GNU Emacs which fails to interpret \n as the
  ;; end of the comment.
  (if (featurep 'xemacs) (progn
                (modify-syntax-entry ?# "< b" php-mode-syntax-table)
                (modify-syntax-entry ?\n "> b" php-mode-syntax-table)))

  (make-local-variable 'font-lock-defaults)
  (setq font-lock-defaults
               ;; Comment-out the next line if the font-coloring is too
               ;; extreme/ugly for you.
          nil                               ; KEYWORDS-ONLY
          nil                                 ; CASE-FOLD
          nil                               ; SYNTAX-ALIST
          nil))                             ; SYNTAX-BEGIN
  (modify-syntax-entry ?# "< b" php-mode-syntax-table)
  (modify-syntax-entry ?_ "w" php-mode-syntax-table)

  ;; Electric behaviour must be turned off, they do not work since
  ;; they can not find the correct syntax in embedded PHP.
  ;; Seems to work with narrowing so let it be on if the user prefers it.
  ;;(setq c-electric-flag nil)

  (setq font-lock-maximum-decoration t
        case-fold-search t              ; PHP vars are case-sensitive
        imenu-generic-expression php-imenu-generic-expression)

  ;; Do not force newline at end of file.  Such newlines can cause
  ;; trouble if the PHP file is included in another file before calls
  ;; to header() or cookie().
  (set (make-local-variable 'require-final-newline) nil)
  (set (make-local-variable 'next-line-add-newlines) nil)

  ;; PEAR coding standards
  (add-hook 'php-mode-pear-hook
            (lambda ()
              (set (make-local-variable 'tab-width) 4)
              (set (make-local-variable 'c-basic-offset) 4)
              (set (make-local-variable 'indent-tabs-mode) nil)
              (c-set-offset 'block-open' - )
              (c-set-offset 'block-close' 0 )) nil t)

  (if (or php-mode-force-pear
          (and (stringp buffer-file-name)
               (string-match "PEAR\\|pear"
               (string-match "\\.php$" (buffer-file-name))))
      (run-hooks 'php-mode-pear-hook))

  (setq indent-line-function 'php-cautious-indent-line)
  (setq indent-region-function 'php-cautious-indent-region)
  (setq c-special-indent-hook nil)

  (set (make-local-variable 'syntax-begin-function)
  (set (make-local-variable 'beginning-of-defun-function)
  (set (make-local-variable 'end-of-defun-function)
  (set (make-local-variable 'open-paren-in-column-0-is-defun-start)
  (set (make-local-variable 'defun-prompt-regexp)
       "^\\s *function\\s +&?\\(\\(\\sw\\|\\s_\\)+\\)\\s *")
  (set (make-local-variable 'add-log-current-defun-header-regexp)

  (run-hooks 'php-mode-hook))
;; Make a menu keymap (with a prompt string)
;; and make it the menu bar item's definition.
(define-key php-mode-map [menu-bar] (make-sparse-keymap))
(define-key php-mode-map [menu-bar php]
  (cons "PHP" (make-sparse-keymap "PHP")))

;; Define specific subcommands in this menu.
(define-key php-mode-map [menu-bar php complete-function]
  '("Complete function name" . php-complete-function))
(define-key php-mode-map
  [menu-bar php browse-manual]
  '("Browse manual" . php-browse-manual))
(define-key php-mode-map
  [menu-bar php search-documentation]
  '("Search documentation" . php-search-documentation))
;; Define function name completion function
(defun php-complete-function ()
  "Perform function completion on the text around point.
Completes to the set of names listed in the current tags table
and the standard php functions.
The string to complete is chosen in the same way as the default
for \\[find-tag] (which see)."
  (let ((pattern (php-get-pattern))
        (php-functions (php-completion-table)))
    (if (not pattern) (message "Nothing to complete")
        (search-backward pattern)
        (setq beg (point))
        (forward-char (length pattern))
        (setq completion (try-completion pattern php-functions nil))
        (cond ((eq completion t))
              ((null completion)
               (message "Can't find completion for \"%s\"" pattern)
              ((not (string= pattern completion))
               (delete-region beg (point))
               (insert completion))
               (message "Making completion list...")
               (with-output-to-temp-buffer "*Completions*"
                  (all-completions pattern php-functions)))
               (message "Making completion list...%s" "done"))))))

;; Build php-completion-table on demand.  The table includes the
;; PHP functions and the tags from the current tags-file-name
(defun php-completion-table ()
  (or (and tags-file-name
           (save-excursion (tags-verify-table tags-file-name))
      (let ((tags-table
             (if (and tags-file-name
                      (functionp 'etags-tags-completion-table))
                 (with-current-buffer (get-file-buffer tags-file-name)
             (cond ((and (not (string= "" php-completion-file))
                         (file-readable-p php-completion-file))
                    (php-build-table-from-file php-completion-file))
                    (php-build-table-from-path php-manual-path))
                   (t nil))))
        (unless (or php-table tags-table)
           (concat "No TAGS file active nor are "
                   "`php-completion-file' or `php-manual-path' set")))
        (when tags-table
          ;; Combine the tables.
          (mapatoms (lambda (sym) (intern (symbol-name sym) php-table))
        (setq php-completion-table php-table))))

(defun php-build-table-from-file (filename)
  (let ((table (make-vector 1022 0))
        (buf (find-file-noselect filename)))
      (set-buffer buf)
      (goto-char (point-min))
      (while (re-search-forward
              nil t)
        (intern (buffer-substring (match-beginning 1) (match-end 1))
    (kill-buffer buf)

(defun php-build-table-from-path (path)
  (let ((table (make-vector 1022 0))
        (files (directory-files
    (mapc (lambda (file)
            (string-match "\\.\\([-a-zA-Z_0-9]+\\)\\.html$" file)
              "-" "_" (substring file (match-beginning 1) (match-end 1)) t)

;; Find the pattern we want to complete
;; find-tag-default from GNU Emacs etags.el
(defun php-get-pattern ()
    (while (looking-at "\\sw\\|\\s_")
      (forward-char 1))
    (if (or (re-search-backward "\\sw\\|\\s_"
                                (save-excursion (beginning-of-line) (point))
            (re-search-forward "\\(\\sw\\|\\s_\\)+"
                               (save-excursion (end-of-line) (point))
        (progn (goto-char (match-end 0))
                (progn (forward-sexp -1)
                       (while (looking-at "\\s'")
                         (forward-char 1))

(defun php-show-arglist ()
  (let* ((tagname (php-get-pattern)) arglist)
      (set-buffer (find-tag-noselect tagname nil nil))
      (goto-char (point-min))
      (when (re-search-forward
             (format "function[ \t]+%s[ \t]*(\\([^{]*\\))" tagname)
             nil t)
        (setq arglist (buffer-substring-no-properties
                       (match-beginning 1) (match-end 1)))))
    (if arglist
        (message "Arglist for %s: %s" tagname arglist)
      (message "Unknown function: %s" tagname))))
;; Define function documentation function
(defun php-search-documentation ()
  "Search PHP documentation for the word at the point."
  (browse-url (concat php-search-url (current-word t))))

;; Define function for browsing manual
(defun php-browse-manual ()
  "Bring up manual for PHP."
  (browse-url php-manual-url))

;; Define shortcut
(define-key php-mode-map

;; Define shortcut
(define-key php-mode-map
  [(meta tab)]

;; Define shortcut
(define-key php-mode-map

;; Define shortcut
(define-key php-mode-map
  '[(control .)]
(defconst php-constants
     '(;; core constants
       "__LINE__" "__FILE__"
       "__FUNCTION__" "__CLASS__" "__METHOD__"
       "TRUE" "FALSE" "NULL"

       ;; from ext/standard:
       "M_LN10" "M_PI" "M_PI_2" "M_PI_4" "M_1_PI" "M_2_PI"

       ;; Disabled by default because they slow buffer loading
       ;; If you have use for them, uncomment the strings
       ;; that you want colored.
       ;; To compile, you may have to increase 'max-specpdl-size'

       ;; from other bundled extensions:
;        "CAL_EASTER_TO_xxx" "VT_NULL" "VT_EMPTY" "VT_UI1" "VT_I2"
;        "VT_I4" "VT_R4" "VT_R8" "VT_BOOL" "VT_ERROR" "VT_CY" "VT_DATE"
;        "VT_I1" "VT_UI2" "VT_UI4" "VT_INT" "VT_UINT" "VT_ARRAY"
;        "FBSQL_NUM" "FBSQL_BOTH" "FDFValue" "FDFStatus" "FDFFile"
;        "FDFID" "FDFFf" "FDFSetFf" "FDFClearFf" "FDFFlags" "FDFSetF"
;        "FDFClrF" "FDFAP" "FDFAS" "FDFAction" "FDFAA" "FDFAPRef"
;        "FDFIF" "FDFEnter" "FDFExit" "FDFDown" "FDFUp" "FDFFormat"
;        "FDFValidate" "FDFKeystroke" "FDFCalculate"
;        "BSOver" "BSUp" "OverDowntoIdle" "IdletoOverDown"
;        "OutDowntoIdle" "OutDowntoOverDown" "OverDowntoOutDown"
;        "OverUptoOverDown" "OverUptoIdle" "IdletoOverUp" "ButtonEnter"
;        "ButtonExit" "MenuEnter" "MenuExit" "XML_ERROR_NONE"

       ;; PEAR constants

  "PHP constants.")

(defconst php-keywords
     ;; "class", "new" and "extends" get special treatment
     ;; "case" and  "default" get special treatment elsewhere
     '("and" "as" "break" "continue" "declare" "do" "echo" "else" "elseif"
       "endfor" "endforeach" "endif" "endswitch" "endwhile" "exit"
       "extends" "for" "foreach" "global" "if" "include" "include_once"
       "next" "or" "require" "require_once" "return" "static" "switch"
       "then" "var" "while" "xor" "private" "throw" "catch" "try"
       "instanceof" "catch all" "finally")))
  "PHP keywords.")

(defconst php-identifier
  "Characters in a PHP identifier.")

(defconst php-types
    (regexp-opt '("array" "bool" "boolean" "char" "const" "double" "float"
                  "int" "integer" "long" "mixed" "object" "real"
  "PHP types.")

(defconst php-superglobals
    (regexp-opt '("_GET" "_POST" "_COOKIE" "_SESSION" "_ENV" "GLOBALS"
                  "_SERVER" "_FILES" "_REQUEST")))
  "PHP superglobal variables.")

;; Set up font locking
(defconst php-font-lock-keywords-1
   ;; Fontify constants
    (concat "\\<\\(" php-constants "\\)\\>")

   ;; Fontify keywords
    (concat "\\<\\(" php-keywords "\\)\\>")

   ;; Fontify keywords and targets, and case default tags.
   (list "\\<\\(break\\|case\\|continue\\)\\>[ \t]*\\(-?\\(?:\\sw\\|\\s_\\)+\\)?"
         '(1 font-lock-keyword-face) '(2 font-lock-constant-face t t))
   ;; This must come after the one for keywords and targets.
   '(":" ("^[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)[ \t]*:[ \t]*$"
          (beginning-of-line) (end-of-line)
          (1 font-lock-constant-face)))

   ;; treat 'print' as keyword only when not used like a function name
   '("\\<print\\s-*(" . php-default-face)
   '("\\<print\\>" . font-lock-keyword-face)

   ;; Fontify PHP tag
   '("<\\?\\(php\\)?" . font-lock-constant-face)
   '("\\?>" . font-lock-constant-face)

   ;; Fontify ASP-style tag
   '("<\\%\\(=\\)?" . font-lock-constant-face)
   '("\\%>" . font-lock-constant-face)

  "Subdued level highlighting for PHP mode.")

(defconst php-font-lock-keywords-2

    ;; class declaration
    '("[^_]*\\<\\(class\\|interface\\)[ \t]*\\(\\(?:\\sw\\|\\s_\\)+\\)?"
      (1 font-lock-keyword-face) (2 font-lock-type-face nil t))
    ;; handle several words specially, to include following word,
    ;; thereby excluding it from unknown-symbol checks later
    ;; FIX to handle implementing multiple
    ;; currently breaks on "class Foo implements Bar, Baz"
      (1 font-lock-keyword-face) (2 font-lock-type-face))

    ;; function declaration
      (1 font-lock-keyword-face)
      (2 font-lock-function-name-face nil t))

    ;; class hierarchy
    '("\\(self\\|parent\\)\\W" (1 font-lock-constant-face nil nil))

    ;; method and variable features
      (1 font-lock-keyword-face))

    ;; method features
    '("^[ \t]*\\(abstract\\|static\\|final\\)\\s-+\\$?\\(?:\\sw\\|\\s_\\)+"
      (1 font-lock-keyword-face))

    ;; variable features
    '("^[ \t]*\\(static\\|const\\)\\s-+\\$?\\(?:\\sw\\|\\s_\\)+"
      (1 font-lock-keyword-face))
  "Medium level highlighting for PHP mode.")

(defconst php-font-lock-keywords-3
     ;; <word> or </word> for HTML
     ;;'("</?\\sw+[^> ]*>" . font-lock-constant-face)
     ;;'("</?\\sw+[^>]*" . font-lock-constant-face)
     ;;'("<!DOCTYPE" . font-lock-constant-face)
     ("</?[a-z!:]+" . font-lock-constant-face)

     ;; HTML >
     ("<[^>]*\\(>\\)" (1 font-lock-constant-face))

     ;; HTML tags
     ("\\(<[a-z]+\\)[[:space:]]+\\([a-z:]+=\\)[^>]*?" (1 font-lock-constant-face) (2 font-lock-constant-face) )
     ("\"[[:space:]]+\\([a-z:]+=\\)" (1 font-lock-constant-face))

     ;; HTML entities
     ;;'("&\\w+;" . font-lock-variable-name-face)

     ;; warn about '$' immediately after ->
     ,@(if php-mode-dollar-property-warning
             (1 font-lock-warning-face) (2 php-default-face)))

     ;; warn about $word.word -- it could be a valid concatenation,
     ;; but without any spaces we'll assume $word->word was meant.
     ,@(if php-mode-dot-property-warning
           '("\\$\\(?:\\sw\\|\\s_\\)+\\(\\.\\)\\sw" 1 font-lock-warning-face))

     ;; Warn about ==> instead of =>
     ("==+>" . font-lock-warning-face)

     ;; exclude casts from bare-word treatment (may contain spaces)
     (,(concat "(\\s-*\\(" php-types "\\)\\s-*)") 1 font-lock-type-face)

     ;; PHP5: function declarations may contain classes as parameters type
      1 font-lock-type-face)

     ;; Fontify variables and function calls
     ("\\$\\(this\\|that\\)\\W" (1 font-lock-constant-face nil nil))
     (,(concat "\\$\\(" php-superglobals "\\)\\W")
      (1 font-lock-constant-face nil nil)) ; $_GET & co
     ("\\$\\(\\(?:\\sw\\|\\s_\\)+\\)" (1 font-lock-variable-name-face)) ; $variable
     ("->\\(\\(?:\\sw\\|\\s_\\)+\\)" (1 font-lock-variable-name-face t t)) ; ->variable
     ("->\\(\\(?:\\sw\\|\\s_\\)+\\)\\s-*(" . (1 php-default-face t t)) ; ->function_call
     ("\\(\\(?:\\sw\\|\\s_\\)+\\)::\\(?:\\sw\\|\\s_\\)+\\s-*(?" . (1 font-lock-type-face)) ; class::member
     ("::\\(\\(?:\\sw\\|\\s_\\)+\\>[^(]\\)" . (1 php-default-face)) ; class::constant
     ("\\<\\(?:\\sw\\|\\s_\\)+\\s-*[[(]" . php-default-face) ; word( or word[
     ("\\<[0-9]+" . php-default-face)   ; number (also matches word)

     ;; Warn on any words not already fontified
     ,@(if php-mode-warn-on-unmatched
           '("\\<\\(?:\\sw\\|\\s_\\)+\\>" . font-lock-warning-face))

  "Gauchy level highlighting for PHP mode.")

;; Define the imenu-generic-expression for PHP mode.
;; To use, execute M-x imenu, then click on Functions or Classes,
;; then select given function/class name to go to its definition.
;; [Contributed by Gerrit Riessen]
(defvar php-imenu-generic-expression
   ("All Functions"
    "^\\s-*function\\s-+\\([[:alnum:]_]+\\)\\s-*(" 1)
    "^\\s-*class\\s-+\\([[:alnum:]_]+\\)\\s-*" 1)
   ("Public Methods"
    "^\\s-*public function\\s-+\\([[:alnum:]_]+\\)\\s-*(" 1)
   ("Protected Methods"
    "^\\s-*protected function\\s-+\\([[:alnum:]_]+\\)\\s-*(" 1)
   ("Private Methods"
    "^\\s-*private function\\s-+\\([[:alnum:]_]+\\)\\s-*(" 1)
 "Imenu generic expression for PHP Mode. See `imenu-generic-expression'."

(defconst php-block-stmt-1-kwds '("do" "else" "finally" "try"))
(defconst php-block-stmt-2-kwds
  '("for" "if" "while" "switch" "foreach" "elseif"  "catch all"))

(defconst php-block-stmt-1-key
  (regexp-opt php-block-stmt-1-kwds))
(defconst php-block-stmt-2-key
  (regexp-opt php-block-stmt-2-kwds))

(defconst php-class-decl-kwds '("class" "interface"))

(defconst php-class-key
   "\\(" (regexp-opt php-class-decl-kwds) "\\)\\s +"
   c-symbol-key                                 ;; Class name.
   "\\(\\s *extends\\s *" c-symbol-key "\\)?"   ;; Name of superclass.
   "\\(\\s *implements *[^{]+{\\)?")) ;; List of any adopted protocols.

;; Create "php-default-face" symbol for GNU Emacs so that both XEmacs
;; and GNU emacs can refer to the default face.
(unless (boundp 'php-default-face)
   (defvar php-default-face 'php-default-face))

;; Create faces for XEmacs
(when (featurep 'xemacs)
  (unless (boundp 'font-lock-keyword-face)
    (copy-face 'bold 'font-lock-keyword-face))
  (unless (boundp 'font-lock-constant-face)
    (copy-face 'font-lock-keyword-face 'font-lock-constant-face)))

(provide 'php-mode)

;;; php-mode.el ends here