Skip to content

Commit

Permalink
fix(native): get pathstr by cursor position (#4553)
Browse files Browse the repository at this point in the history
close #4549
  • Loading branch information
fannheyward authored Aug 31, 2023
1 parent 1c9c72f commit 02c2542
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/__tests__/completion/sources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { CancellationToken, CancellationTokenSource, Disposable } from 'vscode-l
import { Position, Range, TextEdit } from 'vscode-languageserver-types'
import { Around } from '../../completion/native/around'
import { Buffer } from '../../completion/native/buffer'
import { File, filterFiles, getDirectory, getFileItem, getItemsFromRoot, resolveEnvVariables } from '../../completion/native/file'
import { File, filterFiles, getDirectory, getFileItem, getFilePathFromLine, getItemsFromRoot, resolveEnvVariables } from '../../completion/native/file'
import Source, { firstMatchFuzzy } from '../../completion/source'
import VimSource from '../../completion/source-vim'
import sources, { Sources, logError, getSourceType } from '../../completion/sources'
Expand Down Expand Up @@ -352,6 +352,11 @@ describe('native sources', () => {
expect(res).toEqual([])
})

it('should getFilePathFromLine', () => {
expect(getFilePathFromLine('$HOME/ $PWD/', 6)).toBe('$HOME/')
expect(getFilePathFromLine('$HOME/ $PWD/', 12)).toBe('$PWD/')
})

it('should getFileItem', async () => {
expect(await getFileItem(__dirname, '')).toBeDefined()
expect(await getFileItem(__dirname, 'file_not_exists')).toBeNull()
Expand Down
15 changes: 14 additions & 1 deletion src/completion/native/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ export function resolveEnvVariables(str: string, env = process.env): string {
return replaced
}

export function getFilePathFromLine(line: string, cursorIndex: number): string {
let begin = cursorIndex - 1
let end = cursorIndex
while (begin >= 0 && line[begin] !== ' ') {
begin--
}
while (end < line.length && line[end] !== ' ') {
end++
}
return line.slice(begin + 1, end)
}

export async function getFileItem(root: string, filename: string): Promise<VimCompleteItem | null> {
let f = path.join(root, filename)
let stat = await statAsync(f)
Expand Down Expand Up @@ -85,7 +97,8 @@ export class File extends Source {

private getPathOption(opt: CompleteOption): PathOption | null {
let { line, colnr } = opt
let part = byteSlice(line, 0, colnr - 1)
let filepath = getFilePathFromLine(line, colnr - 1)
let part = byteSlice(filepath, 0, colnr - 1)
part = resolveEnvVariables(part)
if (!part || part.endsWith('//')) return null
let ms = part.match(pathRe)
Expand Down

0 comments on commit 02c2542

Please sign in to comment.