Sublime Forum

HTML-CSS-JS Prettify Plugin

#1

Hi all!

I’m using a great plugin (HTML-CSS-JS Prettify) sublime.wbond.net/packages/HTML … 20Prettify

Issue:
I have a page that is .html which has now been changed to .php, the page contains basic HTML code, but as the extension has now been changed to .php the plugin will not format the code.

Is there a solution for this please?

Thanks…

0 Likes

#2

I’ve just seen a note that says edit run.js file, but I’m not to sure what to do, is there anyone who could edit the code for me please?


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

(function() {
  "use strict";

  // Cache the console log function and the process arguments.
  var log = console.log;
  var argv = process.argv;

  // Require path and file system utilities to load the jshint.js file.
  var path = require("path");
  var fs = require("fs");

  // The source file to be prettified, original source's path and some options.
  var tempPath = argv[2] || "";
  var filePath = argv[3] || "";
  var options = { html: {}, css: {}, js: {} };

  // This stuff does all the magic.
  var html_beautify = require(path.join(__dirname, "beautify-html.js")).html_beautify;
  var js_beautify = require(path.join(__dirname, "beautify.js")).js_beautify;
  var css_beautify = require(path.join(__dirname, "beautify-css.js")).css_beautify;

  // Some handy utility functions.
  function isTrue(value) {
    return value == "true" || value == true;
  }
  function getUserHome() {
    return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
  }
  function getOptions(file) {
    var data = fs.readFileSync(file, "utf8");
    var comments = /(?:\/\*(?:\s\S]*?)\*\/)|(?:\/\/(?:.*)$)/gm;
    try {
      return JSON.parse(data.replace(comments, ""));
    } catch (e) {
      return Object.create(null);
    }
  }
  function setOptions(file, optionsStore) {
    var obj = getOptions(file);
    for (var key in obj) {
      var value = obj[key];

      // Options are defined as an object for each format, with keys as prefs.
      if (key != "html" && key != "css" && key != "js") {
        continue;
      }
      for (var pref in value) {
        // Special case "true" and "false" pref values as actually booleans.
        // This avoids common accidents in .jsbeautifyrc json files.
        if (value == "true" || value == "false") {
          optionsStore[key][pref] = isTrue(value[pref]);
        } else {
          optionsStore[key][pref] = value[pref];
        }
      }
    }
  }

  var jsbeautifyrc = ".jsbeautifyrc";
  var pluginFolder = path.dirname(__dirname);
  var sourceFolder = path.dirname(filePath);
  var sourceParent = path.dirname(sourceFolder);
  var jsbeautifyrcPath;

  // Older versions of node has `existsSync` in the path module, not fs. Meh.
  fs.existsSync = fs.existsSync || path.existsSync;

  // Try and get some persistent options from the plugin folder.
  if (fs.existsSync(jsbeautifyrcPath = pluginFolder + path.sep + jsbeautifyrc)) {
    setOptions(jsbeautifyrcPath, options);
  }

  // When a JSBeautify config file exists in the same dir as the source file or
  // one dir above, then use this configuration to overwrite the default prefs.

  // Try and get more options from the source's folder.
  if (fs.existsSync(jsbeautifyrcPath = sourceFolder + path.sep + jsbeautifyrc)) {
    setOptions(jsbeautifyrcPath, options);
  }
  // ...or the parent folder.
  else if (fs.existsSync(jsbeautifyrcPath = sourceParent + path.sep + jsbeautifyrc)) {
    setOptions(jsbeautifyrcPath, options);
  }
  // ...or the user's home folder if everything else fails.
  else if (fs.existsSync(jsbeautifyrcPath = getUserHome() + path.sep + jsbeautifyrc)) {
    setOptions(jsbeautifyrcPath, options);
  }

  function isHTML(path, data) {
    return path.match(/\.html?$/) ||
      path.match(/\.xhtml?$/) ||
      path.match(/\.xml$/) ||
      (path == "?" && data.match(/^\s*</)); // First non-whitespace character is &lt;
  }

  function isCSS(path, data) {
    return path.match(/\.css$/) ||
      path.match(/\.sass$/) ||
      path.match(/\.less$/);
  }

  function isJS(path, data) {
    return path.match(/\.jsm?$/) ||
      path.match(/\.json$/) ||
      path.match(/\.jshintrc$/) ||
      path.match(/\.jsbeautifyrc$/) ||
      path.match(/\.sublime-/) ||
      (path == "?" && !data.match(/^\s*</)); // First non-whitespace character is not &lt;
  }

  // Read the source file and, when complete, beautify the code.
  fs.readFile(tempPath, "utf8", function(err, data) {
    if (err) {
      return;
    }

    // Mark the output as being from this plugin.
    log("*** HTMLPrettify output ***");

    if (isCSS(filePath, data)) {
      log(css_beautify(data, options"css"]).replace(/\s+$/, ""));
    }
    else if (isHTML(filePath, data)) {
      log(html_beautify(data, options"html"]).replace(/\s+$/, ""));
    }
    else if (isJS(filePath, data)) {
      log(js_beautify(data, options"js"]).replace(/\s+$/, ""));
    }
  });
}());

0 Likes

#3

It’s doable, but it presumes the existence of beautify-php.js (or a very smart beautify-html.js). I’ll post the latter fix in a few minutes.

0 Likes

#4

Modify isHTML to match this:

function isHTML(path, data) { return path.match(/\.html?$/) || path.match(/\.xhtml?$/) || path.match(/\.xml$/) || path.match(/\.php$/) || // *** new line is here (path == "?" && data.match(/^\s*</)); // First non-whitespace character is &lt; }

That should map PHP files to the HTML beautifier. What happens after that, I couldn’t say.

0 Likes

#5

[quote=“brook.monroe”]Modify isHTML to match this:

function isHTML(path, data) { return path.match(/\.html?$/) || path.match(/\.xhtml?$/) || path.match(/\.xml$/) || path.match(/\.php$/) || // *** new line is here (path == "?" && data.match(/^\s*</)); // First non-whitespace character is &lt; }

That should map PHP files to the HTML beautifier. What happens after that, I couldn’t say.[/quote]

Thank you brook.monroe, it works fine now!

0 Likes

#6

Is there a way to control extra lines being added to tags… Head, HTML, Body etc.

ex. On the closing body tag, it inserts another line.

http://www.innov8graphics.com/draft/lines.jpg

Thanks…

0 Likes

#7

ctrl+shift+p -> Set prettify Preferences will open the .jsbeautifyrc file to set optons. This is what I have in mine for this, specifically the “html” fixed what I didn’t like it doing similar to that screenshot:

"unformatted": // inline elements "html", "b", "big", "i", "small", "tt", "abbr", "acronym", "cite", "code", "dfn", "em", "kbd", "strong", "samp", "var", "a", "bdo", "br", "img", "map", "object", "q", "script", "span", "sub", "sup", "button", "input", "label", "select", "textarea", "command", "datalist", "keygen", "mark", "meter", "progress", "rp", "rt", "ruby", "time", "wbr" ],

I was actually hoping to find an answer for getting the opposite behavior. I want my figure tags to get an indent since they are block level elements.

I tried adding what I thought would be logical

"formatted": //block elements "figure" ],
but no, it does nothing. Will have to keep looking I guess.

Assuming there is no way to set this kind of option in the .jsbeautifyrc file, I’ve found a different solution that seems to work. There’s already a “reindent” command built into ST3 (edit > line > reindent) so I’ve added “reindent” to my chain of commands (after “htmlprettify”) that I’ve put together for cleaning up code that I get from other people.

[code]import sublime, sublime_plugin

class ReformatHtml(sublime_plugin.WindowCommand):
def run(self):
# package dependancies: https://github.com/SublimeText/TrailingSpaces - https://github.com/victorporof/Sublime-HTMLPrettify
self.window.run_command(“select_all”)
self.window.run_command(“delete_trailing_spaces”)
self.window.run_command(“delete_blank_lines”)
self.window.run_command(“htmlprettify”)
self.window.run_command(“reindent”)
self.window.run_command(“invert_selection”)[/code]
I have no idea if what I’ve done is correct or not, but it works for me and I added a keyboard shortcut for the above .py file.

{ "keys": "ctrl+alt+r"], "command": "reformat_html" }, // ReformatHtml.py

The “reindent” command fails on code in cases where it does not already have a line return for the opening and closing tags though. So if the code was

blahpictureaandtext
all on one line, my shortcut would fail to give me what i want so I’m still going to be stuck with spending too much time looking at and formatting some code more than I want to.

edit

Ignore everything I said above, i could delete but maybe better to keep in case someone else might have a similar idea so they can see that it is a bad idea to do what i did.

After more playing around i discovered that adding “html” to the unformatted list of elements was the source of the problem with other tags not getting formatted properly.

beautify-html.js line 122 has an extra_liners property… so I duplicated that line, commented out the original and removed the list of tags from inside the single quotes.

// extra_liners: 'head,body,/html'.split(','), //for tags that need a line of whitespace before them extra_liners: ''.split(','), //for tags that need a line of whitespace before them
I’m not really a programmer but this seems to work…

0 Likes

#8

I have the short solution for this problem, just add a few code into Setting of HTML-CSS-JS Prettify Plugin. This’s my way:

  • Ctrl+Shift+P, then type “Set Prettify Preferences” to open setting page
  • Looking up the key “allowed_file_extensions”, and add “php” into this array.

That’s it! Hope this solution helpful :wink:

3 Likes

#9

KISS - Works wonders.

1 Like

#10

Works perfectly. Thanx mate.

1 Like

#11

How can in disable this plugin for pug in vue template ?

0 Likes