Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Embedded language position updates properly #72

Merged
merged 1 commit into from
Nov 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading