2
This commit is contained in:
1 parent
5ac164b407
commit
f93f6095af
94 files changed
+7877
-4018
No files matched your search
@@ -0,0 +1,136 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
import '../fuzzy_matcher.dart';
|
||||
import '../providers/completion_provider.dart';
|
||||
import 'completion_types.dart';
|
||||
|
||||
/// 补全调度引擎 (Completion Engine)
|
||||
///
|
||||
/// 核心职责:
|
||||
/// 1. 0ms 同步聚合本地所有同步 Provider(关键字、词法启发提取),保证首帧流畅弹出;
|
||||
/// 2. 异步发起 LSP 或远程 Provider 请求;
|
||||
/// 3. 基于 requestId 与版本号防抖校验,杜绝陈旧回包覆盖;
|
||||
/// 4. 统一执行 Fuzzy 模糊匹配打分、sortText 权重排序与截断;
|
||||
/// 5. 动态向绑定的 ValueNotifier 推流更新,实现平滑渐进增强。
|
||||
class CompletionEngine {
|
||||
CompletionEngine({
|
||||
required this.providers,
|
||||
this.maxSuggestions = 40,
|
||||
});
|
||||
|
||||
final List<CompletionProvider> providers;
|
||||
final int maxSuggestions;
|
||||
|
||||
int _lastRequestId = 0;
|
||||
|
||||
/// 异步直接请求补全(专为 LSP 异步语义流优化设计)
|
||||
Future<CodeAutocompleteEditingValue?> requestCompletionsAsync(
|
||||
CompletionContext context,
|
||||
) async {
|
||||
final currentRequestId = ++_lastRequestId;
|
||||
final currentInput = context.input;
|
||||
|
||||
try {
|
||||
final results = await Future.wait(
|
||||
providers.map((p) async {
|
||||
try {
|
||||
final res = await p.provideCompletions(context);
|
||||
return res;
|
||||
} catch (_) {
|
||||
return <SmartPrompt>[];
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// 请求过期(用户已键入新内容或已移动光标),直接废弃
|
||||
if (currentRequestId != _lastRequestId) return null;
|
||||
|
||||
final allPrompts = <SmartPrompt>[];
|
||||
final seenWords = <String>{};
|
||||
for (final list in results) {
|
||||
for (final p in list) {
|
||||
if (seenWords.add(p.word)) {
|
||||
allPrompts.add(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (allPrompts.isEmpty) return null;
|
||||
return scoreAndFilter(allPrompts, currentInput);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 兼容推流式调用
|
||||
CodeAutocompleteEditingValue? requestCompletions(
|
||||
CompletionContext context, {
|
||||
ValueNotifier<CodeAutocompleteEditingValue>? notifier,
|
||||
}) {
|
||||
if (notifier != null) {
|
||||
requestCompletionsAsync(context).then((value) {
|
||||
if (value != null) {
|
||||
notifier.value = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// 模糊匹配打分、权重排序与截取
|
||||
CodeAutocompleteEditingValue? scoreAndFilter(List<SmartPrompt> candidates, String input) {
|
||||
if (candidates.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final List<SmartPrompt> matchedPrompts = [];
|
||||
for (final candidate in candidates) {
|
||||
if (input.isEmpty) {
|
||||
matchedPrompts.add(candidate.copyWithScore(
|
||||
score: 100,
|
||||
matchedIndices: const [],
|
||||
));
|
||||
} else {
|
||||
final result = FuzzyMatcher.match(input, candidate.word);
|
||||
if (result.isMatch) {
|
||||
matchedPrompts.add(candidate.copyWithScore(
|
||||
score: result.score,
|
||||
matchedIndices: result.matchedIndices,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (matchedPrompts.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 按照得分降序排序,相同得分若有 LSP sortText 则依据 sortText 升序,否则按字典序升序
|
||||
matchedPrompts.sort((a, b) {
|
||||
final scoreCompare = b.score.compareTo(a.score);
|
||||
if (scoreCompare != 0) return scoreCompare;
|
||||
if (a.sortText != null && b.sortText != null) {
|
||||
final sortCompare = a.sortText!.compareTo(b.sortText!);
|
||||
if (sortCompare != 0) return sortCompare;
|
||||
}
|
||||
return a.word.compareTo(b.word);
|
||||
});
|
||||
|
||||
// 截取前 maxSuggestions 条最佳结果,保证 60fps 流畅渲染
|
||||
final limitedPrompts = matchedPrompts.take(maxSuggestions).toList();
|
||||
|
||||
return CodeAutocompleteEditingValue(
|
||||
input: input,
|
||||
prompts: limitedPrompts,
|
||||
index: 0,
|
||||
);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_lastRequestId++;
|
||||
for (final provider in providers) {
|
||||
provider.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
import '../fuzzy_matcher.dart';
|
||||
|
||||
/// 补全候选词类别
|
||||
enum SmartPromptKind {
|
||||
keyword,
|
||||
function,
|
||||
field,
|
||||
type,
|
||||
constant,
|
||||
word,
|
||||
}
|
||||
|
||||
/// 具有模糊匹配打分与高亮索引的工业级智能补全 Prompt
|
||||
class SmartPrompt extends CodePrompt {
|
||||
SmartPrompt({
|
||||
required super.word,
|
||||
this.type,
|
||||
this.kind = SmartPromptKind.word,
|
||||
this.customAutocomplete,
|
||||
this.parameters = const {},
|
||||
this.score = 0,
|
||||
this.matchedIndices = const [],
|
||||
this.detail,
|
||||
this.documentation,
|
||||
this.sortText,
|
||||
});
|
||||
|
||||
final String? type;
|
||||
final SmartPromptKind kind;
|
||||
final CodeAutocompleteResult? customAutocomplete;
|
||||
final Map<String, String> parameters;
|
||||
final String? detail;
|
||||
final String? documentation;
|
||||
final String? sortText;
|
||||
int score;
|
||||
List<int> matchedIndices;
|
||||
|
||||
@override
|
||||
CodeAutocompleteResult get autocomplete {
|
||||
if (customAutocomplete != null) {
|
||||
return customAutocomplete!;
|
||||
}
|
||||
if (kind == SmartPromptKind.function && parameters.isNotEmpty) {
|
||||
final paramStr = parameters.keys.join(', ');
|
||||
return CodeAutocompleteResult(
|
||||
input: '',
|
||||
word: '$word($paramStr)',
|
||||
selection: TextSelection.collapsed(offset: word.length + 1),
|
||||
);
|
||||
}
|
||||
return CodeAutocompleteResult.fromWord(word);
|
||||
}
|
||||
|
||||
@override
|
||||
bool match(String input) {
|
||||
if (input.isEmpty) return true;
|
||||
final res = FuzzyMatcher.match(input, word);
|
||||
if (res.isMatch) {
|
||||
score = res.score;
|
||||
matchedIndices = res.matchedIndices;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
SmartPrompt copyWithScore({
|
||||
required int score,
|
||||
required List<int> matchedIndices,
|
||||
}) {
|
||||
return SmartPrompt(
|
||||
word: word,
|
||||
type: type,
|
||||
kind: kind,
|
||||
customAutocomplete: customAutocomplete,
|
||||
parameters: parameters,
|
||||
score: score,
|
||||
matchedIndices: matchedIndices,
|
||||
detail: detail,
|
||||
documentation: documentation,
|
||||
sortText: sortText,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 代码补全上下文请求参数
|
||||
class CompletionContext {
|
||||
final String input;
|
||||
final String? triggerCharacter;
|
||||
final String? target;
|
||||
final String? filePath;
|
||||
final int lineIndex;
|
||||
final int characterOffset;
|
||||
final CodeLine codeLine;
|
||||
final CodeLines? codeLines;
|
||||
final CodeLineSelection selection;
|
||||
|
||||
const CompletionContext({
|
||||
required this.input,
|
||||
this.triggerCharacter,
|
||||
this.target,
|
||||
this.filePath,
|
||||
required this.lineIndex,
|
||||
required this.characterOffset,
|
||||
required this.codeLine,
|
||||
this.codeLines,
|
||||
required this.selection,
|
||||
});
|
||||
|
||||
bool get isDotTrigger => triggerCharacter == '.';
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import 'dart:math';
|
||||
|
||||
/// 模糊匹配与打字纠错结果
|
||||
class FuzzyMatchResult {
|
||||
const FuzzyMatchResult({
|
||||
required this.isMatch,
|
||||
required this.score,
|
||||
this.matchedIndices = const [],
|
||||
});
|
||||
|
||||
static const notMatched = FuzzyMatchResult(isMatch: false, score: -1);
|
||||
|
||||
final bool isMatch;
|
||||
final int score;
|
||||
final List<int> matchedIndices;
|
||||
}
|
||||
|
||||
/// 工业级代码模糊匹配与容错纠错打分器
|
||||
class FuzzyMatcher {
|
||||
const FuzzyMatcher();
|
||||
|
||||
/// 对 [pattern](用户输入)与 [target](候选词)进行匹配打分
|
||||
///
|
||||
/// 支持:
|
||||
/// 1. 精确匹配 / 精确前缀匹配 (Prefix Match)
|
||||
/// 2. 忽略大小写前缀匹配 (Case-insensitive Prefix)
|
||||
/// 3. 驼峰与下划线缩写匹配 (CamelCase / Snake_case)
|
||||
/// 4. 连续子序列匹配 (Subsequence Match with Consecutive Bonus)
|
||||
/// 5. 打字手误纠错 (Typo Tolerance / Levenshtein Distance)
|
||||
static FuzzyMatchResult match(String pattern, String target) {
|
||||
if (pattern.isEmpty) {
|
||||
return const FuzzyMatchResult(isMatch: true, score: 100);
|
||||
}
|
||||
if (target.isEmpty) {
|
||||
return FuzzyMatchResult.notMatched;
|
||||
}
|
||||
|
||||
// 1. 完全相同
|
||||
if (pattern == target) {
|
||||
return FuzzyMatchResult(
|
||||
isMatch: true,
|
||||
score: 3000,
|
||||
matchedIndices: List.generate(pattern.length, (i) => i),
|
||||
);
|
||||
}
|
||||
|
||||
// 2. 严格区分大小写的前缀匹配 (最高优先级)
|
||||
if (target.startsWith(pattern)) {
|
||||
final score = 2000 - (target.length - pattern.length);
|
||||
return FuzzyMatchResult(
|
||||
isMatch: true,
|
||||
score: score,
|
||||
matchedIndices: List.generate(pattern.length, (i) => i),
|
||||
);
|
||||
}
|
||||
|
||||
final lowerPattern = pattern.toLowerCase();
|
||||
final lowerTarget = target.toLowerCase();
|
||||
|
||||
// 3. 忽略大小写的前缀匹配
|
||||
if (lowerTarget.startsWith(lowerPattern)) {
|
||||
final score = 1500 - (target.length - pattern.length);
|
||||
return FuzzyMatchResult(
|
||||
isMatch: true,
|
||||
score: score,
|
||||
matchedIndices: List.generate(pattern.length, (i) => i),
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 驼峰与下划线缩写匹配 (例如 "fb" 匹配 "FloatingActionButton", "tv" 匹配 "text_view")
|
||||
final camelMatch = _matchCamelOrSeparator(lowerPattern, target);
|
||||
if (camelMatch.isMatch) {
|
||||
return camelMatch;
|
||||
}
|
||||
|
||||
// 5. 字符子序列匹配 (Subsequence Match)
|
||||
final subseqMatch = _matchSubsequence(lowerPattern, lowerTarget, target);
|
||||
if (subseqMatch.isMatch) {
|
||||
return subseqMatch;
|
||||
}
|
||||
|
||||
// 6. 拼写手误纠错 (Typo Tolerance / Levenshtein Distance)
|
||||
// 当输入字符长度 >= 3 时,允许前缀 1 处编辑距离错误(如 prnt -> print, lenght -> length)
|
||||
// 当输入字符长度 >= 6 时,允许前缀 2 处编辑距离错误
|
||||
if (pattern.length >= 3) {
|
||||
final typoMatch = _matchTypo(lowerPattern, lowerTarget, target);
|
||||
if (typoMatch.isMatch) {
|
||||
return typoMatch;
|
||||
}
|
||||
}
|
||||
|
||||
return FuzzyMatchResult.notMatched;
|
||||
}
|
||||
|
||||
/// 驼峰与分隔符匹配
|
||||
static FuzzyMatchResult _matchCamelOrSeparator(String lowerPattern, String target) {
|
||||
final List<int> wordStartIndices = [];
|
||||
|
||||
for (int i = 0; i < target.length; i++) {
|
||||
final char = target[i];
|
||||
if (i == 0) {
|
||||
wordStartIndices.add(i);
|
||||
} else if (char == '_' || char == '-' || char == '.') {
|
||||
if (i + 1 < target.length) {
|
||||
wordStartIndices.add(i + 1);
|
||||
}
|
||||
} else {
|
||||
final isUpper = char.toUpperCase() == char && char.toLowerCase() != char;
|
||||
final prevChar = target[i - 1];
|
||||
final isPrevLower = prevChar.toLowerCase() == prevChar && prevChar.toUpperCase() != prevChar;
|
||||
if (isUpper && isPrevLower) {
|
||||
wordStartIndices.add(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lowerPattern.length <= wordStartIndices.length) {
|
||||
int pIdx = 0;
|
||||
final List<int> matched = [];
|
||||
for (final sIdx in wordStartIndices) {
|
||||
if (pIdx < lowerPattern.length &&
|
||||
target[sIdx].toLowerCase() == lowerPattern[pIdx]) {
|
||||
matched.add(sIdx);
|
||||
pIdx++;
|
||||
}
|
||||
}
|
||||
if (pIdx == lowerPattern.length) {
|
||||
final score = 1000 - (target.length - lowerPattern.length) * 2;
|
||||
return FuzzyMatchResult(
|
||||
isMatch: true,
|
||||
score: max(score, 600),
|
||||
matchedIndices: matched,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return FuzzyMatchResult.notMatched;
|
||||
}
|
||||
|
||||
/// 子序列匹配(考虑连续命中加分)
|
||||
static FuzzyMatchResult _matchSubsequence(
|
||||
String lowerPattern,
|
||||
String lowerTarget,
|
||||
String target,
|
||||
) {
|
||||
int pIdx = 0;
|
||||
int tIdx = 0;
|
||||
final List<int> matched = [];
|
||||
int consecutiveCount = 0;
|
||||
int score = 700;
|
||||
|
||||
while (pIdx < lowerPattern.length && tIdx < lowerTarget.length) {
|
||||
if (lowerPattern[pIdx] == lowerTarget[tIdx]) {
|
||||
matched.add(tIdx);
|
||||
// 大小写一致加分
|
||||
if (pIdx < target.length && target[tIdx] == lowerPattern[pIdx]) {
|
||||
score += 10;
|
||||
}
|
||||
// 连续匹配加分
|
||||
if (matched.length > 1 && matched.last == matched[matched.length - 2] + 1) {
|
||||
consecutiveCount++;
|
||||
score += consecutiveCount * 25;
|
||||
} else {
|
||||
consecutiveCount = 0;
|
||||
}
|
||||
pIdx++;
|
||||
}
|
||||
tIdx++;
|
||||
}
|
||||
|
||||
if (pIdx == lowerPattern.length) {
|
||||
score -= matched.first * 15;
|
||||
score -= (target.length - lowerPattern.length) * 2;
|
||||
return FuzzyMatchResult(
|
||||
isMatch: true,
|
||||
score: max(score, 450),
|
||||
matchedIndices: matched,
|
||||
);
|
||||
}
|
||||
|
||||
return FuzzyMatchResult.notMatched;
|
||||
}
|
||||
|
||||
/// 打字手误纠错(基于编辑距离对比前缀)
|
||||
static FuzzyMatchResult _matchTypo(
|
||||
String lowerPattern,
|
||||
String lowerTarget,
|
||||
String target,
|
||||
) {
|
||||
final int pLen = lowerPattern.length;
|
||||
final int minLen = max(1, pLen - 1);
|
||||
final int maxLen = min(lowerTarget.length, pLen + 1);
|
||||
|
||||
int bestDistance = 999;
|
||||
int bestPrefixLen = pLen;
|
||||
|
||||
for (int len = minLen; len <= maxLen; len++) {
|
||||
final prefix = lowerTarget.substring(0, len);
|
||||
final dist = _levenshteinDistance(lowerPattern, prefix);
|
||||
if (dist < bestDistance) {
|
||||
bestDistance = dist;
|
||||
bestPrefixLen = len;
|
||||
}
|
||||
}
|
||||
|
||||
final int maxAllowedDist = pLen >= 6 ? 2 : 1;
|
||||
if (bestDistance <= maxAllowedDist) {
|
||||
final score = 380 - (bestDistance * 80) - (target.length - pLen);
|
||||
return FuzzyMatchResult(
|
||||
isMatch: true,
|
||||
score: max(score, 150),
|
||||
matchedIndices: List.generate(min(bestPrefixLen, target.length), (i) => i),
|
||||
);
|
||||
}
|
||||
|
||||
return FuzzyMatchResult.notMatched;
|
||||
}
|
||||
|
||||
/// 计算两个字符串的 Levenshtein 编辑距离
|
||||
static int _levenshteinDistance(String s1, String s2) {
|
||||
if (s1 == s2) return 0;
|
||||
if (s1.isEmpty) return s2.length;
|
||||
if (s2.isEmpty) return s1.length;
|
||||
|
||||
List<int> prev = List<int>.generate(s2.length + 1, (i) => i);
|
||||
List<int> curr = List<int>.filled(s2.length + 1, 0);
|
||||
|
||||
for (int i = 0; i < s1.length; i++) {
|
||||
curr[0] = i + 1;
|
||||
for (int j = 0; j < s2.length; j++) {
|
||||
final cost = (s1[i] == s2[j]) ? 0 : 1;
|
||||
curr[j + 1] = min(
|
||||
curr[j] + 1,
|
||||
min(
|
||||
prev[j + 1] + 1,
|
||||
prev[j] + cost,
|
||||
),
|
||||
);
|
||||
}
|
||||
final temp = prev;
|
||||
prev = curr;
|
||||
curr = temp;
|
||||
}
|
||||
|
||||
return prev[s2.length];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import 'dart:async';
|
||||
import '../core/completion_types.dart';
|
||||
|
||||
/// 补全数据源提供者抽象契约
|
||||
abstract class CompletionProvider {
|
||||
/// 提供者唯一标识
|
||||
String get id;
|
||||
|
||||
/// 是否为异步远程数据源(如 LSP)
|
||||
bool get isAsync => false;
|
||||
|
||||
/// 依据上下文提供补全候选项
|
||||
FutureOr<List<SmartPrompt>> provideCompletions(CompletionContext context);
|
||||
|
||||
/// 释放资源
|
||||
void dispose() {}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
import '../../lsp/lsp_manager.dart';
|
||||
import '../../lsp/lsp_protocol.dart';
|
||||
import '../core/completion_types.dart';
|
||||
import 'completion_provider.dart';
|
||||
|
||||
/// 远程 LSP 语言服务补全数据源提供者
|
||||
class LspCompletionProvider implements CompletionProvider {
|
||||
const LspCompletionProvider();
|
||||
|
||||
@override
|
||||
String get id => 'lsp';
|
||||
|
||||
@override
|
||||
bool get isAsync => true;
|
||||
|
||||
@override
|
||||
Future<List<SmartPrompt>> provideCompletions(CompletionContext context) async {
|
||||
final filePath = context.filePath;
|
||||
if (filePath == null || filePath.isEmpty) {
|
||||
return const [];
|
||||
}
|
||||
|
||||
final session = LspManager.instance.getExistingSession(filePath);
|
||||
if (session == null || !session.isInitialized) {
|
||||
return const [];
|
||||
}
|
||||
|
||||
final lspItems = await session.getCompletions(
|
||||
filePath,
|
||||
context.lineIndex,
|
||||
context.characterOffset,
|
||||
);
|
||||
|
||||
return lspItems.map(fromLspItem).toList();
|
||||
}
|
||||
|
||||
/// 将 LSP 原始协议的 LspCompletionItem 转换为统一领域模型 SmartPrompt
|
||||
static SmartPrompt fromLspItem(LspCompletionItem item) {
|
||||
SmartPromptKind kind;
|
||||
switch (item.kind) {
|
||||
case 2: // Method
|
||||
case 3: // Function
|
||||
case 4: // Constructor
|
||||
kind = SmartPromptKind.function;
|
||||
break;
|
||||
case 5: // Field
|
||||
case 6: // Variable
|
||||
case 10: // Property
|
||||
kind = SmartPromptKind.field;
|
||||
break;
|
||||
case 7: // Class
|
||||
case 8: // Interface
|
||||
case 13: // Enum
|
||||
case 22: // Struct
|
||||
case 25: // TypeParameter
|
||||
kind = SmartPromptKind.type;
|
||||
break;
|
||||
case 14: // Keyword
|
||||
kind = SmartPromptKind.keyword;
|
||||
break;
|
||||
case 21: // Constant
|
||||
kind = SmartPromptKind.constant;
|
||||
break;
|
||||
default:
|
||||
kind = SmartPromptKind.word;
|
||||
}
|
||||
|
||||
final insert = item.effectiveInsertText;
|
||||
final word = item.label.isNotEmpty ? item.label : insert;
|
||||
|
||||
CodeAutocompleteResult? customAuto;
|
||||
if (insert != word) {
|
||||
customAuto = CodeAutocompleteResult(
|
||||
input: '',
|
||||
word: insert,
|
||||
selection: TextSelection.collapsed(offset: insert.length),
|
||||
);
|
||||
}
|
||||
|
||||
return SmartPrompt(
|
||||
word: word,
|
||||
kind: kind,
|
||||
type: item.detail,
|
||||
detail: item.detail,
|
||||
documentation: item.documentation,
|
||||
sortText: item.sortText,
|
||||
customAutocomplete: customAuto,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:re_editor/re_editor.dart';
|
||||
import 'core/completion_engine.dart';
|
||||
import 'core/completion_types.dart';
|
||||
import 'providers/completion_provider.dart';
|
||||
import 'providers/lsp_completion_provider.dart';
|
||||
|
||||
export 'core/completion_engine.dart';
|
||||
export 'core/completion_types.dart';
|
||||
export 'providers/completion_provider.dart';
|
||||
export 'providers/lsp_completion_provider.dart';
|
||||
|
||||
/// 工业级智能代码补全构建器适配器
|
||||
///
|
||||
/// 实现 re_editor 的 CodeAutocompletePromptsBuilder 协议,
|
||||
/// 将编辑器的输入上下文规范化后,转派给 LSP CompletionEngine 异步调度处理。
|
||||
class SmartCodeAutocompletePromptsBuilder implements CodeAutocompletePromptsBuilder {
|
||||
SmartCodeAutocompletePromptsBuilder({
|
||||
this.controller,
|
||||
this.filePath,
|
||||
this.enableLspCompletion = true,
|
||||
@Deprecated('本地补全已完全移除,此参数无效') bool enableLocalCompletion = false,
|
||||
@Deprecated('本地补全已完全移除,此参数无效') dynamic language,
|
||||
@Deprecated('本地补全已完全移除,此参数无效') List<CodePrompt> keywordPrompts = const [],
|
||||
@Deprecated('本地补全已完全移除,此参数无效') List<CodePrompt> directPrompts = const [],
|
||||
@Deprecated('本地补全已完全移除,此参数无效') Map<String, List<CodePrompt>> relatedPrompts = const {},
|
||||
List<CompletionProvider>? customProviders,
|
||||
}) {
|
||||
final providers = <CompletionProvider>[
|
||||
if (customProviders != null)
|
||||
...customProviders
|
||||
else if (enableLspCompletion)
|
||||
const LspCompletionProvider(),
|
||||
];
|
||||
|
||||
engine = CompletionEngine(providers: providers);
|
||||
}
|
||||
|
||||
final CodeLineEditingController? controller;
|
||||
final String? filePath;
|
||||
final bool enableLspCompletion;
|
||||
|
||||
late final CompletionEngine engine;
|
||||
|
||||
/// 当前活跃的悬浮面板 ValueNotifier(由 CodeAutocompleteView 动态注入绑定)
|
||||
ValueNotifier<CodeAutocompleteEditingValue>? activeNotifier;
|
||||
|
||||
@override
|
||||
FutureOr<CodeAutocompleteEditingValue?> build(
|
||||
BuildContext context,
|
||||
CodeLine codeLine,
|
||||
CodeLineSelection selection,
|
||||
) {
|
||||
if (!enableLspCompletion || engine.providers.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final String text = codeLine.text;
|
||||
if (selection.extentOffset > text.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Characters charactersBefore = text.substring(0, selection.extentOffset).characters;
|
||||
if (charactersBefore.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 检查是否在普通闭合双引号或单引号字符串中(简易校验)
|
||||
final String linePrefix = text.substring(0, selection.extentOffset);
|
||||
final int singleQuoteCount = "'".allMatches(linePrefix).length;
|
||||
final int doubleQuoteCount = '"'.allMatches(linePrefix).length;
|
||||
if (singleQuoteCount % 2 == 1 || doubleQuoteCount % 2 == 1) {
|
||||
// 位于字符串字面量内部,不触发代码智能补全
|
||||
return null;
|
||||
}
|
||||
|
||||
final String input;
|
||||
String? triggerCharacter;
|
||||
String? target;
|
||||
|
||||
if (charactersBefore.takeLast(1).string == '.') {
|
||||
triggerCharacter = '.';
|
||||
input = '';
|
||||
int start = charactersBefore.length - 2;
|
||||
for (; start >= 0; start--) {
|
||||
final char = charactersBefore.elementAt(start);
|
||||
if (!_isValidIdentifierChar(char)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
target = charactersBefore.getRange(start + 1, charactersBefore.length - 1).string;
|
||||
} else {
|
||||
int start = charactersBefore.length - 1;
|
||||
for (; start >= 0; start--) {
|
||||
final char = charactersBefore.elementAt(start);
|
||||
if (!_isValidIdentifierChar(char)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
input = charactersBefore.getRange(start + 1, charactersBefore.length).string;
|
||||
if (input.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (start > 0 && charactersBefore.elementAt(start) == '.') {
|
||||
triggerCharacter = '.';
|
||||
final int mark = start;
|
||||
for (start = start - 1; start >= 0; start--) {
|
||||
final char = charactersBefore.elementAt(start);
|
||||
if (!_isValidIdentifierChar(char)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
target = charactersBefore.getRange(start + 1, mark).string;
|
||||
}
|
||||
}
|
||||
|
||||
final completionContext = CompletionContext(
|
||||
input: input,
|
||||
triggerCharacter: triggerCharacter,
|
||||
target: target,
|
||||
filePath: filePath,
|
||||
lineIndex: selection.extentIndex,
|
||||
characterOffset: selection.extentOffset,
|
||||
codeLine: codeLine,
|
||||
codeLines: controller?.codeLines,
|
||||
selection: selection,
|
||||
);
|
||||
|
||||
// 原生异步发起 LSP 智能语义补全请求
|
||||
return engine.requestCompletionsAsync(completionContext);
|
||||
}
|
||||
|
||||
static bool _isValidIdentifierChar(String char) {
|
||||
if (char.isEmpty) return false;
|
||||
final code = char.codeUnitAt(0);
|
||||
return (code >= 65 && code <= 90) || // A-Z
|
||||
(code >= 97 && code <= 122) || // a-z
|
||||
(code >= 48 && code <= 57) || // 0-9
|
||||
code == 95; // _
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user