# Improve readability of code search terminal output

`f941166`→[main](/content/gh/entireio/cli/commits/main/index.html)·  
  
evisdren·4d ago·2 files·+140 added/-15 removed

Code search results were plain undifferentiated text, making matches  
hard to scan (ENT-1130). Group results by file with a colored header,  
dim line numbers, highlight query matches, and dim the stats footer,  
matching the styling of other commands. Piped and --json output stay  
plain.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

## Changes

2

- cmd/entire/cli

- Msearch_cmd.go+78/-11

- Msearch_cmd_test.go+62/-4

```
488 unmodified lines

489
490
491
492
492
493
494
495
307 unmodified lines

803
804
805
806
807
806
807
808
809
810
811
812
813
3 unmodified lines

817
818
819
820
821
822
823
824
825
826
827
828
829
818
819
820
821
830
831
832
833
834
835
836
823
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
827
859
860
861
830
862
863
864
865
866
834
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908

488 unmodified lines

return writeCodeSearchJSON(w, resp)
}

writeCodeSearchText(w, resp)
writeCodeSearchText(w, resp, newStatusStyles(w))
return nil
}

307 unmodified lines

// with an ellipsis so that JSONL/minified files don't blow up the terminal.
const maxContextLineLen = 200

// writeCodeSearchText renders code search results in grep-style format.
func writeCodeSearchText(w io.Writer, resp *codesearch.SearchResponse) {
// writeCodeSearchText renders code search results grouped by file (ripgrep
// style): a colored "repo:path" header per file, indented line-numbered
// matches beneath it, and a dimmed stats footer. Colors are applied only when
// the writer supports them (styles.colorEnabled); piped output stays plain.
func writeCodeSearchText(w io.Writer, resp *codesearch.SearchResponse, styles statusStyles) {
if len(resp.Results) == 0 {
if len(resp.FailedJurisdictions) > 0 {
fmt.Fprintf(w, "No code search results found (some regions failed: %s)
",
3 unmodified lines

}
return
}

// Group results by repo:path, preserving first-appearance order so the
// best-scored file stays on top (results arrive globally score-sorted).
type fileGroup struct {
key     string
results []codesearch.Result
}
var groups []fileGroup
idx := make(map[string]int, len(resp.Results))
for _, r := range resp.Results {
line := r.ContextLine
runes := []rune(line)
if len(runes) > maxContextLineLen {
line = string(runes[:maxContextLineLen]) + "…"
}
key := r.Repo + ":" + r.Path
	i, ok := idx[key]
if !ok {
	i = len(groups)
	idx[key] = i
	groups = append(groups, fileGroup{key: key})
}
fmt.Fprintf(w, "%s:%s:%d: %s\n", r.Repo, r.Path, r.Line, line)
groups[i].results = append(groups[i].results, r)
}

for gi, g := range groups {
if gi > 0 {
fmt.Fprintln(w)
}
fmt.Fprintln(w, styles.render(styles.cyan, g.key))
for _, r := range g.results {
line := r.ContextLine
runes := []rune(line)
if len(runes) > maxContextLineLen {
line = string(runes[:maxContextLineLen]) + "…"
}
lineNo := styles.render(styles.dim, fmt.Sprintf("%d:", r.Line))
fmt.Fprintf(w, "  %s %s\n", lineNo, highlightCodeMatches(line, resp.Query, styles))
}
}

shown := len(resp.Results)
var summary string
if resp.Stats.TotalMatches > shown {
fmt.Fprintf(w, "\nShowing %d of %d matches across %d files in %d repos (%.0fms)\n",
summary = fmt.Sprintf("Showing %d of %d matches across %d files in %d repos (%.0fms)",
shown, resp.Stats.TotalMatches, resp.Stats.TotalFiles, resp.Stats.ReposSearched, resp.Stats.DurationMs)
} else {
fmt.Fprintf(w, "\n%d matches across %d files in %d repos (%.0fms)\n",
summary = fmt.Sprintf("%d matches across %d files in %d repos (%.0fms)",
resp.Stats.TotalMatches, resp.Stats.TotalFiles, resp.Stats.ReposSearched, resp.Stats.DurationMs)
}
fmt.Fprintf(w, "\n%s\n", styles.render(styles.dim, summary))
if len(resp.FailedJurisdictions) > 0 {
fmt.Fprintf(w, "Warning: results may be incomplete (failed jurisdictions: %s)\n",
warning := fmt.Sprintf("Warning: results may be incomplete (failed jurisdictions: %s)",
strings.Join(resp.FailedJurisdictions, ", "))
fmt.Fprintln(w, styles.render(styles.yellow, warning))
}
}

// highlightCodeMatches bold-red highlights occurrences of query in line
// (grep convention). Matching is case-insensitive when lowercasing doesn't
// change byte lengths (it can for some Unicode); otherwise it falls back to
// exact matching so byte offsets stay aligned. Returns line unchanged when
// color is disabled or there's nothing to highlight.
func highlightCodeMatches(line, query string, styles statusStyles) string {
if !styles.colorEnabled || query == "" {
return line
}
haystack, needle := line, query
if l, q := strings.ToLower(line), strings.ToLower(query); len(l) == len(line) && len(q) == len(query) {
	haystack, needle = l, q
}
matchStyle := styles.red.Bold(true)
var b strings.Builder
i := 0
for {
j := strings.Index(haystack[i:], needle)
if j < 0 {
break
}
j += i
b.WriteString(line[i:j])
b.WriteString(matchStyle.Render(line[j : j+len(needle)]))
i = j + len(needle)
}
if i == 0 {
return line // no matches; skip the builder copy
}
b.WriteString(line[i:])
return b.String()
}

// writeSearchJSON writes client-side paginated search results as JSON.
func writeSearchJSON(w io.Writer, resp *search.Response, limit, page int) error {
if limit <= 0 {
```

Mcmd/entire/cli/search_cmd.go+78/-11

```
166 unmodified lines

167
168
169
170
170
171
172
173
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
36 unmodified lines

276
277
278
221
279
280
281
282
17 unmodified lines

300
301
302
245
303
304
305
306

166 unmodified lines

}

var buf bytes.Buffer
writeCodeSearchText(&buf, resp)
writeCodeSearchText(&buf, resp, newStatusStyles(&buf))

output := buf.String()
if !strings.Contains(output, "entireio/cli:main.go:10: func main() {") {
if !strings.Contains(output, "entireio/cli:main.go\n") {
	t.Errorf("output missing file header:\n%s", output)
}
if !strings.Contains(output, "  10: func main() {") {
	t.Errorf("output missing first result:\n%s", output)
}
if !strings.Contains(output, "  42: \tfmt.Println(\"hello\")") {
	t.Errorf("output missing second result:\n%s", output)
}
if !strings.Contains(output, "2 matches across 1 files") {
	t.Errorf("output missing summary line:\n%s", output)
}
if strings.Contains(output, "\x1b[") {
	t.Errorf("expected no ANSI codes for non-terminal writer:\n%s", output)
}
}

func TestWriteCodeSearchText_GroupsByFile(t *testing.T) {
t.Parallel()

// Interleaved files (score-sorted input) should collapse into one header
	// per file, in first-appearance order.
	resp := &codesearch.SearchResponse{
		Stats: codesearch.Stats{TotalMatches: 3, TotalFiles: 2, ReposSearched: 1, DurationMs: 1},
		Results: []codesearch.Result{
			{Repo: "r", Path: "a.go", Line: 1, ContextLine: "one"},
			{Repo: "r", Path: "b.go", Line: 2, ContextLine: "two"},
			{Repo: "r", Path: "a.go", Line: 3, ContextLine: "three"},
		},
	}

var buf bytes.Buffer
	writeCodeSearchText(&buf, resp, newStatusStyles(&buf))

output := buf.String()
	if got := strings.Count(output, "r:a.go\n"); got != 1 {
		t.Errorf("expected exactly 1 header for a.go, got %d:\n%s", got, output)
	}
	if aIdx, bIdx := strings.Index(output, "r:a.go"), strings.Index(output, "r:b.go"); aIdx > bIdx {
		t.Errorf("expected a.go header before b.go:\n%s", output)
	}
}

func TestHighlightCodeMatches(t *testing.T) {
t.Parallel()

styles := statusStyles{colorEnabled: true}

out := highlightCodeMatches("func HandleRequest(w)", "handlerequest", styles)
	if !strings.Contains(out, "\x1b[") {
		t.Errorf("expected ANSI codes in highlighted output, got %q", out)
	}
	if !strings.HasPrefix(out, "func ") || !strings.HasSuffix(out, "(w)") {
		t.Errorf("expected unmatched text preserved around highlight, got %q", out)
	}
	if out := highlightCodeMatches("no match here", "zzz", styles); out != "no match here" {
		t.Errorf("expected unchanged line when no match, got %q", out)
	}
	plain := statusStyles{colorEnabled: false}
	if out := highlightCodeMatches("func main()", "main", plain); out != "func main()" {
		t.Errorf("expected unchanged line when color disabled, got %q", out)
	}
}

func TestWriteCodeSearchJSON(t *testing.T) {
36 unmodified lines

}

var buf bytes.Buffer
writeCodeSearchText(&buf, resp)
writeCodeSearchText(&buf, resp, newStatusStyles(&buf))

output := buf.String()
if strings.Contains(output, longLine) {
17 unmodified lines

}

var buf bytes.Buffer
writeCodeSearchText(&buf, resp)
writeCodeSearchText(&buf, resp, newStatusStyles(&buf))

if !strings.Contains(buf.String(), "No code search results found") { 
	t.Errorf("expected empty results message, got:\n%s", buf.String())
}
```
