Add Javascript into Custom Language - ACE Editor

2019-06-03 00:02发布

问题:

I am using ACE editor for a custom metalanguage using JSON as base. But I want to add Javascript when the user types something like

"custom" : function(param){ .... javascript code ..... }

The idea is to highlight the javascript code using the styling already used for JS.

I am not usng the JSON highligther, just use my own.

I saw in the documentation something "Embedding a different highlighter" (https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode)

But it doesnt works. Here is my code:

Thanks!

回答1:

This is a bit hard to do since you need to count braces to detect when javascript mode ends. The following code seems to work well

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

var oop = require("../lib/oop");
var JsonHighlightRules = require("./json_highlight_rules").JsonHighlightRules;
var JavaScriptHighlightRules = require("./javascript_highlight_rules")
   .JavaScriptHighlightRules;

var JsonPlusHighlightRules = function() {
    JsonHighlightRules.call(this);

    this.$rules.start.unshift({  
        regex: "function",
        next: "js-start",
        token: "keyword"
    }); 
    this.embedRules(JavaScriptHighlightRules, "js-", [{ 
        regex: "[{}]", onMatch: function(val, state, stack) {
            this.next = "";
            console.log(stack, this.next, val);
            if (val == "{") {
                stack.unshift("js-start", state);
                return "paren";
            }
            if (val == "}" && stack.length) {
                stack.shift();
                this.next = stack.shift();
                if (this.next.indexOf("quasi") != -1)
                    return "paren.string";
            } 
            if (val == "}" && !stack.length) {
                this.next = "start";
            } 
            return "paren";
        }
    }], ["no_regex"]); 

};

oop.inherits(JsonPlusHighlightRules, JsonHighlightRules);

exports.JsonPlusHighlightRules = JsonPlusHighlightRules;
});