Search code examples
ace-editor

First tokenizing run when executing setValue on editor does not work like consecutive changes


I am testing out a properties editor with an out of the box theme (twilight) - which works as expected - and out of the box properties mode. Setting the initial text of properties in the editor via javascript (editor.setValue()) gets parsed as plain text (type : text) when tokenizing instead of properties (variable, keyword, string)

(See also following codepen: https://codepen.io/anon/pen/xjrvvG?editors=1111 )


UPDATE: loading following scripts within the page, solves the issue, but this cannot be the actual idea

<script src="./ace/theme-twilight.js" type="text/javascript" charset="utf-8"></script>
<script src="./ace/mode-properties.js" type="text/javascript" charset="utf-8"></script>

HTML:

 <div id="code" style="position: relative; width: 500px; height: 400px;"></div>

Javascript:

var editor = ace.edit("code");
var session = editor.getSession();

editor.setTheme("ace/theme/twilight");
session.setMode({
    path: "ace/mode/properties",
    v: Date.now()
});

session.on('change', function (e) {
    console.log(e);
    console.log(session.getLine(e.end.row).length);
    var TokenIterator = ace.require("ace/token_iterator").TokenIterator;
    var iterator = new TokenIterator(editor.getSession(), e.end.row, 0);
    var token = iterator.getCurrentToken();
    while (token && iterator.getCurrentTokenRow() === e.end.row) {
        console.log(token);
        token = iterator.stepForward();
    }
});

editor.getSession().setValue("#just a comment\n" +
    "database=localhost\n" +
    "database=remotehost\n" +
    "dbuser=uuu\n" +
    "dbpassword=password", 1);

Console log at page load (not expected since type = text is not correct for properties mode):

Object {
  action: "insert",
  end: Object {
    column: 19,
    row: 4
  },
  id: 1,
  lines: ["#just a comment", "database=localhost", "database=remotehost", "dbuser=uuu", "dbpassword=password"],
  start: Object {
    column: 0,
    row: 0
  }
}
19
Object {
  index: 0,
  start: 0,
  type: "text",
  value: "dbpassword=password"
}

When doing a change in the editor directly, the property is parsed correctly (variable, keyword, string):

Object {
  action: "insert",
  end: Object {
    column: 20,
    row: 4
  },
  id: 2,
  lines: ["d"],
  start: Object {
    column: 19,
    row: 4
  }
}
20
Object {
  index: 0,
  start: 0,
  type: "variable",
  value: "dbpassword"
}
Object {
  type: "keyword",
  value: "="
}
Object {
  type: "string",
  value: "passwordd"
}

Solution

  • when using setMode the mode is loaded asynchronously, so the first time it is parsed as text.

    When you include <script src="./ace/mode-properties.js" type="text/javascript" charset="utf-8"></script> the mode is loaded before the rest of your code, so on the first run editor already uses the correct mode