From 7af1f7cad2d237b9aad972bd498b4ef8c3b0781c Mon Sep 17 00:00:00 2001 From: Tomas Brejla Date: Fri, 9 Jul 2021 22:16:52 +0200 Subject: [PATCH] optimize rangeForDefun slowing repl printout #942 --- src/cursor-doc/token-cursor.ts | 55 +++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/src/cursor-doc/token-cursor.ts b/src/cursor-doc/token-cursor.ts index d9d4d7f2f..833d289f6 100644 --- a/src/cursor-doc/token-cursor.ts +++ b/src/cursor-doc/token-cursor.ts @@ -612,25 +612,46 @@ export class LispTokenCursor extends TokenCursor { * @param commentIsTopLevel? Controls */ rangeForDefun(offset: number, depth = 0, commentCreatesTopLevel = true): [number, number] { - const cursor = this.clone(); - while (cursor.forwardSexp()) { - if (cursor.offsetEnd >= offset) { - if (depth < 1 && cursor.getPrevToken().raw === ')') { - const commentCursor = cursor.clone(); - commentCursor.previous(); - if (commentCursor.getFunctionName() === 'comment' && commentCreatesTopLevel) { - commentCursor.backwardList(); - commentCursor.forwardWhitespace(); - commentCursor.forwardSexp(); - return commentCursor.rangeForDefun(offset, depth + 1); - } + const cursor = this.doc.getTokenCursor(offset); + if (cursor.getPrevToken().raw == ')') { + cursor.backwardSexp(); + } + if (cursor.getToken().type === 'eol' || cursor.getToken().type === 'ws') { + cursor.forwardWhitespace(); + } + if (cursor.getToken().raw == '(') { + cursor.next(); + } + if (cursor.getToken().raw === 'comment' && commentCreatesTopLevel) { + cursor.next(); + cursor.forwardWhitespace(); + } + if (cursor.getToken().raw == '(') { + cursor.next(); + } + do { + let rowColBefore = cursor.rowCol; + const peekForwardUpPrevCursor = cursor.clone(); + peekForwardUpPrevCursor.forwardList(); + peekForwardUpPrevCursor.upList(); + peekForwardUpPrevCursor.previous(); + if (peekForwardUpPrevCursor.getFunctionName() === 'comment' && commentCreatesTopLevel) { + break; + } + cursor.forwardList(); + if (!cursor.upList()) { + if (cursor.getPrevToken().type === 'eol' && cursor.getToken().type === 'eol') { + return [offset, offset] + } else { + return cursor.rangeForCurrentForm(0); } - const end = cursor.offsetStart; - cursor.backwardSexp(); - return [cursor.offsetStart, end]; } - } - return [offset, offset] + let rowColAfter = cursor.rowCol; + if (rowColAfter[0] == rowColBefore[0] && rowColAfter[1] == rowColBefore[1]) { + break; + } + } while (cursor.withinValidList()); + return cursor.rangeForCurrentForm(0); } rangesForTopLevelForms(): [number, number][] {