summaryrefslogtreecommitdiff
path: root/internal/lsp
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2025-09-06 10:25:36 +0300
committerPaul Buetow <paul@buetow.org>2025-09-06 10:25:36 +0300
commit5be9532cfa630f4aacd8d879c3e4f5cc316da0fa (patch)
tree0a901680fccd1e2703ffdbd9284ccff932be1d67 /internal/lsp
parent70f1d0e78c57dfa5beae779b3d392b6e6fa44c14 (diff)
feat(lsp): configurable inline/chat triggers; switch inline markers to >text>/>>text>; update docs and example config; tests updated to new triggers and raise LSP coverage to >=85%; chore: remove semicolon legacy; chore(mage): auto-refresh coverage daily if docs/coverage.out is older than 24h
Diffstat (limited to 'internal/lsp')
-rw-r--r--internal/lsp/codeaction_test.go2
-rw-r--r--internal/lsp/completion_prefix_strip_test.go102
-rw-r--r--internal/lsp/debounce_throttle_more_test.go36
-rw-r--r--internal/lsp/document_test.go27
-rw-r--r--internal/lsp/handlers.go15
-rw-r--r--internal/lsp/handlers_completion.go51
-rw-r--r--internal/lsp/handlers_document.go79
-rw-r--r--internal/lsp/handlers_end_to_end_test.go4
-rw-r--r--internal/lsp/handlers_helpers_test.go56
-rw-r--r--internal/lsp/handlers_test.go78
-rw-r--r--internal/lsp/handlers_utils.go259
-rw-r--r--internal/lsp/helpers_inline_prompt_test.go58
-rw-r--r--internal/lsp/helpers_more_test.go22
-rw-r--r--internal/lsp/init_and_trigger_test.go5
-rw-r--r--internal/lsp/instruction_table_test.go3
-rw-r--r--internal/lsp/llm_stats_test.go11
-rw-r--r--internal/lsp/postprocess_indent_test.go5
-rw-r--r--internal/lsp/provider_native_success_test.go21
-rw-r--r--internal/lsp/server.go40
-rw-r--r--internal/lsp/transport_test.go15
-rw-r--r--internal/lsp/triggers_config_test.go74
21 files changed, 628 insertions, 335 deletions
diff --git a/internal/lsp/codeaction_test.go b/internal/lsp/codeaction_test.go
index 5a74d66..4de0790 100644
--- a/internal/lsp/codeaction_test.go
+++ b/internal/lsp/codeaction_test.go
@@ -22,7 +22,7 @@ func TestBuildRewriteCodeAction_LazyAndResolves(t *testing.T) {
s := newTestServer()
s.llmClient = fakeLLM{resp: "REWRITTEN"}
p := CodeActionParams{TextDocument: TextDocumentIdentifier{URI: "file:///t.go"}, Range: Range{Start: Position{Line: 1, Character: 2}, End: Position{Line: 3, Character: 4}}}
- sel := ";rewrite;\nold code"
+ sel := ">rewrite>\nold code"
ca := s.buildRewriteCodeAction(p, sel)
if ca == nil {
t.Fatalf("expected code action")
diff --git a/internal/lsp/completion_prefix_strip_test.go b/internal/lsp/completion_prefix_strip_test.go
index 99a08d6..e8e70f5 100644
--- a/internal/lsp/completion_prefix_strip_test.go
+++ b/internal/lsp/completion_prefix_strip_test.go
@@ -55,30 +55,30 @@ func TestTryLLMCompletion_ManualInvokeAfterWhitespace_Allows(t *testing.T) {
}
}
-func TestTryLLMCompletion_InlineSemicolonPromptAlwaysTriggers(t *testing.T) {
- s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
- s.llmClient = fakeLLM{resp: "replacement"}
- line := "prefix ;do something; suffix"
- // No trigger char immediately before cursor; place cursor at end
- p := CompletionParams{Position: Position{Line: 0, Character: len(line)}, TextDocument: TextDocumentIdentifier{URI: "file://inline.go"}}
- items, ok := s.tryLLMCompletion(p, "", line, "", "", "", false, "")
- if !ok || len(items) == 0 {
- t.Fatalf("expected completion to trigger on inline ;text; prompt")
- }
+func TestTryLLMCompletion_InlinePromptAlwaysTriggers(t *testing.T) {
+ s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
+ s.llmClient = fakeLLM{resp: "replacement"}
+ line := "prefix >do something> suffix"
+ // No trigger char immediately before cursor; place cursor at end
+ p := CompletionParams{Position: Position{Line: 0, Character: len(line)}, TextDocument: TextDocumentIdentifier{URI: "file://inline.go"}}
+ items, ok := s.tryLLMCompletion(p, "", line, "", "", "", false, "")
+ if !ok || len(items) == 0 {
+ t.Fatalf("expected completion to trigger on inline >text> prompt")
+ }
}
-func TestTryLLMCompletion_DoubleSemicolonEmpty_DoesNotAutoTrigger(t *testing.T) {
+func TestTryLLMCompletion_DoubleOpenEmpty_DoesNotAutoTrigger(t *testing.T) {
s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
fake := &countingLLM{}
s.llmClient = fake
- line := ";; " // empty content after ';;' should not force-trigger
+ line := ">> " // empty content after double-open should not force-trigger
p := CompletionParams{Position: Position{Line: 0, Character: len(line)}, TextDocument: TextDocumentIdentifier{URI: "file://empty-inline.go"}}
items, ok := s.tryLLMCompletion(p, "", line, "", "", "", false, "")
if !ok {
t.Fatalf("expected ok=true for non-trigger path")
}
if len(items) != 0 {
- t.Fatalf("expected no items when inline ';;' is empty")
+ t.Fatalf("expected no items when inline double-open is empty")
}
if fake.calls != 0 {
t.Fatalf("LLM should not be called; calls=%d", fake.calls)
@@ -86,63 +86,63 @@ func TestTryLLMCompletion_DoubleSemicolonEmpty_DoesNotAutoTrigger(t *testing.T)
}
func TestHasDoubleSemicolonTrigger_Variants(t *testing.T) {
- if hasDoubleSemicolonTrigger(";;") {
- t.Fatalf("bare ';;' should not trigger")
- }
- if hasDoubleSemicolonTrigger(";; ;") {
- t.Fatalf("';;' followed by space should not trigger")
- }
- if hasDoubleSemicolonTrigger(";;;") {
- t.Fatalf("';;;' should not trigger (no content)")
- }
- if !hasDoubleSemicolonTrigger(";;x;") {
- t.Fatalf("expected trigger for ';;x;' pattern")
- }
+ if hasDoubleOpenTrigger(">>") {
+ t.Fatalf("bare double-open should not trigger")
+ }
+ if hasDoubleOpenTrigger(">> ") {
+ t.Fatalf("double-open followed by space should not trigger")
+ }
+ if hasDoubleOpenTrigger(">>>") {
+ t.Fatalf("';;;' should not trigger (no content)")
+ }
+ if !hasDoubleOpenTrigger(">>x>") {
+ t.Fatalf("expected trigger for ';;x;' pattern")
+ }
}
-func TestBareDoubleSemicolonPreventsAutoTriggerEvenWithOtherTriggers(t *testing.T) {
- s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
- fake := &countingLLM{}
- s.llmClient = fake
- // Place a '.' earlier but also include bare ';;' at end; should not auto-trigger
- line := "obj. call ;;"
+func TestBareDoubleOpenPreventsAutoTriggerEvenWithOtherTriggers(t *testing.T) {
+ s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
+ fake := &countingLLM{}
+ s.llmClient = fake
+ // Place a '.' earlier but also include bare double-open at end; should not auto-trigger
+ line := "obj. call >>"
p := CompletionParams{Position: Position{Line: 0, Character: len(line)}, TextDocument: TextDocumentIdentifier{URI: "file://bare-ds.go"}}
items, ok := s.tryLLMCompletion(p, "", line, "", "", "", false, "")
if !ok {
t.Fatalf("expected ok=true (handled), but not auto-triggering")
}
- if len(items) != 0 {
- t.Fatalf("expected no items due to bare ';;'")
- }
+ if len(items) != 0 {
+ t.Fatalf("expected no items due to bare double-open")
+ }
if fake.calls != 0 {
t.Fatalf("LLM should not be called; calls=%d", fake.calls)
}
}
-func TestBareDoubleSemicolonOnNextLine_PreventsAutoTrigger(t *testing.T) {
- s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
- fake := &countingLLM{}
- s.llmClient = fake
- current := "expression := flag.String(\"expression\", \"\", \"Expression to evaluate\")"
- below := ";;"
+func TestBareDoubleOpenOnNextLine_PreventsAutoTrigger(t *testing.T) {
+ s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
+ fake := &countingLLM{}
+ s.llmClient = fake
+ current := "expression := flag.String(\"expression\", \"\", \"Expression to evaluate\")"
+ below := ">>"
p := CompletionParams{Position: Position{Line: 0, Character: len(current)}, TextDocument: TextDocumentIdentifier{URI: "file://nextline.go"}}
items, ok := s.tryLLMCompletion(p, "", current, below, "", "", false, "")
if !ok {
t.Fatalf("expected ok=true handled")
}
- if len(items) != 0 {
- t.Fatalf("expected no items due to bare ';;' on next line")
- }
+ if len(items) != 0 {
+ t.Fatalf("expected no items due to bare double-open on next line")
+ }
if fake.calls != 0 {
t.Fatalf("LLM should not be called; calls=%d", fake.calls)
}
}
-func TestBareDoubleSemicolonPreventsManualInvoke(t *testing.T) {
- s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
- fake := &countingLLM{}
- s.llmClient = fake
- line := ";;"
+func TestBareDoubleOpenPreventsManualInvoke(t *testing.T) {
+ s := &Server{maxTokens: 32, triggerChars: []string{".", ":", "/", "_"}, compCache: make(map[string]string)}
+ fake := &countingLLM{}
+ s.llmClient = fake
+ line := ">>"
p := CompletionParams{Position: Position{Line: 0, Character: len(line)}, TextDocument: TextDocumentIdentifier{URI: "file://bare-ds-manual.go"}}
// Simulate manual invoke
p.Context = json.RawMessage([]byte(`{"triggerKind":1}`))
@@ -150,9 +150,9 @@ func TestBareDoubleSemicolonPreventsManualInvoke(t *testing.T) {
if !ok {
t.Fatalf("expected ok=true (handled)")
}
- if len(items) != 0 {
- t.Fatalf("expected no items for bare ';;' even with manual invoke")
- }
+ if len(items) != 0 {
+ t.Fatalf("expected no items for bare double-open even with manual invoke")
+ }
if fake.calls != 0 {
t.Fatalf("LLM should not be called; calls=%d", fake.calls)
}
diff --git a/internal/lsp/debounce_throttle_more_test.go b/internal/lsp/debounce_throttle_more_test.go
new file mode 100644
index 0000000..cb11ea4
--- /dev/null
+++ b/internal/lsp/debounce_throttle_more_test.go
@@ -0,0 +1,36 @@
+package lsp
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+func TestWaitForDebounce_WaitsRoughlyDebounce(t *testing.T) {
+ s := newTestServer()
+ s.completionDebounce = 20 * time.Millisecond
+ s.mu.Lock()
+ s.lastInput = time.Now()
+ s.mu.Unlock()
+ start := time.Now()
+ s.waitForDebounce(context.Background())
+ if elapsed := time.Since(start); elapsed < 15*time.Millisecond {
+ t.Fatalf("debounce did not wait long enough: %v", elapsed)
+ }
+}
+
+func TestWaitForThrottle_WaitsRoughlyInterval(t *testing.T) {
+ s := newTestServer()
+ s.throttleInterval = 20 * time.Millisecond
+ s.mu.Lock()
+ s.lastLLMCall = time.Now()
+ s.mu.Unlock()
+ start := time.Now()
+ if !s.waitForThrottle(context.Background()) {
+ t.Fatalf("waitForThrottle returned false")
+ }
+ if elapsed := time.Since(start); elapsed < 15*time.Millisecond {
+ t.Fatalf("throttle did not wait long enough: %v", elapsed)
+ }
+}
+
diff --git a/internal/lsp/document_test.go b/internal/lsp/document_test.go
index 4bd96e2..5fee18b 100644
--- a/internal/lsp/document_test.go
+++ b/internal/lsp/document_test.go
@@ -9,10 +9,20 @@ import (
)
func newTestServer() *Server {
- return &Server{
- logger: log.New(io.Discard, "", 0),
- docs: make(map[string]*document),
- }
+ s := &Server{
+ logger: log.New(io.Discard, "", 0),
+ docs: make(map[string]*document),
+ inlineOpen: ">",
+ inlineClose: ">",
+ chatSuffix: ">",
+ chatPrefixes: []string{"?","!",":",";"},
+ }
+ // Keep package-level helpers in sync for tests using free functions
+ inlineOpenChar = '>'
+ inlineCloseChar = '>'
+ chatSuffixChar = '>'
+ chatPrefixSingles = []string{"?","!",":",";"}
+ return s
}
func TestSplitLines(t *testing.T) {
@@ -60,6 +70,15 @@ func TestLineContext_EmptyDoc(t *testing.T) {
}
}
+func TestDocBeforeAfter_ClampsIndices(t *testing.T) {
+ s := newTestServer()
+ uri := "file:///clamp.go"
+ s.setDocument(uri, "abc\nxyz")
+ // Position beyond document length should be clamped safely
+ before, after := s.docBeforeAfter(uri, Position{Line: 99, Character: 99})
+ if before == "" && after == "" { t.Fatalf("expected some text with clamped indices") }
+}
+
func TestTrimLen(t *testing.T) {
long := strings.Repeat("a", 205)
got := trimLen(long)
diff --git a/internal/lsp/handlers.go b/internal/lsp/handlers.go
index 547be67..5e7d86d 100644
--- a/internal/lsp/handlers.go
+++ b/internal/lsp/handlers.go
@@ -51,7 +51,7 @@ func findFirstInstructionInLine(line string) (instr string, cleaned string, ok b
text string
}
cands := []cand{}
- if t, l, r, ok := findStrictSemicolonTag(line); ok {
+ if t, l, r, ok := findStrictInlineTag(line); ok {
cands = append(cands, cand{start: l, end: r, text: t})
}
if i := strings.Index(line, "/*"); i >= 0 {
@@ -298,8 +298,9 @@ func (s *Server) isTriggerEvent(p CompletionParams, current string) bool {
b, _ := json.Marshal(p.Context)
_ = json.Unmarshal(b, &ctx)
}
- // If the line contains a bare ';;' (no ';;text;'), do not treat as a trigger source.
- if strings.Contains(current, ";;") && !hasDoubleSemicolonTrigger(current) {
+ // If configured and the line contains a bare double-open marker (e.g., '>>' with no '>>text>'),
+ // do not treat as a trigger source.
+ if s.inlineOpen != "" && strings.Contains(current, s.inlineOpen+s.inlineOpen) && !hasDoubleOpenTrigger(current) {
return false
}
// TriggerKind 1 = Invoked (manual). Always allow manual invoke.
@@ -326,10 +327,10 @@ func (s *Server) isTriggerEvent(p CompletionParams, current string) bool {
if idx <= 0 || idx > len(current) {
return false
}
- // Bare ';;' should not trigger via fallback char either
- if strings.Contains(current, ";;") && !hasDoubleSemicolonTrigger(current) {
- return false
- }
+ // Bare double-open should not trigger via fallback char either (only when configured)
+ if s.inlineOpen != "" && strings.Contains(current, s.inlineOpen+s.inlineOpen) && !hasDoubleOpenTrigger(current) {
+ return false
+ }
ch := string(current[idx-1])
for _, c := range s.triggerChars {
if c == ch {
diff --git a/internal/lsp/handlers_completion.go b/internal/lsp/handlers_completion.go
index 576fc3d..036e591 100644
--- a/internal/lsp/handlers_completion.go
+++ b/internal/lsp/handlers_completion.go
@@ -93,10 +93,10 @@ func (s *Server) tryLLMCompletion(p CompletionParams, above, current, below, fun
logging.AnsiGreen, logging.PreviewForLog(cleaned), logging.AnsiBase)
return s.makeCompletionItems(cleaned, inParams, current, p, docStr), true
}
- if (isBareDoubleSemicolon(current) || isBareDoubleSemicolon(below)) && !manualInvoke {
- logging.Logf("lsp ", "%scompletion skip=empty-double-semicolon line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase)
- return []CompletionItem{}, true
- }
+ if (isBareDoubleOpen(current) || isBareDoubleOpen(below)) {
+ logging.Logf("lsp ", "%scompletion skip=empty-double-semicolon line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase)
+ return []CompletionItem{}, true
+ }
if !inParams && !s.prefixHeuristicAllows(inlinePrompt, current, p, manualInvoke) {
logging.Logf("lsp ", "%scompletion skip=short-prefix line=%d char=%d current=%q%s", logging.AnsiYellow, p.Position.Line, p.Position.Character, trimLen(current), logging.AnsiBase)
@@ -163,14 +163,19 @@ func parseManualInvoke(ctx any) bool {
// shouldSuppressForChatTriggerEOL returns true when a chat trigger like ">" follows ?, !, :, or ; at EOL.
func (s *Server) shouldSuppressForChatTriggerEOL(current string, p CompletionParams) bool {
- if t := strings.TrimRight(current, " \t"); len(t) >= 2 && t[len(t)-1] == '>' {
- prev := t[len(t)-2]
- if prev == '?' || prev == '!' || prev == ':' || prev == ';' {
- logging.Logf("lsp ", "completion skip=chat-trigger-eol uri=%s line=%d", p.TextDocument.URI, p.Position.Line)
- return true
- }
- }
- return false
+ t := strings.TrimRight(current, " \t")
+ if s.chatSuffix == "" { return false }
+ if strings.HasSuffix(t, s.chatSuffix) {
+ if len(t) < len(s.chatSuffix)+1 { return false }
+ prev := string(t[len(t)-len(s.chatSuffix)-1])
+ for _, pf := range s.chatPrefixes {
+ if prev == pf {
+ logging.Logf("lsp ", "completion skip=chat-trigger-eol uri=%s line=%d", p.TextDocument.URI, p.Position.Line)
+ return true
+ }
+ }
+ }
+ return false
}
// prefixHeuristicAllows applies minimal prefix rules unless inlinePrompt or structural triggers apply.
@@ -244,12 +249,12 @@ func (s *Server) tryProviderNativeCompletion(current string, p CompletionParams,
if cleaned != "" {
cleaned = stripDuplicateGeneralPrefix(current[:p.Position.Character], cleaned)
}
- if cleaned != "" && hasDoubleSemicolonTrigger(current) {
- indent := leadingIndent(current)
- if indent != "" {
- cleaned = applyIndent(indent, cleaned)
- }
- }
+ if cleaned != "" && hasDoubleOpenTrigger(current) {
+ indent := leadingIndent(current)
+ if indent != "" {
+ cleaned = applyIndent(indent, cleaned)
+ }
+ }
if strings.TrimSpace(cleaned) != "" {
key := s.completionCacheKey(p, above, current, below, funcCtx, inParams, hasExtra, extraText)
s.completionCachePut(key, cleaned)
@@ -354,10 +359,10 @@ func (s *Server) postProcessCompletion(text string, leftOfCursor string, current
if cleaned != "" {
cleaned = stripDuplicateGeneralPrefix(leftOfCursor, cleaned)
}
- if cleaned != "" && hasDoubleSemicolonTrigger(currentLine) {
- if indent := leadingIndent(currentLine); indent != "" {
- cleaned = applyIndent(indent, cleaned)
- }
- }
+ if cleaned != "" && hasDoubleOpenTrigger(currentLine) {
+ if indent := leadingIndent(currentLine); indent != "" {
+ cleaned = applyIndent(indent, cleaned)
+ }
+ }
return cleaned
}
diff --git a/internal/lsp/handlers_document.go b/internal/lsp/handlers_document.go
index 5b83d78..3f9d4b0 100644
--- a/internal/lsp/handlers_document.go
+++ b/internal/lsp/handlers_document.go
@@ -10,6 +10,11 @@ import (
"time"
)
+// Package-level chat trigger vars for helpers without Server receiver.
+// NewServer assigns these from configuration on startup.
+var chatSuffixChar byte = '>'
+var chatPrefixSingles = []string{"?", "!", ":", ";"}
+
func (s *Server) handleDidOpen(req Request) {
var p DidOpenTextDocumentParams
if err := json.Unmarshal(req.Params, &p); err == nil {
@@ -92,7 +97,7 @@ func (s *Server) detectAndHandleChat(uri string) {
if d == nil || len(d.lines) == 0 {
return
}
- for i, raw := range d.lines {
+ for i, raw := range d.lines {
// Find last non-space character index
j := len(raw) - 1
for j >= 0 {
@@ -102,14 +107,25 @@ func (s *Server) detectAndHandleChat(uri string) {
}
break
}
- if j < 1 {
- continue
- } // need at least two chars
- pair := raw[j-1 : j+1]
- isTrigger := pair == "?>" || pair == "!>" || pair == ":>" || pair == ";>"
- if !isTrigger {
- continue
- }
+ if j < 0 {
+ continue
+ }
+ // Check suffix/prefix according to configuration
+ if s.chatSuffix == "" {
+ continue
+ }
+ // Last non-space must equal suffix
+ if string(raw[j]) != s.chatSuffix {
+ continue
+ }
+ // Require at least one char before suffix and that char must be in chatPrefixes
+ if j < 1 { continue }
+ prev := string(raw[j-1])
+ isTrigger := false
+ for _, pfx := range s.chatPrefixes {
+ if prev == pfx { isTrigger = true; break }
+ }
+ if !isTrigger { continue }
// Avoid double-answering: if the next non-empty line starts with '>' we skip.
k := i + 1
for k < len(d.lines) && strings.TrimSpace(d.lines[k]) == "" {
@@ -119,9 +135,9 @@ func (s *Server) detectAndHandleChat(uri string) {
continue
}
// Derive prompt by removing only the trailing '>'
- removeCount := 1
+ removeCount := len(s.chatSuffix)
base := raw[:j+1-removeCount]
- prompt := strings.TrimSpace(base)
+ prompt := strings.TrimSpace(base)
if prompt == "" {
continue
}
@@ -230,26 +246,27 @@ func (s *Server) buildChatHistory(uri string, lineIdx int, currentPrompt string)
// stripTrailingTrigger removes the trailing chat trigger punctuation from a line if present.
func stripTrailingTrigger(sx string) string {
- s := strings.TrimRight(sx, " \t")
- if len(s) >= 2 && s[len(s)-1] == '>' { // new triggers
- prev := s[len(s)-2]
- if prev == '?' || prev == '!' || prev == ':' || prev == ';' {
- return strings.TrimRight(s[:len(s)-1], " \t")
- }
- }
- if strings.HasSuffix(s, ";;") { // legacy inline cleanup used in history building
- return strings.TrimRight(strings.TrimSuffix(s, ";;"), " \t")
- }
- if len(s) == 0 {
- return sx
- }
- last := s[len(s)-1]
- switch last { // legacy: remove one trailing punctuation
- case '?', '!', ':':
- return strings.TrimRight(s[:len(s)-1], " \t")
- default:
- return sx
- }
+ s := strings.TrimRight(sx, " \t")
+ if len(s) == 0 {
+ return sx
+ }
+ // Configurable suffix removal when preceded by configured prefixes
+ if len(s) >= 2 && s[len(s)-1] == chatSuffixChar {
+ prev := string(s[len(s)-2])
+ for _, pf := range chatPrefixSingles {
+ if prev == pf {
+ return strings.TrimRight(s[:len(s)-1], " \t")
+ }
+ }
+ }
+ // Legacy: remove one trailing punctuation (?, !, :) to build history nicely
+ last := s[len(s)-1]
+ switch last {
+ case '?', '!', ':':
+ return strings.TrimRight(s[:len(s)-1], " \t")
+ default:
+ return sx
+ }
}
// clientApplyEdit sends a workspace/applyEdit request to the client.
diff --git a/internal/lsp/handlers_end_to_end_test.go b/internal/lsp/handlers_end_to_end_test.go
index 73478e9..fd66a3c 100644
--- a/internal/lsp/handlers_end_to_end_test.go
+++ b/internal/lsp/handlers_end_to_end_test.go
@@ -66,6 +66,8 @@ func TestHandleCodeAction_ListsHexaiActions(t *testing.T) {
// Prepare server
var out bytes.Buffer
s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out}
+ s.chatSuffix = ">"
+ s.chatPrefixes = []string{"?","!",":",";"}
s.llmClient = fakeLLM{resp: "// doc\nfunc add(a,b int) int { return a+b }"}
// Document with a function
@@ -190,7 +192,7 @@ func TestHandle_Dispatch_Initialize(t *testing.T) {
func TestDetectAndHandleChat_InsertsReply(t *testing.T) {
var out bytes.Buffer
- s := &Server{logger: log.New(io.Discard, "", 0), docs: make(map[string]*document), out: &out}
+ s := NewServer(bytes.NewReader(nil), &out, log.New(io.Discard, "", 0), ServerOptions{})
s.llmClient = fakeLLM{resp: tut.MultilineChatReply()}
uri := "file:///chat.go"
// Place a prompt line with a supported trigger at EOL, then a blank line
diff --git a/internal/lsp/handlers_helpers_test.go b/internal/lsp/handlers_helpers_test.go
index eb7f273..24a9690 100644
--- a/internal/lsp/handlers_helpers_test.go
+++ b/internal/lsp/handlers_helpers_test.go
@@ -6,32 +6,32 @@ import (
)
func TestHasDoubleSemicolonTrigger(t *testing.T) {
- cases := []struct {
- line string
- want bool
- }{
- {";;todo; remove this", true},
- {"prefix ;;x; suffix", true},
- {";; spaced ;", false},
- {"no markers", false},
- {";;x ; space before close", false},
- }
- for _, tc := range cases {
- got := hasDoubleSemicolonTrigger(tc.line)
- if got != tc.want {
- t.Fatalf("hasDoubleSemicolonTrigger(%q)=%v want %v", tc.line, got, tc.want)
- }
- }
+ cases := []struct {
+ line string
+ want bool
+ }{
+ {">>todo> remove this", true},
+ {"prefix >>x> suffix", true},
+ {">> spaced >", false},
+ {"no markers", false},
+ {">>x > space before close", false},
+ }
+ for _, tc := range cases {
+ got := hasDoubleOpenTrigger(tc.line)
+ if got != tc.want {
+ t.Fatalf("hasDoubleOpenTrigger(%q)=%v want %v", tc.line, got, tc.want)
+ }
+ }
}
func TestCollectSemicolonMarkers(t *testing.T) {
- line := "keep ;ok; this and ;another; that"
- edits := collectSemicolonMarkers(line, 7)
- if len(edits) != 2 {
- t.Fatalf("expected 2 edits, got %d", len(edits))
- }
- // Validate the first edit aligns with ;ok;
- start := strings.Index(line, ";ok;")
+ line := "keep >ok> this and >another> that"
+ edits := collectSemicolonMarkers(line, 7)
+ if len(edits) != 2 {
+ t.Fatalf("expected 2 edits, got %d", len(edits))
+ }
+ // Validate the first edit aligns with ;ok;
+ start := strings.Index(line, ">ok>")
if start < 0 {
t.Fatalf("test setup: missing ;ok;")
}
@@ -41,11 +41,11 @@ func TestCollectSemicolonMarkers(t *testing.T) {
}
func TestPromptRemovalEditsForLine_WholeLine(t *testing.T) {
- line := ";;todo; remove this whole line"
- edits := promptRemovalEditsForLine(line, 3)
- if len(edits) != 1 {
- t.Fatalf("expected 1 whole-line edit, got %d", len(edits))
- }
+ line := ">>todo> remove this whole line"
+ edits := promptRemovalEditsForLine(line, 3)
+ if len(edits) != 1 {
+ t.Fatalf("expected 1 whole-line edit, got %d", len(edits))
+ }
e := edits[0]
if e.Range.Start.Line != 3 || e.Range.End.Line != 3 || e.Range.Start.Character != 0 || e.Range.End.Character != len(line) {
t.Fatalf("unexpected range for whole-line removal: %+v", e.Range)
diff --git a/internal/lsp/handlers_test.go b/internal/lsp/handlers_test.go
index 5b84254..8fdd34f 100644
--- a/internal/lsp/handlers_test.go
+++ b/internal/lsp/handlers_test.go
@@ -14,8 +14,8 @@ func TestFindFirstInstructionInLine_NoMarker(t *testing.T) {
}
}
-func TestFindFirstInstructionInLine_StrictSemicolon_Basic(t *testing.T) {
- line := "prefix ;rename var; suffix"
+func TestFindFirstInstructionInLine_StrictInline_Basic(t *testing.T) {
+ line := "prefix >rename var> suffix"
instr, cleaned, ok := findFirstInstructionInLine(line)
if !ok {
t.Fatalf("expected ok=true")
@@ -29,8 +29,8 @@ func TestFindFirstInstructionInLine_StrictSemicolon_Basic(t *testing.T) {
}
}
-func TestFindFirstInstructionInLine_StrictSemicolon_TrailingSpacesTrimmed(t *testing.T) {
- line := "code;fix; \t\t"
+func TestFindFirstInstructionInLine_StrictInline_TrailingSpacesTrimmed(t *testing.T) {
+ line := "code>fix> \t\t"
instr, cleaned, ok := findFirstInstructionInLine(line)
if !ok {
t.Fatalf("expected ok=true")
@@ -43,17 +43,17 @@ func TestFindFirstInstructionInLine_StrictSemicolon_TrailingSpacesTrimmed(t *tes
}
}
-func TestFindFirstInstructionInLine_Semicolon_InvalidPatterns(t *testing.T) {
- cases := []string{
- "prefix ; bad; suffix", // space after first ';' ⇒ invalid
- "prefix ;bad ; suffix", // space before closing ';' ⇒ invalid
- "prefix ; ; suffix", // empty inner ⇒ invalid
- }
- for _, line := range cases {
- if instr, _, ok := findFirstInstructionInLine(line); ok && instr != "" {
- t.Fatalf("%q: expected no semicolon instruction; got instr=%q", line, instr)
- }
- }
+func TestFindFirstInstructionInLine_Inline_InvalidPatterns(t *testing.T) {
+ cases := []string{
+ "prefix > bad> suffix", // space after first '>' ⇒ invalid
+ "prefix >bad > suffix", // space before closing '>' ⇒ invalid
+ "prefix > > suffix", // empty inner ⇒ invalid
+ }
+ for _, line := range cases {
+ if instr, _, ok := findFirstInstructionInLine(line); ok && instr != "" {
+ t.Fatalf("%q: expected no inline instruction; got instr=%q", line, instr)
+ }
+ }
}
func TestFindFirstInstructionInLine_CBlockComment(t *testing.T) {
@@ -126,22 +126,22 @@ func TestFindFirstInstructionInLine_DoubleDash(t *testing.T) {
}
}
-func TestFindFirstInstructionInLine_EarliestWins_CommentOverSemicolon(t *testing.T) {
- line := "aa // comment ;not this; trailing"
+func TestFindFirstInstructionInLine_EarliestWins_CommentOverInline(t *testing.T) {
+ line := "aa // comment >not this> trailing"
instr, cleaned, ok := findFirstInstructionInLine(line)
if !ok {
t.Fatalf("expected ok=true")
}
- if instr != "comment ;not this; trailing" {
- t.Fatalf("instr got %q want %q", instr, "comment ;not this; trailing")
- }
+ if instr != "comment >not this> trailing" {
+ t.Fatalf("instr got %q want %q", instr, "comment >not this> trailing")
+ }
if cleaned != "aa" {
t.Fatalf("cleaned got %q want %q", cleaned, "aa")
}
}
-func TestFindFirstInstructionInLine_EarliestWins_SemicolonOverComment(t *testing.T) {
- line := "aa ;short; // comment"
+func TestFindFirstInstructionInLine_EarliestWins_InlineOverComment(t *testing.T) {
+ line := "aa >short> // comment"
instr, cleaned, ok := findFirstInstructionInLine(line)
if !ok {
t.Fatalf("expected ok=true")
@@ -155,21 +155,21 @@ func TestFindFirstInstructionInLine_EarliestWins_SemicolonOverComment(t *testing
}
}
-func TestFindStrictSemicolonTag_Various(t *testing.T) {
- // basic
- if text, l, r, ok := findStrictSemicolonTag("pre;do it;post"); !ok || text != "do it" || l != 3 || r != 10 {
- t.Fatalf("unexpected: ok=%v text=%q l=%d r=%d", ok, text, l, r)
- }
- // at start
- if text, l, r, ok := findStrictSemicolonTag(";x;"); !ok || text != "x" || l != 0 || r != 3 {
- t.Fatalf("unexpected at start: ok=%v text=%q l=%d r=%d", ok, text, l, r)
- }
- // double opening ';' should still allow a tag starting at the second ';'
- if text, _, _, ok := findStrictSemicolonTag("prefix ;;bad; suffix"); !ok || text != "bad" {
- t.Fatalf("unexpected double-open handling: ok=%v text=%q", ok, text)
- }
- // inner spaces directly after first ';' or before last ';' invalidate the tag
- if _, _, _, ok := findStrictSemicolonTag("a; inner ;b"); ok {
- t.Fatalf("expected invalid strict tag due to spaces at boundaries")
- }
+func TestFindStrictInlineTag_Various(t *testing.T) {
+ // basic
+ if text, l, r, ok := findStrictInlineTag("pre>do it>post"); !ok || text != "do it" || l != 3 || r != 10 {
+ t.Fatalf("unexpected: ok=%v text=%q l=%d r=%d", ok, text, l, r)
+ }
+ // at start
+ if text, l, r, ok := findStrictInlineTag(">x>"); !ok || text != "x" || l != 0 || r != 3 {
+ t.Fatalf("unexpected at start: ok=%v text=%q l=%d r=%d", ok, text, l, r)
+ }
+ // double opening '>>' should still allow a tag starting at the second '>'
+ if text, _, _, ok := findStrictInlineTag("prefix >>bad> suffix"); !ok || text != "bad" {
+ t.Fatalf("unexpected double-open handling: ok=%v text=%q", ok, text)
+ }
+ // inner spaces directly after first '>' or before last '>' invalidate the tag
+ if _, _, _, ok := findStrictInlineTag("a> inner >b"); ok {
+ t.Fatalf("expected invalid strict tag due to spaces at boundaries")
+ }
}
diff --git a/internal/lsp/handlers_utils.go b/internal/lsp/handlers_utils.go
index 42b35a5..e2c35e3 100644
--- a/internal/lsp/handlers_utils.go
+++ b/internal/lsp/handlers_utils.go
@@ -9,6 +9,11 @@ import (
"time"
)
+// Configurable inline trigger characters (default to '>') used by free helpers below.
+// NewServer assigns these based on ServerOptions.
+var inlineOpenChar byte = '>'
+var inlineCloseChar byte = '&g