How to navigate in DocumentViewwhen developing an extension for VS 2022?

Viewed 27

I have to develop a rather simple extension for VS 2022. To do so, I need to insert some text into a certain position of the document worked with (for simplicity, right into the beginning). I followed a few video tutorials by Mads Kristensen on YouTube and GitHub, e.g. his InsertGuid example (https://github.com/MadsKristensen/InsertGuid), which I found enlightening, but I failed to find guidance to how to navigate within the document's text, more specifically, how to insert text right into its beginning or end. My question is how one can do it or where can I find some detailed tutorial or documentation.

1 Answers

After trying to find out myself (unsuccessfully) I asked on GitHub and got the following solution (https://github.com/VsixCommunity/Community.VisualStudio.Toolkit/discussions/355):

DocumentView docView = await VS.Documents.GetActiveDocumentViewAsync();

docView.TextBuffer.Insert(0, "I'm at the start.");

// Insert at the end of the document.
int end = docView.TextBuffer.CurrentSnapshot.Length;
docView.TextBuffer.Insert(end, "I'm at the end.");

// Inserting at the start of the second line.
ITextSnapshotLine secondLine = docView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(1);
docView.TextBuffer.Insert(secondLine.Start, "Now I am the second line\n.");

Tested, and it works.

Related