Skip to content

Instantly share code, notes, and snippets.

@tkosaka
Created May 8, 2010 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkosaka/394530 to your computer and use it in GitHub Desktop.
Save tkosaka/394530 to your computer and use it in GitHub Desktop.
Toggle php-mode and html mode dynamically
;;; toggle-php-mode.el
;;; Toggle php-mode and html-mode.
;;; Version: 0.02: 2010/11/24
;;; Version: 0.01: 2010/05/08
(defvar php-html-major-mode 'html-mode
"Major mode for editing html files with `php-mode'.")
(defvar php-activate-html-mode-command 'html-mode
"Command that activates a major-mode for html."
)
(defun preserve-region (beg end)
(cond ((< (point) beg)
(push-mark (point) nil t)
(push-mark end nil t))
((> (point) end)
(push-mark beg nil t)
(push-mark (point) nil t))
(t
(push-mark beg nil t)
(push-mark end nil t)
)))
(defun php-change-major-mode-to-html ()
(when (equal major-mode 'php-mode)
(if (region-active-p)
(progn
(funcall php-activate-html-mode-command)
(preserve-region (region-beginning) (region-end))
(funcall php-activate-html-mode-command)))))
(defun php-change-major-mode-to-php ()
(unless (equal major-mode 'php-mode)
(if (region-active-p)
(progn
(php-mode)
(preserve-region (region-beginning) (region-end)))
(php-mode))))
(defun toggle-php-mode ()
"Toggle php-mode and `php-html-major-mode' if necessary."
(when (or (equal major-mode 'php-mode) (equal major-mode php-html-major-mode))
(let ((php-beginning-position (save-excursion (search-backward "<?php" nil t)))
(php-end-position (save-excursion (search-backward "?>" nil t))))
(if (save-excursion
(beginning-of-line)
(looking-at "[ \t\s]+<[?]php"))
(php-change-major-mode-to-php)
(cond ((not (integerp php-beginning-position))
(php-change-major-mode-to-html))
((and (integerp php-beginning-position) (not (integerp php-end-position)))
(php-change-major-mode-to-php))
((and (integerp php-beginning-position) (integerp php-end-position))
(if (> php-beginning-position php-end-position)
(php-change-major-mode-to-php)
(php-change-major-mode-to-html))))))))
(add-hook 'post-command-hook 'toggle-php-mode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment