Search code examples
javascriptace-editor

Is it possible to serialize an Ace Session object?


I'd like to serialize and store Ace Session objects, so I can open a "File" and restore everything, value, selection, cursor position, mode, etc.

I've tried JSON.stringify(session) and it throws a circular error.

Any ideas?


Solution

  • the simplest version would be

    var session = editor.session
    state = {}
    state.value = session.getValue();
    state.selection = session.selection.toJSON()
    state.options = session.getOptions()
    state.mode = session.getMode().$id
    state.folds = session.getAllFolds().map(function(fold) {
        return {
            start       : fold.start,
            end         : fold.end,
            placeholder : fold.placeholder
        };
    });
    state.scrollTop = session.getScrollTop()
    state.scrollLeft = session.getScrollLeft()
    
    JSON.stringify(state)
    

    and to restore

    session.setValue(state.value)
    session.selection.fromJSON(state.selection)
    session.setOptions(state.options)
    session.setMode(state.mode)
    try {
        state.folds.forEach(function(fold){
            session.addFold(fold.placeholder, 
                Range.fromPoints(fold.start, fold.end));
        });
    } catch(e) {}
    session.setScrollTop(state.scrollTop)
    session.setScrollTop(state.scrollLeft)
    

    this doesn't cover restoring undomanager which is doable but a little trickier. you can try to bump this issue https://github.com/ajaxorg/ace/issues/1452