【问题标题】:Preserve cursor position after setValue in Ace editor在 Ace 编辑器中的 setValue 之后保留光标位置
【发布时间】:2020-01-19 15:05:20
【问题描述】:

我正在使用 ace 开发一个实时编辑器,并在编辑器发生变化并且光标将自身定位在文本下方的随机位置时调用 editor.setValue()。我想要的很明显,在设置值加载新文本后,光标准确定位到文本结束的位置。有什么想法吗??

【问题讨论】:

    标签: ace-editor


    【解决方案1】:

    这根本不是很简单,因为如果文本发生了变化,same position 将不再相同。

    如果要恢复相同的选择,可以使用 toJSON 方法

    before = editor.selection.toJSON();
    editor.setValue(editor.getValue() + "xxx")
    editor.selection.fromJSON(before)
    

    但是除了浪费性能之外,在换行的情况下也无法正常工作,例如editor.setValue("xxx\n" + editor.getValue())

    一般来说最好使用 session.insert/session.remove 方法

    editor.session.insert({row: 0, column: 0}, "xxx\n")
    editor.session.remove({start: {row: 0, column: 1}, end: {row: 1, column: 1}})
    

    【讨论】:

    • 谢谢。这些方法 (session.insert/remove) 究竟有什么作用?
    猜你喜欢
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多