/// <summary> /// Reformat all comments between the specified start and end point. Comments that start /// within the range, even if they overlap the end are included. /// </summary> /// <param name="textDocument">The text document.</param> /// <param name="start">The start point.</param> /// <param name="end">The end point.</param> public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end) { var options = new CodeCommentOptions(Settings.Default, _package, textDocument); bool foundComments = false; while (start.Line <= end.Line) { if (CodeCommentHelper.IsCommentLine(start)) { var comment = new CodeComment(start); if (comment.IsValid) { comment.Format(options); foundComments = true; } if (comment.EndPoint != null) { start = comment.EndPoint.CreateEditPoint(); } } if (start.Line == textDocument.EndPoint.Line) { break; } start.LineDown(); start.StartOfLine(); } return foundComments; }
void Example6() { //Create a new text document TextDocument document = new TextDocument(); document.New(); //Create a table for a text document using the TableBuilder Table table = TableBuilder.CreateTextDocumentTable( document, "table1", "table1", 3, 3, 16.99, false, false); //Fill the cells foreach (Row row in table.RowCollection) { foreach (Cell cell in row.CellCollection) { //Create a standard paragraph Paragraph paragraph = ParagraphBuilder.CreateStandardTextParagraph(document); //Add some simple text paragraph.TextContent.Add(new SimpleText(document, "Cell text")); cell.Content.Add(paragraph); } } //Merge some cells. Notice this is only available in text documents! table.RowCollection[1].MergeCells(document, 1, 2, true); //Add table to the document document.Content.Add(table); //Save the document document.SaveTo("example6_simpleTableWithMergedCells.odt"); }
public void Howto_special_charInch() { TextDocument document = new TextDocument(); document.Load(@"F:\odtFiles\Howto_special_char.odt"); document.SaveTo(@"F:\odtFiles\Howto_special_char.html"); document.Dispose(); }
void Example3() { string imagePath = @"Assets\ODFSample\Examples\example3.png"; TextDocument document = new TextDocument(); document.New(); //Create standard paragraph Paragraph paragraphOuter = ParagraphBuilder.CreateStandardTextParagraph(document); //Create the frame with graphic Frame frame = new Frame(document, "frame1", "graphic1", imagePath); //Create a Draw Area Rectangle DrawAreaRectangle drawAreaRec = new DrawAreaRectangle( document, "0cm", "0cm", "1.5cm", "2.5cm", null); drawAreaRec.Href = "http://OpenDocument4all.com"; //Create a Draw Area Circle DrawAreaCircle drawAreaCircle = new DrawAreaCircle( document, "4cm", "4cm", "1.5cm", null); drawAreaCircle.Href = "http://AODL.OpenDocument4all.com"; DrawArea[] drawArea = new DrawArea[2] { drawAreaRec, drawAreaCircle }; //Create a Image Map ImageMap imageMap = new ImageMap(document, drawArea); //Add Image Map to the frame frame.Content.Add(imageMap); //Add frame to paragraph paragraphOuter.Content.Add(frame); //Add paragraph to document document.Content.Add(paragraphOuter); //Save the document document.SaveTo(@"example3_simpleImageMap.odt"); }
public void ParagraphAddRemoveTest() { TextDocument td = new TextDocument(); td.New(); Paragraph p = new Paragraph(td, "P1"); Assert.IsNotNull(p.Style, "Style object must exist!"); Assert.AreEqual(p.Style.GetType().Name, "ParagraphStyle", "IStyle object must be type of ParagraphStyle"); Assert.IsNotNull(((ParagraphStyle)p.Style).Properties, "Properties object must exist!"); //add text p.TextContent.Add(new SimpleText(p, "Hello")); IText itext = p.TextContent[0]; p.TextContent.Remove(itext); //Console.Write(p.Node.Value); Assert.IsTrue(p.Node.InnerXml.IndexOf("Hello") == -1, "Must be removed!"); //Add the Paragraph td.Content.Add((IContent)p); //Blank para td.Content.Add(new Paragraph(td, ParentStyles.Standard.ToString())); // new para p = new Paragraph(td, "P2"); p.TextContent.Add(new SimpleText(p, "Hello i'm still here")); td.Content.Add(p); td.SaveTo("pararemoved.odt"); //Console.WriteLine("Document: {0}", td.XmlDoc.OuterXml); }
public void Howto_special_char() { TextDocument document = new TextDocument(); document.Load("Howto_special_char.odt"); document.SaveTo("Howto_special_char.html"); document.Dispose(); }
public void NewTextDocument() { TextDocument td = new TextDocument(); td.New(); Assert.IsNotNull(td.XmlDoc, "Must exist!"); //Console.WriteLine("Doc: {0}", td.XmlDoc.OuterXml); }
void Example10() { //some text e.g read from a TextBox string someText = "Max Mustermann\nMustermann Str. 300\n22222 Hamburg\n\n\n\n" + "Heinz Willi\nDorfstr. 1\n22225 Hamburg\n\n\n\n" + "Offer for 200 Intel Pentium 4 CPU's\n\n\n\n" + "Dear Mr. Willi,\n\n\n\n" + "thank you for your request. \tWe can " + "offer you the 200 Intel Pentium IV 3 Ghz CPU's for a price of " + "79,80 € per unit." + "This special offer is valid to 31.10.2005. If you accept, we " + "can deliver within 24 hours.\n\n\n\n" + "Best regards \nMax Mustermann"; //Create new TextDocument TextDocument document = new TextDocument(); document.New(); //Use the ParagraphBuilder to split the string into ParagraphCollection ParagraphCollection pCollection = ParagraphBuilder.CreateParagraphCollection( document, someText, true, ParagraphBuilder.ParagraphSeperator); //Add the paragraph collection foreach (Paragraph paragraph in pCollection) document.Content.Add(paragraph); //save document.SaveTo("example10_Letter.odt"); }
void Example4() { string imagePath = @"Assets\ODFSample\Examples\example3.png"; TextDocument textdocument = new TextDocument(); textdocument.New(); Paragraph pOuter = ParagraphBuilder.CreateStandardTextParagraph(textdocument); DrawTextBox drawTextBox = new DrawTextBox(textdocument); Frame frameTextBox = new Frame(textdocument, "fr_txt_box"); frameTextBox.DrawName = "fr_txt_box"; frameTextBox.ZIndex = "0"; Paragraph p = ParagraphBuilder.CreateStandardTextParagraph(textdocument); p.StyleName = "Illustration"; Frame frame = new Frame(textdocument, "frame1", "graphic1", imagePath); frame.ZIndex = "1"; p.Content.Add(frame); p.TextContent.Add(new SimpleText(textdocument, "Illustration")); drawTextBox.Content.Add(p); frameTextBox.SvgWidth = frame.SvgWidth; drawTextBox.MinWidth = frame.SvgWidth; drawTextBox.MinHeight = frame.SvgHeight; frameTextBox.Content.Add(drawTextBox); pOuter.Content.Add(frameTextBox); textdocument.Content.Add(pOuter); textdocument.SaveTo("example4_drawTextbox.odt"); }
private async void UploadDocumentTextToHastebin(TextDocument document) { var textToUpload = textSelector.GetDocumentSelection(document); var textWithExcessTabsRemoved = ExcessTabRemover.RemoveExcessTabs(textToUpload, document.TabSize); var urlExtension = new LanguageUrlExtensionProvider(document).Extension; using (var request = new HasteRequest(url)) { try { var response = await request.PostAsync(textWithExcessTabsRemoved); var fullUrl = response.GetUrl(url, urlExtension); ClipboardCommunicator.AddToClipboard(fullUrl); SetStatusBarText($"Code URL copied to clipboard: {fullUrl}"); } catch (HttpRequestException) { SetStatusBarText("An error occurred trying to post to hastebin"); } } }
public void RawlyIndentLine(int tabsToInsert, TextDocument document, DocumentLine line) { if (!_doBeginUpdateManually) document.BeginUpdate(); /* * 1) Remove old indentation * 2) Insert new one */ // 1) int prevInd = 0; int curOff = line.Offset; if (curOff < document.TextLength) { char curChar = '\0'; while (curOff < document.TextLength && ((curChar = document.GetCharAt(curOff)) == ' ' || curChar == '\t')) { prevInd++; curOff++; } document.Remove(line.Offset, prevInd); } // 2) string indentString = ""; for (int i = 0; i < tabsToInsert; i++) indentString += dEditor.Editor.Options.IndentationString; document.Insert(line.Offset, indentString); if (!_doBeginUpdateManually) document.EndUpdate(); }
private static void ExtractRemainingSelection(TextDocument ActiveDoc, SourceRange SelectRange) { // Extract Remaining Selection CodeRush.Selection.SelectRange(SelectRange); ExecuteRefactoring("Extract Method"); ActiveDoc.ParseIfTextChanged(); }
static void AppendRtfText (StringBuilder rtfText, TextDocument doc, int start, int end, ref bool appendSpace) { for (int i = start; i < end; i++) { char ch = doc.GetCharAt (i); switch (ch) { case '\\': rtfText.Append (@"\\"); break; case '{': rtfText.Append (@"\{"); break; case '}': rtfText.Append (@"\}"); break; case '\t': rtfText.Append (@"\tab"); appendSpace = true; break; default: if (appendSpace) { rtfText.Append (' '); appendSpace = false; } rtfText.Append (ch); break; } } }
public void CellParagraphTest() { TextDocument doc = new TextDocument(); doc.New(); Table table = new Table(doc, "table1"); table.Init(5, 3, 16.99); foreach(Row r in table.Rows) foreach(Cell c in r.Cells) c.InsertText("Hello"); Paragraph p = new Paragraph(doc, "P1"); FormatedText ft = new FormatedText(p, "T1", "Hello World"); ((TextStyle)ft.Style).Properties.Italic = "italic"; p.TextContent.Add(ft); table.Rows[0].Cells[0].Content.Add(p); doc.Content.Add(table); doc.SaveTo("tablewithstyles.odt"); }
static void AppendHtmlText (StringBuilder htmlText, TextDocument doc, ITextEditorOptions options, int start, int end) { for (int i = start; i < end; i++) { char ch = doc.GetCharAt (i); switch (ch) { case ' ': htmlText.Append (" "); break; case '\t': for (int i2 = 0; i2 < options.TabSize; i2++) htmlText.Append (" "); break; case '<': htmlText.Append ("<"); break; case '>': htmlText.Append (">"); break; case '&': htmlText.Append ("&"); break; case '"': htmlText.Append ("""); break; default: htmlText.Append (ch); break; } } }
void Example7() { //Create a new text document TextDocument document = new TextDocument(); document.New(); //Create a table for a text document using the TableBuilder Table table = TableBuilder.CreateTextDocumentTable( document, "table1", "table1", 3, 3, 16.99, false, false); //Create a standard paragraph Paragraph paragraph = ParagraphBuilder.CreateStandardTextParagraph(document); //Add some simple text paragraph.TextContent.Add(new SimpleText(document, "Some cell text")); //Insert paragraph into the first cell table.RowCollection[0].CellCollection[0].Content.Add(paragraph); //Add table to the document document.Content.Add(table); //Save the document document.SaveTo("example7_simpleTable.odt"); }
public void CellSpanTest() { TextDocument doc = new TextDocument(); doc.New(); Table table = new Table(doc, "table1"); table.Init(5, 2, 16.99); //Create a new row within this table and //set the cellspan to 2 Row row = new Row(table, ""); //Create a real cell Cell cell = new Cell(row, "table1.ZZ1"); //Set cell span cell.ColumnRepeating = "2"; //Set the border ((CellStyle)cell.Style).CellProperties.Border = Border.NormalSolid; //add some content to this cell cell.Content.Add(new Paragraph(doc, ParentStyles.Standard, "Hello I'm merged over two cells!")); //add cell to the row row.Cells.Add(cell); //we have to add one CellSpan object, because the //table has original 2 columns row.CellSpans.Add(new CellSpan(row)); //at least at this row the table table.Rows.Add(row); //add the table to the document doc.Content.Add(table); //save it to the disk doc.SaveTo("tablecellspan.odt"); }
/// <summary> /// Reformat all comments between the specified start and end point. Comments that start /// within the range, even if they overlap the end are included. /// </summary> /// <param name="textDocument">The text document.</param> /// <param name="start">The start point.</param> /// <param name="end">The end point.</param> public bool FormatComments(TextDocument textDocument, EditPoint start, EditPoint end) { bool foundComments = false; int tabSize = CodeCommentHelper.GetTabSize(_package, textDocument); while (start.Line <= end.Line) { if (CodeCommentHelper.IsCommentLine(start)) { var comment = new CodeComment(start, tabSize); if (comment.IsValid) { comment.Format(); foundComments = true; } if (comment.EndPoint != null) { start = comment.EndPoint.CreateEditPoint(); } } if (start.Line == textDocument.EndPoint.Line) { break; } start.LineDown(); start.StartOfLine(); } return foundComments; }
public static string GenerateHtml (TextDocument doc, Mono.TextEditor.Highlighting.ISyntaxMode mode, Mono.TextEditor.Highlighting.ColorScheme style, ITextEditorOptions options) { var htmlText = new StringBuilder (); htmlText.AppendLine (@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">"); htmlText.AppendLine ("<HTML>"); htmlText.AppendLine ("<HEAD>"); htmlText.AppendLine ("<META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=utf-8\">"); htmlText.AppendLine ("<META NAME=\"GENERATOR\" CONTENT=\"Mono Text Editor\">"); htmlText.AppendLine ("</HEAD>"); htmlText.AppendLine ("<BODY>"); var selection = new TextSegment (0, doc.TextLength); int startLineNumber = doc.OffsetToLineNumber (selection.Offset); int endLineNumber = doc.OffsetToLineNumber (selection.EndOffset); htmlText.AppendLine ("<FONT face = '" + options.Font.Family + "'>"); bool first = true; if (mode is SyntaxMode) { SyntaxModeService.StartUpdate (doc, (SyntaxMode)mode, selection.Offset, selection.EndOffset); SyntaxModeService.WaitUpdate (doc); } foreach (var line in doc.GetLinesBetween (startLineNumber, endLineNumber)) { if (!first) { htmlText.AppendLine ("<BR>"); } else { first = false; } if (mode == null) { AppendHtmlText (htmlText, doc, options, System.Math.Max (selection.Offset, line.Offset), System.Math.Min (line.EndOffset, selection.EndOffset)); continue; } int curSpaces = 0; foreach (var chunk in mode.GetChunks (style, line, line.Offset, line.Length)) { int start = System.Math.Max (selection.Offset, chunk.Offset); int end = System.Math.Min (chunk.EndOffset, selection.EndOffset); var chunkStyle = style.GetChunkStyle (chunk); if (start < end) { htmlText.Append ("<SPAN style='"); if (chunkStyle.FontWeight != Xwt.Drawing.FontWeight.Normal) htmlText.Append ("font-weight:" + ((int)chunkStyle.FontWeight) + ";"); if (chunkStyle.FontStyle != Xwt.Drawing.FontStyle.Normal) htmlText.Append ("font-style:" + chunkStyle.FontStyle.ToString ().ToLower () + ";"); htmlText.Append ("color:" + ((HslColor)chunkStyle.Foreground).ToPangoString () + ";"); htmlText.Append ("'>"); AppendHtmlText (htmlText, doc, options, start, end); htmlText.Append ("</SPAN>"); } } } htmlText.AppendLine ("</FONT>"); htmlText.AppendLine ("</BODY></HTML>"); if (Platform.IsWindows) return GenerateCFHtml (htmlText.ToString ()); return htmlText.ToString (); }
/// <summary> /// Run the visual studio built-in remove unused using statements command. /// </summary> /// <param name="textDocument">The text document to update.</param> /// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param> public void RemoveUnusedUsingStatements(TextDocument textDocument, bool isAutoSave) { if (!Settings.Default.Cleaning_RunVisualStudioRemoveUnusedUsingStatements) return; if (isAutoSave && Settings.Default.Cleaning_SkipRemoveUnusedUsingStatementsDuringAutoCleanupOnSave) return; // Capture all existing using statements that should be re-inserted if removed. string patternFormat = _package.UsePOSIXRegEx ? @"^:b*{0}:b*\n" : @"^[ \t]*{0}[ \t]*\r?\n"; var points = (from usingStatement in _usingStatementsToReinsertWhenRemoved.Value from editPoint in TextDocumentHelper.FindMatches(textDocument, string.Format(patternFormat, usingStatement)) select new { editPoint, text = editPoint.GetLine() }).Reverse().ToList(); _package.IDE.ExecuteCommand("Edit.RemoveUnusedUsings", String.Empty); // Check each using statement point and re-insert it if removed. foreach (var point in points) { string text = point.editPoint.GetLine(); if (text != point.text) { point.editPoint.StartOfLine(); point.editPoint.Insert(point.text); point.editPoint.Insert(Environment.NewLine); } } }
/// <summary> /// Removes blank lines from the top of the specified text document. /// </summary> /// <param name="textDocument">The text document to cleanup.</param> internal void RemoveBlankLinesAtTop(TextDocument textDocument) { if (!Settings.Default.Cleaning_RemoveBlankLinesAtTop) return; EditPoint cursor = textDocument.StartPoint.CreateEditPoint(); cursor.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical); }
/// <summary> /// Breaks the lines into words in the form of a list of <see cref="TextSegment">TextSegments</see>. A 'word' is defined as an identifier (a series of letters, digits or underscores) /// or a single non-identifier character (including white space characters) /// </summary> /// <returns> /// The list of segments representing the 'words' in the lines /// </returns> /// <param name='document'> /// The document to get the words from /// </param> /// <param name='startLine'> /// The first line in the documents to get the words from /// </param> /// <param name='lineCount'> /// The number of lines to get words from /// </param> public static List<TextSegment> BreakLinesIntoWords (TextDocument document, int startLine, int lineCount, bool includeDelimiter = true) { var result = new List<TextSegment> (); for (int line = startLine; line < startLine + lineCount; line++) { var lineSegment = document.GetLine (line); int offset = lineSegment.Offset; bool wasIdentifierPart = false; int lastWordEnd = 0; for (int i = 0; i < lineSegment.Length; i++) { char ch = document.GetCharAt (offset + i); bool isIdentifierPart = char.IsLetterOrDigit (ch) || ch == '_'; if (!isIdentifierPart) { if (wasIdentifierPart) { result.Add (new TextSegment (offset + lastWordEnd, i - lastWordEnd)); } result.Add (new TextSegment (offset + i, 1)); lastWordEnd = i + 1; } wasIdentifierPart = isIdentifierPart; } if (lastWordEnd != lineSegment.Length) { result.Add (new TextSegment (offset + lastWordEnd, lineSegment.Length - lastWordEnd)); } if (includeDelimiter && lineSegment.DelimiterLength > 0) result.Add (new TextSegment (lineSegment.Offset + lineSegment.Length, lineSegment.DelimiterLength)); } return result; }
/// <summary> /// Run the visual studio built-in remove unused using statements command. /// </summary> /// <param name="textDocument">The text document to update.</param> public void RemoveUnusedUsingStatements(TextDocument textDocument) { if (!Settings.Default.Cleaning_RunVisualStudioRemoveUnusedUsingStatements) return; if (_package.IsAutoSaveContext && Settings.Default.Cleaning_SkipRemoveUnusedUsingStatementsDuringAutoCleanupOnSave) return; // Capture all existing using statements that should be re-inserted if removed. const string patternFormat = @"^[ \t]*{0}[ \t]*\r?\n"; var points = (from usingStatement in _usingStatementsToReinsertWhenRemoved.Value from editPoint in TextDocumentHelper.FindMatches(textDocument, string.Format(patternFormat, usingStatement)) select new { editPoint, text = editPoint.GetLine() }).Reverse().ToList(); // Shift every captured point one character to the right so they will auto-advance // during new insertions at the start of the line. foreach (var point in points) { point.editPoint.CharRight(); } _package.IDE.ExecuteCommand("Edit.RemoveUnusedUsings", string.Empty); // Check each using statement point and re-insert it if removed. foreach (var point in points) { string text = point.editPoint.GetLine(); if (text != point.text) { point.editPoint.StartOfLine(); point.editPoint.Insert(point.text); point.editPoint.Insert(Environment.NewLine); } } }
public LanguageUrlExtensionProvider(TextDocument document) { string extension; if (document.Language != null && Extensions.TryGetValue(document.Language.ToLowerInvariant(), out extension)) { Extension = extension; } }
public void Setup() { TestClass test = new TestClass(); test.LetterTestLongVersion(); this._document = new TextDocument(); this._document.Load(this._testfile); }
/// <summary> /// Initializes a new instance of the <see cref="CodeCommentOptions" /> class. /// </summary> /// <param name="package">The hosting package.</param> /// <param name="document">The text document.</param> public CodeCommentOptions(CodeMaidPackage package, TextDocument document) { SkipWrapOnLastWord = Settings.Default.Formatting_CommentSkipWrapOnLastWord; TabSize = CodeCommentHelper.GetTabSize(package, document); WrapAtColumn = Math.Max(Settings.Default.Formatting_CommentWrapColumn, 20); XmlAlignParamTags = Settings.Default.Formatting_CommentXmlAlignParamTags; XmlSpaceTags = Settings.Default.Formatting_CommentXmlSpaceTags; XmlValueIndent = Settings.Default.Formatting_CommentXmlValueIndent; }
/// <summary> /// Initializes a new instance of the <see cref="SearchableTextSegment"/> class. /// </summary> /// <param name="document">The document.</param> /// <param name="offset">The offset.</param> /// <param name="length">The length.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="document"/> is <see langword="null"/>. /// </exception> public SearchableTextSegment(TextDocument document, int offset, int length) { if (document == null) throw new ArgumentNullException(nameof(document)); _document = document; _offset = offset; _length = length; }
/// <summary> /// Inserts a single blank space before a self-closing angle bracket. /// </summary> /// <param name="textDocument">The text document to cleanup.</param> internal void InsertBlankSpaceBeforeSelfClosingAngleBracket(TextDocument textDocument) { if (!Settings.Default.Cleaning_InsertBlankSpaceBeforeSelfClosingAngleBrackets) return; const string pattern = @"([^ \t])/>"; const string replacement = @"$1 />"; TextDocumentHelper.SubstituteAllStringMatches(textDocument, pattern, replacement); }
/// <summary> /// Removes blank lines after an opening brace. /// </summary> /// <param name="textDocument">The text document to cleanup.</param> internal void RemoveBlankLinesAfterOpeningBrace(TextDocument textDocument) { if (!Settings.Default.Cleaning_RemoveBlankLinesAfterOpeningBrace) return; const string pattern = @"\{([ \t]*(//[^\r\n]*)*)(\r?\n){2,}"; string replacement = @"{$1" + Environment.NewLine; TextDocumentHelper.SubstituteAllStringMatches(textDocument, pattern, replacement); }
/// <summary> /// Removes blank lines after attributes. /// </summary> /// <param name="textDocument">The text document to cleanup.</param> internal void RemoveBlankLinesAfterAttributes(TextDocument textDocument) { if (!Settings.Default.Cleaning_RemoveBlankLinesAfterAttributes) return; const string pattern = @"(^[ \t]*\[[^\]]+\][ \t]*(//[^\r\n]*)*)(\r?\n){2}(?![ \t]*//)"; string replacement = @"$1" + Environment.NewLine; TextDocumentHelper.SubstituteAllStringMatches(textDocument, pattern, replacement); }
public abstract bool TryGetFromDocument(TextDocument document, out ITextBuffer textBuffer);
private void OnDocumentChanging(TextDocument document, EventArgs e) { }
/// <summary> /// Creates a new TextSegmentReadOnlySectionProvider instance for the specified document. /// </summary> public TextSegmentReadOnlySectionProvider(TextDocument textDocument) { segments = new TextSegmentCollection <T>(textDocument); }
public int Format(TextDocument textDocument, uint offset, uint length, int cursor) { return(cursor); }
public async ValueTask <ImmutableArray <ActiveStatementSpan> > GetAdjustedActiveStatementSpansAsync(TextDocument document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(_workspace, cancellationToken).ConfigureAwait(false); if (client == null) { return(await GetLocalService().GetAdjustedActiveStatementSpansAsync(_sessionId, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false)); } var result = await client.TryInvokeAsync <IRemoteEditAndContinueService, ImmutableArray <ActiveStatementSpan> >( document.Project.Solution, (service, solutionInfo, callbackId, cancellationToken) => service.GetAdjustedActiveStatementSpansAsync(solutionInfo, callbackId, _sessionId, document.Id, cancellationToken), callbackTarget : new ActiveStatementSpanProviderCallback(activeStatementSpanProvider), cancellationToken).ConfigureAwait(false); return(result.HasValue ? result.Value : ImmutableArray <ActiveStatementSpan> .Empty); }
/// <summary> /// Initializes a new instance of the <see cref="ResultViewModel" /> class. /// </summary> /// <param name="runtime">The runtime service.</param> /// <param name="queryResults">The query results.</param> /// <param name="messages">The WITSML messages.</param> /// <param name="soapMessages">The SOAP messages.</param> public ResultViewModel(IRuntimeService runtime, TextEditorViewModel queryResults, TextDocument messages, TextDocument soapMessages) { _log.Debug("Creating view model instance"); Runtime = runtime; ObjectData = new DataGridViewModel(runtime); ObjectProperties = new PropertyGridViewModel(runtime, ObjectData); QueryResults = queryResults; Messages = new TextEditorViewModel(runtime, "XML", true) { Document = messages }; SoapMessages = new TextEditorViewModel(runtime, "XML", true) { Document = soapMessages }; }
/// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollPercentage = 0.3; TextView textView = textArea.TextView; TextDocument document = textView.Document; if (scrollViewer != null && document != null) { if (line < 1) { line = 1; } if (line > document.LineCount) { line = document.LineCount; } IScrollInfo scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = scrollViewer.ViewportHeight / 2; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) { break; } vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), VisualYPosition.LineMiddle); double verticalPos = p.Y - scrollViewer.ViewportHeight / 2; if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > MinimumScrollPercentage * scrollViewer.ViewportHeight) { scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos)); } if (column > 0) { if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2); if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > MinimumScrollPercentage * scrollViewer.ViewportWidth) { scrollViewer.ScrollToHorizontalOffset(horizontalPos); } } else { scrollViewer.ScrollToHorizontalOffset(0); } } } }
public IEnumerable <CustomNewFolding> UpdateFoldings(TextDocument document) { return(CreateNewFoldings(document)); }
private async Task AnalyzeDocumentForKindAsync(TextDocument document, AnalysisKind kind, CancellationToken cancellationToken) { try { if (!document.SupportsDiagnostics()) { return; } var isActiveDocument = _documentTrackingService.TryGetActiveDocument() == document.Id; var isOpenDocument = document.IsOpen(); var isGeneratedRazorDocument = document.Services.GetService <DocumentPropertiesService>()?.DiagnosticsLspClientName != null; // Only analyze open/active documents, unless it is a generated Razor document. if (!isActiveDocument && !isOpenDocument && !isGeneratedRazorDocument) { return; } var stateSets = _stateManager.GetOrUpdateStateSets(document.Project); var compilationWithAnalyzers = await GetOrCreateCompilationWithAnalyzersAsync(document.Project, stateSets, cancellationToken).ConfigureAwait(false); var version = await GetDiagnosticVersionAsync(document.Project, cancellationToken).ConfigureAwait(false); var backgroundAnalysisScope = GlobalOptions.GetBackgroundAnalysisScope(document.Project.Language); // We split the diagnostic computation for document into following steps: // 1. Try to get cached diagnostics for each analyzer, while computing the set of analyzers that do not have cached diagnostics. // 2. Execute all the non-cached analyzers with a single invocation into CompilationWithAnalyzers. // 3. Fetch computed diagnostics per-analyzer from the above invocation, and cache and raise diagnostic reported events. // In near future, the diagnostic computation invocation into CompilationWithAnalyzers will be moved to OOP. // This should help simplify and/or remove the IDE layer diagnostic caching in devenv process. // First attempt to fetch diagnostics from the cache, while computing the state sets for analyzers that are not cached. using var _ = ArrayBuilder <StateSet> .GetInstance(out var nonCachedStateSets); foreach (var stateSet in stateSets) { var data = TryGetCachedDocumentAnalysisData(document, stateSet, kind, version, backgroundAnalysisScope, isActiveDocument, isOpenDocument, isGeneratedRazorDocument, cancellationToken); if (data.HasValue) { // We need to persist and raise diagnostics for suppressed analyzer. PersistAndRaiseDiagnosticsIfNeeded(data.Value, stateSet); } else { nonCachedStateSets.Add(stateSet); } } // Then, compute the diagnostics for non-cached state sets, and cache and raise diagnostic reported events for these diagnostics. if (nonCachedStateSets.Count > 0) { var analysisScope = new DocumentAnalysisScope(document, span: null, nonCachedStateSets.SelectAsArray(s => s.Analyzer), kind); var executor = new DocumentAnalysisExecutor(analysisScope, compilationWithAnalyzers, _diagnosticAnalyzerRunner, logPerformanceInfo: true, onAnalysisException: OnAnalysisException); var logTelemetry = document.Project.Solution.Options.GetOption(DiagnosticOptions.LogTelemetryForBackgroundAnalyzerExecution); foreach (var stateSet in nonCachedStateSets) { var computedData = await ComputeDocumentAnalysisDataAsync(executor, stateSet, logTelemetry, cancellationToken).ConfigureAwait(false); PersistAndRaiseDiagnosticsIfNeeded(computedData, stateSet); } } } catch (Exception e) when(FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } void PersistAndRaiseDiagnosticsIfNeeded(DocumentAnalysisData result, StateSet stateSet) { if (result.FromCache == true) { RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, result.Items); return; } // no cancellation after this point. var state = stateSet.GetOrCreateActiveFileState(document.Id); state.Save(kind, result.ToPersistData()); RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, result.OldItems, result.Items); } void OnAnalysisException() { // Do not re-use cached CompilationWithAnalyzers instance in presence of an exception, as the underlying analysis state might be corrupt. ClearCompilationsWithAnalyzersCache(document.Project); } }
/// <summary> /// Create <see cref="NewFolding"/>s for the specified document. /// </summary> public override IEnumerable <NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset) { firstErrorOffset = -1; return(CreateNewFoldings(document)); }
/// <summary> /// Start listening to document change events /// </summary> public virtual void StartDocumentProcessing() { // Start compilation process TextDocument.StartSendingChangeEvents(); }
int SearchBracketForward(TextDocument document, int offset, char openBracket, char closingBracket) { bool inString = false; bool inChar = false; bool verbatim = false; bool lineComment = false; bool blockComment = false; if (offset < 0) { return(-1); } // first try "quick find" - find the matching bracket if there is no string/comment in the way int quickResult = QuickSearchBracketForward(document, offset, openBracket, closingBracket); if (quickResult >= 0) { return(quickResult); } // we need to parse the line from the beginning, so get the line start position int linestart = ScanLineStart(document, offset); // we need to know where offset is - in a string/comment or in normal code? // ignore cases where offset is in a block comment int starttype = GetStartType(document, linestart, offset); if (starttype != 0) { return(-1); // start position is in a comment/string } int brackets = 1; while (offset < document.TextLength) { char ch = document.GetCharAt(offset); switch (ch) { case '\r': case '\n': lineComment = false; inChar = false; if (!verbatim) { inString = false; } break; case '/': if (blockComment) { Debug.Assert(offset > 0); if (document.GetCharAt(offset - 1) == '*') { blockComment = false; } } if (!inString && !inChar && offset + 1 < document.TextLength) { if (!blockComment && document.GetCharAt(offset + 1) == '/') { lineComment = true; } if (!lineComment && document.GetCharAt(offset + 1) == '*') { blockComment = true; } } break; case '"': if (!(inChar || lineComment || blockComment)) { if (inString && verbatim) { if (offset + 1 < document.TextLength && document.GetCharAt(offset + 1) == '"') { ++offset; // skip escaped quote inString = false; // let the string go } else { verbatim = false; } } else if (!inString && offset > 0 && document.GetCharAt(offset - 1) == '@') { verbatim = true; } inString = !inString; } break; case '\'': if (!(inString || lineComment || blockComment)) { inChar = !inChar; } break; case '\\': if ((inString && !verbatim) || inChar) { ++offset; // skip next character } break; default: if (ch == openBracket) { if (!(inString || inChar || lineComment || blockComment)) { ++brackets; } } else if (ch == closingBracket) { if (!(inString || inChar || lineComment || blockComment)) { --brackets; if (brackets == 0) { return(offset); } } } break; } ++offset; } return(-1); }
private void RaiseDocumentDiagnosticsIfNeeded( TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray <DiagnosticData> oldItems, ImmutableArray <DiagnosticData> newItems) { RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, oldItems, newItems, AnalyzerService.RaiseDiagnosticsUpdated, forceUpdate: false); }
public static string GenerateRtf(TextDocument doc, Mono.TextEditor.Highlighting.ISyntaxMode mode, Mono.TextEditor.Highlighting.ColorScheme style, ITextEditorOptions options) { var rtfText = new StringBuilder(); var colorList = new List <Gdk.Color> (); var selection = new TextSegment(0, doc.TextLength); int startLineNumber = doc.OffsetToLineNumber(selection.Offset); int endLineNumber = doc.OffsetToLineNumber(selection.EndOffset); bool isItalic = false; bool isBold = false; int curColor = -1; foreach (var line in doc.GetLinesBetween(startLineNumber, endLineNumber)) { bool appendSpace = false; if (mode == null) { AppendRtfText(rtfText, doc, System.Math.Max(selection.Offset, line.Offset), System.Math.Min(line.EndOffset, selection.EndOffset), ref appendSpace); continue; } foreach (var chunk in mode.GetChunks(style, line, line.Offset, line.Length)) { int start = System.Math.Max(selection.Offset, chunk.Offset); int end = System.Math.Min(chunk.EndOffset, selection.EndOffset); var chunkStyle = style.GetChunkStyle(chunk); if (start < end) { if (isBold != chunkStyle.Bold) { rtfText.Append(chunkStyle.Bold ? @"\b" : @"\b0"); isBold = chunkStyle.Bold; appendSpace = true; } if (isItalic != chunkStyle.Italic) { rtfText.Append(chunkStyle.Italic ? @"\i" : @"\i0"); isItalic = chunkStyle.Italic; appendSpace = true; } if (!colorList.Contains(chunkStyle.Color)) { colorList.Add(chunkStyle.Color); } int color = colorList.IndexOf(chunkStyle.Color); if (curColor != color) { curColor = color; rtfText.Append(@"\cf" + (curColor + 1)); appendSpace = true; } AppendRtfText(rtfText, doc, start, end, ref appendSpace); } } rtfText.Append(@"\par"); rtfText.AppendLine(); } var rtf = new StringBuilder(); rtf.Append(@"{\rtf1\ansi\deff0\adeflang1025"); // font table rtf.Append(@"{\fonttbl"); rtf.Append(@"{\f0\fnil\fprq1\fcharset128 " + options.Font.Family + ";}"); rtf.Append("}"); rtf.Append(CreateColorTable(colorList)); rtf.Append(@"\viewkind4\uc1\pard"); rtf.Append(@"\f0"); try { string fontName = options.Font.ToString(); double fontSize = Double.Parse(fontName.Substring(fontName.LastIndexOf(' ') + 1), System.Globalization.CultureInfo.InvariantCulture) * 2; rtf.Append(@"\fs"); rtf.Append(fontSize); } catch (Exception) {}; rtf.Append(@"\cf1"); rtf.Append(rtfText.ToString()); rtf.Append("}"); return(rtf.ToString()); }
public static Uri?TryGetURI(this TextDocument document, RequestContext?context = null) => ProtocolConversions.TryGetUriFromFilePath(document.FilePath, context);
private static void AddTextDocument(string[] attributes) { TextDocument doc = new TextDocument(); AddDocument(attributes, doc); }
public void UpdateFoldings(FoldingManager manager, TextDocument document) { IEnumerable <NewFolding> foldings = CreateNewFoldings(document, out int firstErrorOffset); manager.UpdateFoldings(foldings, firstErrorOffset); }
public TextMarkerService(TextDocument document) { markers = new TextSegmentCollection <TextMarker>(document); }
static bool IsBlankLine(TextDocument doc, int i) { var line = doc.GetLine(i); return(line.Length == line.GetIndentation(doc).Length); }
private async ValueTask <DifferenceViewerPreview> CreateRemovedDocumentPreviewViewCoreAsync(ITextBuffer oldBuffer, PreviewWorkspace workspace, TextDocument document, double zoomLevel, CancellationToken cancellationToken) { // IProjectionBufferFactoryService is a Visual Studio API which is not documented as free-threaded await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var firstLine = string.Format(EditorFeaturesResources.Removing_0_from_1_with_content_colon, document.Name, document.Project.Name); var span = new SnapshotSpan(oldBuffer.CurrentSnapshot, Span.FromBounds(0, oldBuffer.CurrentSnapshot.Length)) .CreateTrackingSpan(SpanTrackingMode.EdgeExclusive); var originalBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List <object> { firstLine, "\r\n", span }, registryService: _contentTypeRegistryService); var changedBuffer = _projectionBufferFactoryService.CreatePreviewProjectionBuffer( sourceSpans: new List <object> { firstLine, "\r\n" }, registryService: _contentTypeRegistryService); #pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task (containing method uses JTF) return(await CreateNewDifferenceViewerAsync(workspace, null, originalBuffer, changedBuffer, zoomLevel, cancellationToken)); #pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task }
/// <summary> /// Updates the #endregion directives to match the names of the matching #region directive /// and cleans up any unnecessary white space. /// </summary> /// <remarks> /// This code is very similar to the Common region retrieval function, but since it /// manipulates the cursors during processing the logic is different enough to warrant a /// separate copy of the code. /// </remarks> /// <param name="textDocument">The text document to cleanup.</param> internal void UpdateEndRegionDirectives(TextDocument textDocument) { if (!Settings.Default.Cleaning_UpdateEndRegionDirectives) { return; } var regionStack = new Stack <string>(); EditPoint cursor = textDocument.StartPoint.CreateEditPoint(); const string pattern = @"^[ \t]*#"; // Keep pushing cursor forwards (note ref cursor parameter) until finished. while (cursor != null && TextDocumentHelper.TryFindNextMatch(startPoint: cursor, endPoint: ref cursor, pattern)) { // Create a pointer to capture the text for this line. EditPoint eolCursor = cursor.CreateEditPoint(); eolCursor.EndOfLine(); string regionText = cursor.GetText(eolCursor); if (regionText.StartsWith("region ")) // Space required by compiler. { // Cleanup any whitespace in the region name. string regionName = regionText.Substring(7); string regionNameTrimmed = regionName.Trim(); if (regionName != regionNameTrimmed) { cursor.CharRight(7); cursor.Delete(eolCursor); cursor.Insert(regionNameTrimmed); } // Push the parsed region name onto the top of the stack. regionStack.Push(regionNameTrimmed); } else if (regionText.StartsWith("endregion")) // Space may or may not be present. { if (regionStack.Count > 0) { // Do not trim the endRegionName in order to catch whitespace differences. string endRegionName = regionText.Length > 9 ? regionText.Substring(10) : string.Empty; string matchingRegion = regionStack.Pop(); // Update if the strings do not match. if (matchingRegion != endRegionName) { cursor.CharRight(9); cursor.Delete(eolCursor); cursor.Insert(" " + matchingRegion); } } else { // This document is improperly formatted, abort. return; } } // Note: eolCursor may be outdated now if changes have been made. cursor.EndOfLine(); } }
public Task <DifferenceViewerPreview> CreateRemovedAdditionalDocumentPreviewViewAsync(TextDocument document, double zoomLevel, CancellationToken cancellationToken) { return(CreateRemovedTextDocumentPreviewViewAsync( document, zoomLevel, createBufferAsync: CreateNewPlainTextBufferAsync, cancellationToken)); }
public MonoTextEditor(TextDocument doc, ITextEditorOptions options) : this(doc, options, new SimpleEditMode()) { }
public Task AnalyzeNonSourceDocumentAsync(TextDocument textDocument, InvocationReasons reasons, CancellationToken cancellationToken) => AnalyzeDocumentForKindAsync(textDocument, AnalysisKind.Syntax, cancellationToken);
public MonoTextEditor(TextDocument doc) : this(doc, null) { }
public Task NonSourceDocumentResetAsync(TextDocument document, CancellationToken cancellationToken) => TextDocumentResetAsync(document, cancellationToken);
public abstract IEnumerable <NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset, IEnumerable <NewFolding> existingFoldings);
public void RegisterSourceFile(AvaloniaEdit.TextEditor editor, ISourceFile file, TextDocument doc) { CSharpDataAssociation association = null; if (dataAssociations.TryGetValue(file, out association)) { throw new Exception("Source file already registered with language service."); } IndentationStrategy = new CSharpIndentationStrategy(editor.Options); association = new CSharpDataAssociation(doc); association.Solution = file.Project.Solution as OmniSharpSolution; // CanHandle has checked this. dataAssociations.Add(file, association); association.TextInputHandler = (sender, e) => { if (editor.Document == doc) { editor.BeginChange(); OpenBracket(editor, editor.Document, e.Text); CloseBracket(editor, editor.Document, e.Text); switch (e.Text) { case "}": case ";": editor.CaretOffset = Format(editor.Document, 0, (uint)editor.Document.TextLength, editor.CaretOffset); break; case "{": var lineCount = editor.Document.LineCount; var offset = Format(editor.Document, 0, (uint)editor.Document.TextLength, editor.CaretOffset); // suggests clang format didnt do anything, so we can assume not moving to new line. if (lineCount != editor.Document.LineCount) { if (offset <= editor.Document.TextLength) { var newLine = editor.Document.GetLineByOffset(offset); editor.CaretOffset = newLine.PreviousLine.EndOffset; } } else { editor.CaretOffset = offset; } break; } editor.EndChange(); } }; editor.TextArea.TextEntered += association.TextInputHandler; }
public void UpdateFoldings(TextDocument document) { _foldingManager.UpdateFoldings(_strategy.UpdateFoldings(document), -1); }
private void RaiseDocumentDiagnosticsIfNeeded(TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray <DiagnosticData> items) => RaiseDocumentDiagnosticsIfNeeded(document, stateSet, kind, ImmutableArray <DiagnosticData> .Empty, items);