Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to highlight/change color of certain words in Ace Editor?

Tags:

ace-editor

I am setting text using the following:

var someString = 'Mark has solved the problem';
editor.getSession().setValue(someString);

In above case, Need only 'Mark' to appear in blue color. Is there a way to load html tags in ace editor or manipulate styling of certain words?

like image 655
Pradosh Avatar asked May 02 '17 10:05

Pradosh


1 Answers

You can create custom highlight rules to do this

<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<meta charset="utf-8">
<style type="text/css" media="screen">
    #editor { 
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
    .ace_customTokenName {color: darkred}
</style>
</head>
<body>
 <div id="editor" style="height: 500px; width: 800px"></div>
    
<script src="https://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<script>
define('ace/mode/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 CustomHighlightRules = require("ace/mode/custom_highlight_rules").CustomHighlightRules;

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

(function() {

}).call(Mode.prototype);

exports.Mode = Mode;
});

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

var CustomHighlightRules = function() {

    var keywordMapper = this.createKeywordMapper({
        "variable.language": "this",
        "keyword": "Mark|Ben|Bill",
        "constant.language": "true|false|null",
        // it is also possible to use css, but that may conflict with themes
        "customTokenName": "problem"
    }, "text", true);

    this.$rules = {
        "start": [            
            {
                regex: "\\w+\\b",
                token: keywordMapper
            },
        ]
    };
    this.normalizeRules()
};

oop.inherits(CustomHighlightRules, TextHighlightRules);

exports.CustomHighlightRules = CustomHighlightRules;
});


var editor = ace.edit("editor");

editor.session.setMode("ace/mode/custom");
var someString = 'Mark has solved the problem';
editor.session.setValue(someString);

</script>
</body>
</html>
like image 184
a user Avatar answered Nov 16 '22 22:11

a user