Search code examples
javascriptace-editor

Find all class and id names in an Ace Editor HTML script


What I'm trying to do: Collect all the class and id names in an Ace Editor html script.

Right now my plan is to detect user changes (.on('change'...)) and get the current token using the cursor position. If the token is a not 'unquoted' 'attribute-value' type, I want to iterate back through previous tokens in order to find the 'attribute-name' type token to which that 'attribute-value' belongs and identify whether it is a class or id (I can't just detect the creation of an 'attribute-name' token because the user can go back and change the attribute-values later without changing the name, and I need to detect those changes).

I can do everything except for get previous tokens. I looked up some documentation and the TokenIterator is supposed to be able to do that, but when I try to do something like var iter = new TokeIterator(), my console says that TokenIterator is undefined. I've searched google over and over, but found no results. If the truth is out there I'm obviously not using the right words to find it, but they're the only words I've got.

Is some way built into Ace to iterate through tokens? I know I'm not seeing all the properties and methods on the editor instance object when I console log it, because I can use methods in my script that I can't see in that log. Is there one there that does what I want?

If not, how do I load the TokenIterator? I think something similar went on when I tried to use SnippetManager a while back and it turned out I actually had to do this to make it work:

var tillPageLoaded = setInterval(function() {  // Makes sure page doesn't load forever on startup
    if( document.readyState === 'complete') {
        clearInterval(tillPageLoaded);
        ace.config.loadModule('ace/ext/language_tools', function () {
            editor.insertSnippet( myString );
        }); 
    }
}, 5);

Is this the same kind of situation? If so, what needs to be in .loadModules(...)? Do I need to reference a script somewhere? Does it need to be loaded some other way?

Is there built in functionality for Ace that would already do everything I want?

Other than that, if anyone has any better ideas of how to go about this with Ace, those would be very welcome.


Solution

  • you can get TokenIterator by using

    var TokenIterator = ace.require("ace/token_iterator").TokenIterator
    

    see https://github.com/ajaxorg/ace/blob/master/lib/ace/mode/folding/xml.js#L38 for an example of its usage.