2009-07-29

Emacs mixed-mode PHP sources

Caveat: For these ideas to work, you might [depending on your system] need to download and install either or both of these Elisp modules:

php-mode
   css-mode

Presumption [for the purposes of this tip]:  IF you are using Emacs to edit PHP and/or CSS, THEN you know about and are using one or the other or both of these modules. If not, then you should probably give up now or seek professional help immediately.

Task:  Editing a PHP source file using Emacs can involve working in several source code language formatting modes, since it is common to mix PHP, CSS, (X)HTML, Javascript, and even MySQL query syntax in one PHP source file.

Rationale:  Although mixing languages in a single source file may on the face of it seem to violate the kind of *nixish organizational precepts that give us e.g. header (.h) and source (.c) files in C, sometimes painful experience has shown that the object oriented (OOD) precepts of "Encapsulation", "Isolation of Commonality", "Maintainability", and even (in some cases) "Human Readability" are all served by facilitating the mixing of languages within a single source file.

All that to say this: When editing a block of CSS code within a PHP file (using Emacs, of course), I have found it helpful to use the Emacs 'css-mode' Meta-Q key binding to format CSS rule blocks. However, when entering a multi-line CSS comment in the traditional 'C' style, it is useful to ask Emacs to use 'php-mode' Meta-Q to format the comments.

<?php 
$str = "example";
>
<style<
body {
  /* 
   * To format this comment block:
   * 1. Move the cursor to this line 
   * 2. Meta-X php-mode
   * 3. Meta-Q 
   *
   */
  margin:0;
  padding:0;
}

Summary:

  • The Meta-Q keystroke in Emacs formats the text under the cursor in the current buffer into a 'paragraph' [block] conforming to some arbitrary standard established for whatever mode Emacs is running in (assuming, of course, that Meta-Q is mapped for that mode).
  • When editing CSS, use the CSS mode to get nicely indented rule blocks.
  • Switch to PHP mode to format C-style comments within the CSS block [STYLE element code].
  • Probably should format the CSS first, then break the comments out such that they are surrounded by empty lines, since the php-mode formatting works most readably that way.…