diff --git a/src/XTerm.NET.Tests/SelectionTests.cs b/src/XTerm.NET.Tests/SelectionTests.cs index 933ec49..28b0254 100644 --- a/src/XTerm.NET.Tests/SelectionTests.cs +++ b/src/XTerm.NET.Tests/SelectionTests.cs @@ -69,6 +69,43 @@ public void SelectAll_IncludesScrollback_NotJustViewport() } [Fact] + public void SelectionText_ClampsNegativeColumns() + { + var terminal = new Terminal(new TerminalOptions { Rows = 3, Cols = 10, Scrollback = 20 }); + terminal.Write("alpha"); + + terminal.Selection.StartSelection(-3, 0); + terminal.Selection.UpdateSelection(4, 0); + terminal.Selection.EndSelection(); + + Assert.Equal("alpha", terminal.Selection.GetSelectionText()); + } + + [Fact] + public void SelectionText_ClampsColumnsPastRightEdge() + { + var terminal = new Terminal(new TerminalOptions { Rows = 3, Cols = 10, Scrollback = 20 }); + terminal.Write("alpha"); + + terminal.Selection.StartSelection(0, 0); + terminal.Selection.UpdateSelection(30, 0); + terminal.Selection.EndSelection(); + + Assert.StartsWith("alpha", terminal.Selection.GetSelectionText()); + } + + [Fact] + public void SelectionText_ReturnsEmpty_WhenTerminalHasNoColumns() + { + var terminal = new Terminal(new TerminalOptions { Rows = 3, Cols = 0, Scrollback = 20 }); + + terminal.Selection.StartSelection(0, 0); + terminal.Selection.UpdateSelection(0, 0); + terminal.Selection.EndSelection(); + + Assert.Equal(string.Empty, terminal.Selection.GetSelectionText()); + } + public void SelectionText_UsesLineFeedLineEndings() { var terminal = new Terminal(new TerminalOptions { Rows = 3, Cols = 80, Scrollback = 20 }); diff --git a/src/XTerm.NET/Selection/SelectionManager.cs b/src/XTerm.NET/Selection/SelectionManager.cs index b27e860..bec8d40 100644 --- a/src/XTerm.NET/Selection/SelectionManager.cs +++ b/src/XTerm.NET/Selection/SelectionManager.cs @@ -145,8 +145,15 @@ public string GetSelectionText() if (line == null) continue; - int startX = (y == start.y) ? start.x : 0; - int endX = (y == end.y) ? end.x : _terminal.Cols - 1; + int lastColumn = _terminal.Cols - 1; + if (lastColumn < 0) + continue; + + int startX = Math.Clamp((y == start.y) ? start.x : 0, 0, lastColumn); + int endX = Math.Clamp((y == end.y) ? end.x : lastColumn, 0, lastColumn); + + if (startX > endX) + continue; var lineText = line.TranslateToString(false, startX, endX + 1); text.Append(lineText);