Search code examples
javascriptace-editor

How to format Java code in Ace Editor


I am using ACE Editor to show my Java code. I want to format the java code in Editor. I tried the code like this:

var editor = $('.file-content').ace(),
JavaMode = ace.require('ace/mode/java').Mode,
beautify = ace.require("ace/ext/beautify");

editor.getSession().setValue(content);
editor.getSession().setMode(new JavaMode());
beautify.beautify(editor.getSession());

But I got the beautiful code like this:

publicclassHelloWorld{publicstaticvoidmain(String args[]){System 
.out.println(1);
}}

How can I format Java code in Ace Editor?


Solution

  • Here is an example of hooking JS Beautifier into your existing Ace Editor.

    var editor = ace.edit('editor');
    var txtAra = document.querySelector('textarea[name="editor"]');
    var jsbOpts = {
      indent_size : 2
    };
    
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/java");
    syncEditor();
    
    // Main Logic
    setTimeout(formatCode, 1000); // Format sample Java after 1 second.
    
    // Functions
    function syncEditor() {
      editor.getSession().setValue(txtAra.value);
    }
    function commitChanges() {
      txtAra.value = editor.getSession().getValue();
    }
    function formatCode() {
      var session = editor.getSession();
      session.setValue(js_beautify(session.getValue(), jsbOpts));
    }
    .title {
      font-size: 1.67em;
      font-weight: bold;
      text-align: center;
    }
    #editor {
      height: 75vh;
      width: 100%;
    }
    textarea[name="editor"] {
      display: none;
    }
    
    .as-console-wrapper {
      display: none !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.6.8/beautify.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css" rel="stylesheet"/>
    <div>
      <div class="title">Ace Editor - Java Format</div>
      <textarea name="editor">public class SpringTest {public static void main(String[] args) throws Exception {System.out.print("Hello world");}}</textarea>
      <div id="editor"></div>
    </div>

    Here is jsFiddle Demo