I'm writing Nano like editor in javascript and have problem with calculating cursor position and file offset for display:

I have two variables _rows and settings.verticalMoveOffset (which is default set to 9 like in Nano) when you move cursor in line 20 and there are 19 rows the cursor is offset by verticalMoveOffset.

I work on this few hours and can't figure out how to map file pointer (line) to editor cursor and offset of the file (the line from which it start the view).

Last try was

if (y >= this._rows) {
    var page = Math.floor(y / (this._rows-this._settings.verticalMoveOffset))-1;
    var new_offset = (this._rows - this._settings.verticalMoveOffset) * page;
    if (this._offset !== new_offset) {
        this._view(new_offset);
    }
    cursor_y = y - (this._rows*page) + this._settings.verticalMoveOffset;
} else {
    if (y <= this._rows - this._settings.verticalMoveOffset - 1 &&
        this._offset !== 0) {
        this._pointer.x = x;
        this._pointer.y = y;
        this._view(0);
        cursor_y = y;
    } else if (this._offset !== 0) {
        cursor_y = (y - this._settings.verticalMoveOffset) + 1;
    } else {
        cursor_y = y;
    }
}

It work when I swich from page 1st to page 2nd and back, to 3rd page it switch for 1 line to fast, the cursor_y is -1. I try to put plus or minus 1 in various places when calculating page but it didn't work.

Anybody can help me with this?

有帮助吗?

解决方案

I found solution (this._offset is set by this._view)

var offset = this._offset + this._rows - cursor_offset;
if (y-this._offset >= this._rows) {
    cursor_y = y - offset;
    if (this._offset !== offset) {
        this._pointer.x = x;
        this._pointer.y = y;
        this._view(offset);
    }
} else if (y-this._offset < 0) {
    var new_offset = this._offset - this._rows + cursor_offset;
    this._pointer.x = x;
    this._pointer.y = y;
    this._view(new_offset);
    cursor_y = y - new_offset;
} else {
    cursor_y = y - offset + cursor_offset + 1;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top