Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate syntax check in Ace Editor using custom mode?

I'm new to ace-editor and I have included custom mode to validate my code and every line should end up with semicolon, If semicolon is not present in my query by mistake then the editor should gives up the warning like "Missing Semicolon".

define('ace/mode/javascript-custom', [], function(require, exports, module) {

  var oop = require("ace/lib/oop");
  var TextMode = require("ace/mode/text").Mode;
  var Tokenizer = require("ace/tokenizer").Tokenizer;
  var ExampleHighlightRules = require("ace/mode/example_highlight_rules").ExampleHighlightRules;

  var Mode = function() {
    this.HighlightRules = ExampleHighlightRules;
  };
  oop.inherits(Mode, TextMode);

  (function() {
    this.lineCommentStart = "--";
    this.blockComment = {
      start: "->",
      end: "<-"
    };
  }).call(Mode.prototype);

  exports.Mode = Mode;
});

define('ace/mode/example_highlight_rules', [], function(require, exports, module) {
  var oop = require("ace/lib/oop");
  var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

  var ExampleHighlightRules = function() {

    var keywordMapper = this.createKeywordMapper({
      "variable.language": "this",
      "keyword": "one|two",
      "constant.language": "true|false|null"
    }, "text", true);

    this.$rules = {
      "start": [{
        token: "comment",
        regex: "->",
        next: [{
          regex: "<-",
          token: "comment",
          next: "start"
        }, {
          defaultToken: "comment"
        }]
      }, {
        regex: "\\w+\\b",
        token: keywordMapper
      }, {
        token: "comment",
        regex: "--.*"
      }, {
        token: "string",
        regex: '"',
        next: [{
          regex: /\\./,
          token: "escape.character"
        }, {
          regex: '"',
          token: "string",
          next: "start"
        }, {
          defaultToken: "string"
        }]
      }, {
        token: "numbers",
        regex: /\d+(?:[.](\d)*)?|[.]\d+/
      }]
    };
    this.normalizeRules()
  };

  oop.inherits(ExampleHighlightRules, TextHighlightRules);

  exports.ExampleHighlightRules = ExampleHighlightRules;

});

var langTools = ace.require("ace/ext/language_tools");
var editor = ace.edit("editor");

editor.session.setMode("ace/mode/javascript-custom");
editor.setOptions({
  enableBasicAutocompletion: true,
  enableLiveAutocompletion: true
});
editor.setTheme("ace/theme/monokai");
var lines = editor.session.doc.getAllLines();
var errors = [];

for (var i = 0; i < lines.length; i++) {
  if (/[\w\d{(['"]/.test(lines[i])) {
    alert("hello");
    errors.push({
      row: i,
      column: lines[i].length,
      text: "Missing Semicolon",
      type: "error"
    });
  }
}
<script src="https://ajaxorg.github.io/ace-builds/src/ext-language_tools.js"></script>
<script src="https://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<div id="editor" style="height: 200px; width: 400px"></div>
<div id="commandline" style="position: absolute; bottom: 10px; height: 20px; width: 800px;"></div>

UPDATE:

The following js files are generated from ace and added to my rails application, the files are loaded in rails app but the functionality (semicolon check) doesn't seem to be working.

worker-semicolonlineend - http://pastebin.com/2kZ2fYr9 mode-semicolonlineend - http://pastebin.com/eBY5VvNK

Update:

  1. In ace editor, type in a query1, query2 in line 1 and line 2 respectively
  2. Leave the third line blank
  3. Now in fourth line, type a query without semicolon in the end, x mark appears in third line 5 And when the fifth line is also without a semicolon, then the x mark is displayed at fourth query

enter image description here

like image 583
M.R Avatar asked Jun 22 '15 07:06

M.R


1 Answers

Ace editor widely support this kind analysis for JavaScript by default:

#editor {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
<div id="editor">function foo() { ; // unnessesary semicolon
    var x = "bar" // missing semicolon 
    return x; // semicolon in place
}
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.1.9/ace.js" type="text/javascript"></script>
<script>
 var editor = ace.edit("editor");
 editor.setTheme("ace/theme/monokai");
 editor.getSession().setMode("ace/mode/javascript");
</script>

Just make sure that worker file worker-javascript.js is available for your code. In code snippet above I use CDN to get Ace build, so worker is always available. You can configure JSHint via worker options.

Update: But if really need something beyond that you will need to do the following as my understanding goes:

  1. Create Worker and Mode for you kind of analysis
  2. Download Ace source code and install NodeJS
  3. Put your new files within correspond Ace source code folders
  4. Build Ace
  5. Add build files to your project
  6. Use new mode: editor.getSession().setMode("ace/mode/semicolonlineend");

Worker that perform line ending check will look something like that:

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var Mirror = require("../worker/mirror").Mirror;

var SemicolonLineEndCheckWorker = exports.SemicolonLineEndCheckWorker = function (sender) {
    Mirror.call(this, sender);
    this.setTimeout(500);
    this.setOptions();
};

oop.inherits(SemicolonLineEndCheckWorker, Mirror);

(function() {

    this.onUpdate = function () {
        var text = this.doc.getValue();
        var lines = text.replace(/^#!.*\n/, "\n").match(/[^\r\n]+/g);

        var errors = [];

        for (var i = 0; i < lines.length; i++) {
            var lastLineCharacter = lines[i].trim().slice(-1);
            if (lastLineCharacter === ';')
                continue;

            errors.push({
                row: i,
                column: lines[i].length-1,
                text: "Missing semicolon at the end of the line",
                type: "warning",
                raw: "Missing semicolon"
            });

        }

        this.sender.emit("annotate", errors);
    };

}).call(SemicolonLineEndCheckWorker.prototype);

});

New mode that uses worker:

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;

var Mode = function() { };
oop.inherits(Mode, TextMode);

(function() {

    this.createWorker = function(session) {
        var worker = new WorkerClient(["ace"], "ace/mode/semicolonlineend_worker", 
            "SemicolonLineEndCheckWorker");
        worker.attachToDocument(session.getDocument());

        worker.on("annotate", function(results) {
            session.setAnnotations(results.data);
        });

        worker.on("terminate", function() {
            session.clearAnnotations();
        });

        return worker;
    };

    this.$id = "ace/mode/semicolonlineend";
}).call(Mode.prototype);

exports.Mode = Mode;
});
like image 142
Leonid Vasilev Avatar answered Sep 28 '22 04:09

Leonid Vasilev