Skip to content

Commit

Permalink
feat: use incremental instead of full content updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Leon committed Jan 26, 2024
1 parent 1624094 commit 6258e78
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const main = async () => {
triggerCharacters: ["{", "(", ")", "=", ">", " ", ",", ":", ".", "<", "/"]
},
textDocumentSync: {
change: 1,
change: 2,
}
}
})
Expand Down
42 changes: 32 additions & 10 deletions src/lsp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ enum DiagnosticSeverity {
}

type Position = {
start: number,
end: number
line: number,
character: number
}

type Range = {
Expand Down Expand Up @@ -81,25 +81,47 @@ class Service {

this.on(Event.DidOpen, ({ ctx, request }) => {
ctx.currentUri = request.params.textDocument.uri
ctx.contents = request.params.textDocument.text
ctx.language = request.params.textDocument.languageId
ctx.contentVersion = 0
})

this.on(Event.Shutdown, ({ ctx, request }) => {
this.on(Event.Shutdown, () => {
log("received shutdown request")
process.exit(0)
})

this.on(Event.DidOpen, async ({ ctx, request }) => {
ctx.contents = request.params.textDocument.text
ctx.language = request.params.textDocument.languageId
ctx.contentVersion = 0
})

this.on(Event.DidChange, async ({ ctx, request }) => {
ctx.contents = request.params.contentChanges[0].text
request.params.contentChanges.forEach((change) => {
this.positionalUpdate(change.text, change.range)
})

ctx.contentVersion = request.params.textDocument.version
})
}

positionalUpdate(text: string, range: Range) {
const lines = this.contents.split("\n")
const start = range.start.line
const end = range.end.line
const startLine = lines[start]
const endLine = lines[end]
const startLineStart = startLine.substring(0, range.start.character)
const endLineEnd = endLine.substring(range.end.character)
const newLines = [startLineStart + text + endLineEnd]

const newContents = lines.reduce((acc, line, index) => {
if (index < start || index > end) {
acc.push(line)
} else if (index === start) {
acc.push(newLines[0])
}
return acc
}, [])

this.contents = newContents.join("\n")
}

on(event: string, callback: (request: EventRequest) => void) {
const parent = this

Expand Down

0 comments on commit 6258e78

Please sign in to comment.