Basically you should work with Underlying TextBuffer
from your TextView
.
Selection
To Cut, Copy and Paste, First we should select the part we intended to Copy (or check and see if the buffer already has some selection or not), to select a part we should get an Iterator of type TextIter
from buffer, here is how we can do it:
Here is an example for SelectAll:
var start = textview.Buffer.GetIterAtOffset (0);
var end = textview.Buffer.GetIterAtOffset (0);
end.ForwardToEnd ();
textview.Buffer.SelectRange (start, end);
Here is an example is for selecting range [2,4] from text:
var start = textview.Buffer.GetIterAtOffset (0);
start.ForwardChars (2);
var end = textview.Buffer.GetIterAtOffset (0);
end.ForwardChars (4);
textview.Buffer.SelectRange (start, end);
TextIter
have extensive methods for range selection for example ForwardChars()
has a twin method BackwardChars()
.
To check if our TextBuffer
has any selection we should use HasSelection
Property:
var hasSelection = textview.Buffer.HasSelection;
Working with Clipboard
Now that we have a selected text we can simply use it with Clipboard actions.
Here is a sample for Cutting selected range [2,4]:
var clipboard = textview.GetClipboard (Gdk.Selection.Clipboard);
var start = textview.Buffer.GetIterAtOffset (0);
start.ForwardChars (2);
var end = textview.Buffer.GetIterAtOffset (0);
end.ForwardChars (4);
textview.Buffer.SelectRange (start, end);
textview.Buffer.CutClipboard (clipboard, true);
Copying is very similar to Cutting we should only replace CutClipboard
with CopyClipboard
:
Here is a sample for Copying selected range [2,4]:
var clipboard = textview.GetClipboard (Gdk.Selection.Clipboard);
var start = textview.Buffer.GetIterAtOffset (0);
start.ForwardChars (2);
var end = textview.Buffer.GetIterAtOffset (0);
end.ForwardChars (4);
textview.Buffer.SelectRange (start, end);
textview.Buffer.CopyClipboard (clipboard, true);
and finally Pasting something from clipboard is very similar to Cutting/Copying
Here is an example of Pasting some text from Clipboard to location 0:
var pasteLocation=textview.Buffer.GetIterAtOffset (0);
textview.Buffer.SelectRange (pasteLocation, pasteLocation);
textview.Buffer.PasteClipboard (clipboard);
Final Example:
As a final example, we set text to 123456 and then cut 34 from it and paste it at the beginning, the final text should be like 341256 :
void TextViewSample ()
{
textview.Buffer.Text = "123456";
var clipboard = textview.GetClipboard (Gdk.Selection.Clipboard);
var start = textview.Buffer.GetIterAtOffset (0);
start.ForwardChars (2);
var end = textview.Buffer.GetIterAtOffset (0);
end.ForwardChars (4);
textview.Buffer.SelectRange (start, end);
var hasSelection = textview.Buffer.HasSelection;
textview.Buffer.CutClipboard (clipboard, true);
var pasteLocation = textview.Buffer.GetIterAtOffset (0);
textview.Buffer.SelectRange (pasteLocation, pasteLocation);
textview.Buffer.PasteClipboard (clipboard);
}