Skip to content

Commit

Permalink
Fix: Embedded language position updates properly
Browse files Browse the repository at this point in the history
workspace.openTextDocument would not update the document when and new version get saved, which had for result to give a non-updated position.
  • Loading branch information
idillon-sfl committed Nov 14, 2023
1 parent c8712c7 commit e9b8df1
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions client/src/language/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,43 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */

import { type TextDocument, type Position, workspace } from 'vscode'
import fs from 'fs'

import { type TextDocument, Position } from 'vscode'

import { type EmbeddedLanguageDocInfos } from '../lib/src/types/embedded-languages'
import { logger } from '../lib/src/utils/OutputLogger'

export const getEmbeddedLanguageDocPosition = async (
originalTextDocument: TextDocument,
embeddedLanguageDocInfos: EmbeddedLanguageDocInfos,
originalPosition: Position
): Promise<Position> => {
): Promise<Position | undefined> => {
const originalOffset = originalTextDocument.offsetAt(originalPosition)
const embeddedLanguageDocOffset = embeddedLanguageDocInfos.characterIndexes[originalOffset]
const embeddedLanguageDoc = await workspace.openTextDocument(embeddedLanguageDocInfos.uri.replace('file://', ''))
return embeddedLanguageDoc.positionAt(embeddedLanguageDocOffset)
try {
const embeddedLanguageDocContent = await new Promise<string>((resolve, reject) => {
fs.readFile(embeddedLanguageDocInfos.uri.replace('file://', ''), { encoding: 'utf-8' },
(error, data) => { error !== null ? reject(error) : resolve(data) }
)
})
return getPosition(embeddedLanguageDocContent, embeddedLanguageDocOffset)
} catch (error) {
logger.error(`Failed to get embedded language document position: ${error as any}`)
return undefined
}
}

const getPosition = (documentContent: string, offset: number): Position => {
let line = 0
let character = 0
for (let i = 0; i < offset; i++) {
if (documentContent[i] === '\n') {
line++
character = 0
} else {
character++
}
}
return new Position(line, character)
}

0 comments on commit e9b8df1

Please sign in to comment.