如何在Ace Editor中格式化Java代码

时间:2017-08-02 10:31:17

标签: javascript ace-editor

我正在使用ACE Editor来显示我的Java代码。我想在Editor中格式化java代码。我尝试了这样的代码:

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());

但我得到了这样漂亮的代码:

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

如何在Ace Editor中格式化Java代码?

2 个答案:

答案 0 :(得分:1)

以下是将JS Beautifier挂钩到现有Ace编辑器的示例。



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>
&#13;
&#13;
&#13;

这是jsFiddle Demo

答案 1 :(得分:0)

Ace没有提供美化java的方法,你需要使用另一个程序。

相关问题