TextApi

Scenarios & Cookbook

Real-world examples and patterns for common editing tasks.

Navigation: Overview Quick Start Operations Cursors

Bulk Find and Replace

Replace all occurrences of a pattern across the document:

var result = new DocumentPipeline(doc)
	.Add(new ReplaceAllOperation { Find = "TODO", Replace = "DONE" })
	.Execute();

Console.WriteLine($"Replaced {result.AuditLog.Entries[0].MatchCount} occurrences");

Multi-Cursor Editing

Edit multiple lines at once:

var mc = new MultiCursor(doc);

// Add cursors to lines 5-10 at column 0
mc.AddColumnSelection(5, 10, 0);

// Insert a comment marker at each cursor
mc.InsertText("// ");

// Single undo removes all markers
doc.Undo();

Indent/Dedent Selection

Indent or dedent a block of lines:

var result = new DocumentPipeline(doc)
	.Add(new IndentOperation 
	{ 
		StartLine = 5, 
		EndLine = 10, 
		Prefix = "    ",
		Dedent = false  // true to remove indentation
	})
	.Execute();

Sort and Deduplicate

Clean up file content:

var result = new DocumentPipeline(doc)
	.Add(new TrimTrailingWhitespaceOperation())
	.Add(new DeduplicateLinesOperation())
	.Add(new SortLinesOperation())
	.Execute();

if (result.Success)
	Console.WriteLine("Cleanup complete");

Code Formatting Pipeline

Format a file with multiple operations:

var ops = OperationMapper.FromPipelineJson("""
{
  "operations": [
	{ "type": "TRIM_TRAILING_WHITESPACE" },
	{ "type": "NORMALISE_WHITESPACE" },
	{ "type": "SORT_LINES" },
	{ "type": "DEDUPLICATE_LINES" }
  ]
}
""");

var result = new DocumentPipeline(doc)
	.Add(ops)
	.Execute();

Search and Navigate

Find all matches and navigate through them:

var matches = doc.FindAll("pattern").ToList();

foreach (var match in matches)
{
	var (line, col) = doc.OffsetToPosition(match.Offset);
	Console.WriteLine($"Found at line {line}, col {col}");
}

Diff Two Files

Compare two versions and generate a patch:

var oldDoc = new TextDocument();
oldDoc.Load(File.ReadAllText("old.txt"));

var newDoc = new TextDocument();
newDoc.Load(File.ReadAllText("new.txt"));

var diff = TextDiff.Diff(oldDoc, newDoc);
var patch = diff.ToUnifiedDiff("old.txt", "new.txt", contextLines: 3);

Console.WriteLine(patch);

Batch Process Multiple Files

Transform many files with the same operations:

var operations = OperationMapper.FromPipelineJson(operationsJson);

foreach (var file in Directory.EnumerateFiles("src", "*.cs"))
{
	var doc = new TextDocument();
	await doc.LoadFileAsync(file);

	var result = new DocumentPipeline(doc).Add(operations).Execute();

	if (result.Success)
		await doc.SaveFileAsync();
}

AI-Driven Edits from JSON

Execute operations generated by an LLM:

string llmOutput = await CallLLM("Generate refactoring operations");

var ops = OperationMapper.FromPipelineJson(llmOutput);
var result = new DocumentPipeline(doc).Add(ops).Execute();

if (!result.Success)
	Console.WriteLine($"Failed at operation {result.FailedOperationIndex}");