Build Online Code Formatter
Before we jump into this topic, I would like to recommend you to go through the "Building a Code Editor with CodeMirror" topic. This is a continuation of the previous topic.
In previous topic we have learned following things:
- How to use a code mirror in order to build a web based code editor?
- Learned about syntax highlighter extension for code mirror.
- Learned about theme extension for code mirror.
Now we will be using a code beautifier on top of the code mirror in order to build Code Formatter online tool. Below pic depicts what we are trying to achieve.
Steps to implement it
- First list down list of libraries required to achieve it.
- Bootstrap 5 CSS: For UI rendering. This is optional.
- JQuery: Will use to assign some default value for Editor 1. And later to add a click event listener on "Format" button.
- Code Mirror for Editor 1 and Editor 2. [css, js, language mode(syntax highlighter) and theme.]
- js-beautify: For formatting code which we will write inside Editor 1.
- Next we will build both code editor. Please follow the previous topic.
- Next add "Format" button below the code editor.
- Now we will add a click event on the "Format" button to perform actual formating of written code and then assign formatted value to Editor 2.
After you embed the js-beautify <script> tags in your html file, it will expose three functions: js_beautify, css_beautify, and html_beautify. In the current example we will use the js_beautify function to format javascript code.
const options = { indent_size: 2, space_in_empty_paren: true }; $('.btn').click(function() { //console.log(editor1.getDoc().getValue()); const newval = js_beautify(editor1.getDoc().getValue(), options); editor2.getDoc().setValue(newval); });
Complete Code
<link href='https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css' rel='stylesheet' type='text/css'/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css"/> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/theme/darcula.min.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/mode/javascript/javascript.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.14.9/beautify.min.js"></script>