最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I add new highlight rules at runtime with Ace Code Editor? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to inject custom keywords into whatever mode is set on the editor. I have tried the following:

rules = editor.session.getMode().$highlightRules
startRules = rules.$rules.start

startRules.push({
  regex: "\\w+"
  onMatch: rules.createKeywordMapper({customToken: "one|two"})
})

rules.addRules({start: startRules})

editor.session.bgTokenizer.start(0)

What I'm trying to acplish is to be able to write in the word "two" and have it be wrapped around a custom token

I'm trying to inject custom keywords into whatever mode is set on the editor. I have tried the following:

rules = editor.session.getMode().$highlightRules
startRules = rules.$rules.start

startRules.push({
  regex: "\\w+"
  onMatch: rules.createKeywordMapper({customToken: "one|two"})
})

rules.addRules({start: startRules})

editor.session.bgTokenizer.start(0)

What I'm trying to acplish is to be able to write in the word "two" and have it be wrapped around a custom token

Share Improve this question edited Sep 6, 2016 at 16:08 Jason M asked Sep 6, 2016 at 15:53 Jason MJason M 1,06315 silver badges28 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

I'm a few years late, but I found a solution recently that might help you and others. Check out this issue I opened on their Github repo (Ace Editor Repo). Using this solution, you can define your own token like I have at runtime. In my example, I made a token called "my_token". The editor will wrap this in a div with a class name that matches your token name prefixed with "ace_". So something like "ace_my_token".

Be aware that part of my solution required me to highlight my new rule with highest priority as I needed it to highlight differently even when within a string which is why I put it first in the rule set. You may need to adjust where you insert your rule depending on how you want it highlighted.

this.editor = ace.edit(this.editorId);
var session = this.editor.session;
this.language = this.language || 'text';
session.setMode('ace/mode/' + this.language, function() {
    var rules = session.$mode.$highlightRules.getRules();
    for (var stateName in rules) {
        if (Object.prototype.hasOwnProperty.call(rules, stateName)) {
            rules[stateName].unshift({
                token: 'my_token',
                regex: 'two'
            });
        }
    }
    // force recreation of tokenizer
    session.$mode.$tokenizer = null;
    session.bgTokenizer.setTokenizer(session.$mode.getTokenizer());
    // force re-highlight whole document
    session.bgTokenizer.start(0);
});

Here's a demo: https://jsbin./yogeqewehu/edit?html,css,console,output

发布评论

评论列表(0)

  1. 暂无评论