Skip to content
 

Komodo Editor: PHP Code Beautifier

So I’ve been playing around with Komodo Edit (the free editor available from the people who make the not-free Komodo IDE), and one thing I found missing was a code beautifier (or automatic formatting, if you prefer). It’s not a feature I use a lot, but can be really useful when importing code from someone else.

So after a bit of Googling, I found this article: PHP Code Beautifer Macro+Script. I followed the instructions to install the PEAR PHP_Beautifier package, saved the provided phpbeautifer.php script in my PHP directory, installed the macro file into the Komodo Edit “Toolbox” and edited it so that it pointed to where I’d put the PHP script (using double back-slashes for the directory separators since I’m on Windows), and it worked! All you have to do is double click the phpBeautifier icon in the Toolbox window, and it formats the currently active file.

The only change I’ve made so far is to edit the phpbeautifier.php file to remove the addfilter() instruction to insert a newline before functions, as that messed up classes with any access keywords before the function keyword. I also changed the indention to 3 spaces, and added the filter for PEAR styling.

<?php
if ($argc != 2 || in_array($argv[1], array(
   '--help',
   '-help',
   '-h',
   '-?'
))) {
?>

This is a command line PHP script with one option.

  Usage:
  <?php
   echo $argv[0]; ?> <option>

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

<?php
} else {
   if (file_exists(realpath($argv[1]))) {
      error_reporting(E_ALL | E_STRICT);
      require_once ('PHP/Beautifier.php');
      require_once ('PHP/Beautifier/Batch.php');
      try {
         $oBeaut = new PHP_Beautifier();
         $oBeaut->setIndentNumber(3); // default
         $oBeaut->setIndentChar(' '); // default
         $oBeaut->setNewLine("\n"); // default
         $oBeaut->addFilter('ArrayNested');
         /*
         $oBeaut->addFilter('NewLines', array(
         'before' => 'function'
         ));
         */
         $oBeaut->addFilter('Pear');
         $oBeaut->setInputString(file_get_contents($argv[1]));
         $oBeaut->process();
         if (php_sapi_name() == 'cli') {
            $oBeaut->show();
         } else {
            echo '<pre>' . $oBeaut->show() . '</pre>';
         }
      }
      catch(Exception $oExp) {
         echo ($oExp);
      }
   } else {
      echo "input file " . $argv[1] . " not found, exiting\n";
      exit;
   }
}
?>

I’m not crazy about the way it removes all blank lines, but maybe I’ll find some way to adjust that if I dig further into the PHP_Beautifier package. Right now it’s not important enough to me to spend the time on that bit of nuisance.

Leave a Reply

You must be logged in to post a comment.