Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger autocomplete dynamically with ace editor: input commands and complete options

  1. I know how to use ace editor in web page
  2. I know how to add a completer

I want to do like this, input a command, a blank space, then press - (dash), let ace editor autocomplete options(parameters), what should I do?

For example, here is a command Print with options -a|-b|-c|-d, when I input Print -, how can trigger autocomplete, and let you select -a or -b or -c or -d?

like image 989
wwj Avatar asked Sep 16 '15 09:09

wwj


1 Answers

I solve it by myself. code as follows:

var langTools = ace.require("ace/ext/language_tools");
    var editor = ace.edit("stepEditor");
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/tcl");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: false,
        enableLiveAutocompletion: true
    });
    var wordList = [];
    var icc2Commands = null;
    jQuery.getJSON("auto_completion.json",function(obj){  
        icc2Commands = obj;
        for(var name in obj){         
            wordList.push(name);    
        }    
        for(var i = 0; i < 5; i++)
        {
            console.log(wordList[i]);
        }
    }); 
    var icc2Completer = {
        getCompletions: function(editor, session, pos, prefix, callback) {
            var curLine = session.getDocument().getLine(pos.row);
            var curTokens = curLine.slice(0, pos.column).split(/\s+/);
            var curCmd = curTokens[0];
            if (!curCmd) return;
            var lastToken = curTokens[curTokens.length-1];
            var candidates = [];
            if (lastToken && lastToken.match(/^-/)) {
              for (var option of icc2Commands[curCmd]) {
                if (option.startsWith(lastToken.slice(1))) {
                  candidates.push("-"+option);
                }
              }
              callback(null, candidates.map(function(ea) {
                return {name: ea, value: ea, score: 300, meta: "ICC2Option"};
              }));
            } 
            else{
                callback(null, wordList.map(function(word) {
                    return {
                        caption: word,
                        value: word,
                        meta: "ICC2Command"
                    };
                }));
            }
        }
    }
    langTools.addCompleter(icc2Completer);
like image 54
wwj Avatar answered Nov 17 '22 19:11

wwj