Google Tag Manager

2018/07/31

Syntax highlighting the source code in the JEditorPane

Code

// NG: color:#RGB
// OK: color:#RRGGBB
StyleSheet styleSheet = new StyleSheet();
styleSheet.addRule(".str {color:#008800}");
styleSheet.addRule(".kwd {color:#000088}");
styleSheet.addRule(".com {color:#880000}");
styleSheet.addRule(".typ {color:#660066}");
styleSheet.addRule(".lit {color:#006666}");
styleSheet.addRule(".pun {color:#666600}");
styleSheet.addRule(".pln {color:#000000}");
styleSheet.addRule(".tag {color:#000088}");
styleSheet.addRule(".atn {color:#660066}");
styleSheet.addRule(".atv {color:#008800}");
styleSheet.addRule(".dec {color:#660066}");

HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
htmlEditorKit.setStyleSheet(styleSheet);
editor.setEditorKit(htmlEditorKit);
editor.setEditable(false);
// ...

private void loadFile(String path) {
  try (Stream<String> lines = Files.lines(
      Paths.get(path), Charset.forName("UTF-8"))) {
    String txt = lines.map(s -> s.replace("&", "&amp;")
                                 .replace("<", "&lt;")
                                 .replace(">", "&gt;"))
      .collect(Collectors.joining("\n"));
    editor.setText("<pre>" + prettify(engine, txt) + "\n</pre>");
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}
private static ScriptEngine createEngine() {
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("JavaScript");
  try {
    Path path = Paths.get(MainPanel.class.getResource("prettify.js").toURI());
    try (Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
      engine.eval("var window={}, navigator=null;");
      engine.eval(r);
      return engine;
    }
  } catch (IOException | ScriptException | URISyntaxException ex) {
    ex.printStackTrace();
  }
  return null;
}
private static String prettify(ScriptEngine engine, String src) {
  try {
    Object w = engine.get("window");
    return (String) ((Invocable) engine).invokeMethod(
        w, "prettyPrintOne", src);
  } catch (ScriptException | NoSuchMethodException ex) {
    ex.printStackTrace();
    return "";
  }
}

References