private void btnCopy_Click(object sender, RoutedEventArgs e) { if (_edtXPath.SelectionLength > 0) { string text = _edtXPath.SelectedText; Clipboard.SetText(text); } else { DataObject dobj = new DataObject(); dobj.SetText(_edtXPath.Text); try { IHighlighter highlighter = new DocumentHighlighter( _edtXPath.Document, _edtXPath.SyntaxHighlighting.MainRuleSet); string html = HtmlClipboard.CreateHtmlFragment( _edtXPath.Document, highlighter, null, new HtmlOptions()); HtmlClipboard.SetHtml(dobj, html); } catch { //ignore } Clipboard.SetDataObject(dobj); } }
/// <summary> /// Creates a HTML fragment for the selected text. /// </summary> public string CreateHtmlFragment(TextArea textArea, HtmlOptions options) { if (textArea == null) { throw new ArgumentNullException("textArea"); } if (options == null) { throw new ArgumentNullException("options"); } DocumentHighlighter highlighter = textArea.GetService(typeof(DocumentHighlighter)) as DocumentHighlighter; StringBuilder html = new StringBuilder(); bool first = true; foreach (ISegment selectedSegment in this.Segments) { if (first) { first = false; } else { html.AppendLine("<br>"); } html.Append(HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, selectedSegment, options)); } return(html.ToString()); }
public string GenerateHtml(TextDocument document, IHighlightingDefinition highlightDefinition) { DocumentHighlighter documentHighlighter = null; if (highlightDefinition != null) { documentHighlighter = new DocumentHighlighter(document, highlightDefinition); } return(GenerateHtml(document, documentHighlighter)); }
SearchedFile SearchFile(FileName fileName) { ITextBuffer buffer = fileFinder.Create(fileName); if (buffer == null) { return(null); } ThrowIfCancellationRequested(); var source = DocumentUtilitites.GetTextSource(buffer); TextDocument document = null; DocumentHighlighter highlighter = null; int offset = 0; int length = source.TextLength; if (Target == SearchTarget.CurrentSelection && Selection != null) { offset = Selection.Offset; length = Selection.Length; } List <SearchResultMatch> results = new List <SearchResultMatch>(); foreach (var result in strategy.FindAll(source, offset, length)) { ThrowIfCancellationRequested(); if (document == null) { document = new TextDocument(source); var highlighting = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(fileName)); if (highlighting != null) { highlighter = new DocumentHighlighter(document, highlighting.MainRuleSet); } else { highlighter = null; } } var start = document.GetLocation(result.Offset).ToLocation(); var end = document.GetLocation(result.Offset + result.Length).ToLocation(); var builder = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter); results.Add(new AvalonEditSearchResultMatch(fileName, start, end, result.Offset, result.Length, builder, result)); } if (results.Count > 0) { return(new SearchedFile(fileName, results)); } else { return(null); } }
public ISyntaxHighlighter CreateHighlighter(IDocument document, string fileName) { var def = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(fileName)); var doc = document.GetService(typeof(TextDocument)) as TextDocument; if (def == null || doc == null) { return(null); } var baseHighlighter = new DocumentHighlighter(doc, def.MainRuleSet); var highlighter = new CustomizableHighlightingColorizer.CustomizingHighlighter(CustomizedHighlightingColor.FetchCustomizations(def.Name), baseHighlighter); return(new DocumentSyntaxHighlighter(document, highlighter, def.Name)); }
/// <summary> /// Converts a readonly TextDocument to a RichText and applies the provided highlighting definition. /// </summary> public static RichText ConvertTextDocumentToRichText(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition) { IHighlighter highlighter; if (highlightingDefinition != null) { highlighter = new DocumentHighlighter(document, highlightingDefinition); } else { highlighter = null; } return(ConvertTextDocumentToRichText(document, highlighter)); }
public void AddCodeBlock(string textContent, bool keepLargeMargin = false) { var document = new TextDocument(textContent); var highlighter = new DocumentHighlighter(document, highlightingDefinition); var richText = DocumentPrinter.ConvertTextDocumentToRichText(document, highlighter).ToRichTextModel(); var block = new Paragraph(); block.Inlines.AddRange(richText.CreateRuns(document)); block.FontFamily = GetCodeFont(); if (!keepLargeMargin) { block.Margin = new Thickness(0, 6, 0, 6); } AddBlock(block); }
const string LineSelectedType = "MSDEVLineSelect"; // This is the type VS 2003 and 2005 use for flagging a whole line copy static void CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); string text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS DataObject data = new DataObject(NewLineFinder.NormalizeNewLines(text, Environment.NewLine)); // Also copy text in HTML format to clipboard - good for pasting text into Word // or to the SharpDevelop forums. DocumentHighlighter highlighter = textArea.GetService(typeof(DocumentHighlighter)) as DocumentHighlighter; HtmlClipboard.SetHtml(data, HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, new HtmlOptions(textArea.Options))); MemoryStream lineSelected = new MemoryStream(1); lineSelected.WriteByte(1); data.SetData(LineSelectedType, lineSelected, false); Clipboard.SetDataObject(data, true); }
public async Task <IEnumerable <RtfItem> > Init(string path, string extension) { using (var file = new StreamReader(path, _encoding)) { Text = await file.ReadToEndAsync(); } _textDocument = new TextDocument(Text); _highlightingDefinition = HighlightingManager.Instance.GetDefinitionByExtension(extension); if (_highlightingDefinition != null) { _highlighter = new DocumentHighlighter(_textDocument, _highlightingDefinition); SetHighlightColors(_highlightingDefinition); } var lines = Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None); return(lines.Select((l, index) => new RtfItem(this, l, index + 1))); }
/// <summary> /// Creates a HTML fragment for the selected part of the document. /// </summary> public static string CreateHtmlFragmentForSelection(TextArea textArea, HtmlOptions options) { if (textArea == null) { throw new ArgumentNullException("textArea"); } if (options == null) { throw new ArgumentNullException("options"); } DocumentHighlighter highlighter = textArea.GetService(typeof(DocumentHighlighter)) as DocumentHighlighter; StringBuilder html = new StringBuilder(); foreach (ISegment selectedSegment in textArea.Selection.Segments) { html.AppendLine(CreateHtmlFragment(textArea.Document, highlighter, selectedSegment, options)); } return(html.ToString()); }
protected override void Execute(EditorFrame ef) { TextEditor textEditor = ef.XmlEditor; if (textEditor == null) { throw new Exception("No XmlEditor"); } SaveFileDialog dlgSaveFile = new SaveFileDialog(); dlgSaveFile.Filter = "Html Files|*.html|All Files|*.*"; dlgSaveFile.Title = "Select an Html file to save"; if (string.IsNullOrWhiteSpace(ef.XSDocument.Filename)) { dlgSaveFile.FileName = "undefined.html"; } else { dlgSaveFile.FileName = ef.XSDocument.Filename + ".html"; } if (dlgSaveFile.ShowDialog() == true) { try { IHighlighter highlighter = new DocumentHighlighter( textEditor.Document, textEditor.SyntaxHighlighting.MainRuleSet); string html = HtmlClipboard.CreateHtmlFragment( textEditor.Document, highlighter, null, new HtmlOptions()); File.WriteAllText(dlgSaveFile.FileName, html); } catch (Exception ex) { MessageBox.Show(Application.Current.MainWindow, ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Creates a HTML fragment from a part of a document. /// </summary> /// <param name="document">The document to create HTML from.</param> /// <param name="highlighter">The highlighter used to highlight the document.</param> /// <param name="segment">The part of the document to create HTML for. You can pass null to create HTML for the whole document.</param> /// <param name="options">The options for the HTML creation.</param> /// <returns>HTML code for the document part.</returns> public static string CreateHtmlFragment(TextDocument document, DocumentHighlighter highlighter, ISegment segment, HtmlOptions options) { if (document == null) { throw new ArgumentNullException("document"); } if (options == null) { throw new ArgumentNullException("options"); } if (segment == null) { segment = new SimpleSegment(0, document.TextLength); } StringBuilder html = new StringBuilder(); int segmentEndOffset = segment.EndOffset; DocumentLine line = document.GetLineByOffset(segment.Offset); while (line != null && line.Offset < segmentEndOffset) { HighlightedLine highlightedLine; if (highlighter != null) { highlightedLine = highlighter.HighlightLine(line); } else { highlightedLine = new HighlightedLine(line); } SimpleSegment s = segment.GetOverlap(line); if (html.Length > 0) { html.AppendLine("<br>"); } html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options)); line = line.NextLine; } return(html.ToString()); }
public static void ShowAsSearchResults(string title, List <Reference> list) { if (list == null) { return; } List <SearchResultMatch> results = new List <SearchResultMatch>(list.Count); TextDocument document = null; FileName fileName = null; IHighlighter highlighter = null; foreach (Reference r in list) { var f = new FileName(r.FileName); if (document == null || !f.Equals(fileName)) { document = new TextDocument(DocumentUtilitites.GetTextSource(ParserService.GetParseableFileContent(r.FileName))); fileName = new FileName(r.FileName); var def = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(r.FileName)); if (def != null) { highlighter = new DocumentHighlighter(document, def.MainRuleSet); } else { highlighter = null; } } var start = document.GetLocation(r.Offset).ToLocation(); var end = document.GetLocation(r.Offset + r.Length).ToLocation(); var builder = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter); SearchResultMatch res = new SearchResultMatch(fileName, start, end, r.Offset, r.Length, builder); results.Add(res); } SearchResultsPad.Instance.ShowSearchResults(title, results); SearchResultsPad.Instance.BringToFront(); }
public string GetHTMLString() { IHighlighter highlighter = new DocumentHighlighter(TextEditor.Document, TextEditor.SyntaxHighlighting); return(HtmlClipboard.CreateHtmlFragment(TextEditor.Document, highlighter, null, new HtmlOptions())); }
public void SetUp() { document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();"); highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#")); }
void DisplayTooltip(MouseEventArgs e) { int line = GetLineFromMousePosition(e); if (line == 0) { return; } int startLine; bool added; string oldText = changeWatcher.GetOldVersionFromLine(line, out startLine, out added); TextEditor editor = this.TextView.Services.GetService(typeof(TextEditor)) as TextEditor; markerService = this.TextView.Services.GetService(typeof(ITextMarkerService)) as ITextMarkerService; int offset, length; bool hasNewVersion = changeWatcher.GetNewVersionFromLine(line, out offset, out length); if (hasNewVersion) { if (marker != null) { markerService.Remove(marker); } if (length <= 0) { marker = null; length = 0; } else { marker = markerService.Create(offset, length); marker.BackgroundColor = Colors.LightGreen; } } if (oldText != null) { DiffControl differ = new DiffControl(); differ.editor.SyntaxHighlighting = editor.SyntaxHighlighting; differ.editor.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; differ.editor.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden; differ.editor.Document.Text = oldText; differ.Background = Brushes.White; // TODO : deletions on line 0 cannot be displayed. LineChangeInfo prevLineInfo = changeWatcher.GetChange(startLine - 1); LineChangeInfo lineInfo = changeWatcher.GetChange(startLine); if (prevLineInfo.Change == ChangeType.Deleted) { var docLine = editor.Document.GetLineByNumber(startLine - 1); differ.editor.Document.Insert(0, editor.Document.GetText(docLine.Offset, docLine.TotalLength)); } if (oldText == string.Empty) { differ.editor.Visibility = Visibility.Collapsed; differ.copyButton.Visibility = Visibility.Collapsed; } else { var baseDocument = new TextDocument(changeWatcher.BaseDocument.Text); if (differ.editor.SyntaxHighlighting != null) { var mainHighlighter = new DocumentHighlighter(baseDocument, differ.editor.SyntaxHighlighting.MainRuleSet); var popupHighlighter = differ.editor.TextArea.GetService(typeof(IHighlighter)) as DocumentHighlighter; if (prevLineInfo.Change == ChangeType.Deleted) { popupHighlighter.InitialSpanStack = mainHighlighter.GetSpanStack(prevLineInfo.OldStartLineNumber); } else { popupHighlighter.InitialSpanStack = mainHighlighter.GetSpanStack(lineInfo.OldStartLineNumber); } } } differ.revertButton.Click += delegate { if (hasNewVersion) { int delimiter = 0; DocumentLine l = Document.GetLineByOffset(offset + length); if (added) { delimiter = l.DelimiterLength; } if (length == 0) { oldText += DocumentUtilitites.GetLineTerminator(new AvalonEditDocumentAdapter(Document, null), l.LineNumber); } Document.Replace(offset, length + delimiter, oldText); tooltip.IsOpen = false; } }; tooltip.Child = new Border() { Child = differ, BorderBrush = Brushes.Black, BorderThickness = new Thickness(1) }; if (tooltip.IsOpen) { tooltip.IsOpen = false; } tooltip.IsOpen = true; tooltip.Closed += delegate { if (marker != null) { markerService.Remove(marker); } }; tooltip.HorizontalOffset = -10; tooltip.VerticalOffset = TextView.GetVisualTopByDocumentLine(startLine) - TextView.ScrollOffset.Y; tooltip.Placement = PlacementMode.Top; tooltip.PlacementTarget = this.TextView; } }
// See: http://stackoverflow.com/questions/21558386/avalonedit-getting-syntax-highlighted-text public void ApplyHighlighter(string code) { Inlines.Clear(); if (string.IsNullOrEmpty(code)) { return; } var item = this; var document = new TextDocument(code); var highlighter = new DocumentHighlighter(document, SyntaxHighlighting); var lineCount = document.LineCount; for (var lineNumber = 1; lineNumber <= document.LineCount; lineNumber++) { var line = highlighter.HighlightLine(lineNumber); var lineText = document.GetText(line.DocumentLine); var offset = line.DocumentLine.Offset; var sectionCount = line.Sections.Count; for (var sectionNumber = 0; sectionNumber < sectionCount; sectionNumber++) { var section = line.Sections[sectionNumber]; //Deal with previous text if (section.Offset > offset) { item.Inlines.Add(new Run(document.GetText(offset, section.Offset - offset))); } var runItem = new Run(document.GetText(section)); if (runItem.Foreground != null) { runItem.Foreground = section.Color.Foreground.GetBrush(null); } if (section.Color.FontWeight != null) { runItem.FontWeight = section.Color.FontWeight.Value; } item.Inlines.Add(runItem); offset = section.Offset + section.Length; } //Deal with stuff at end of line var lineEnd = line.DocumentLine.Offset + lineText.Length; if (lineEnd > offset) { item.Inlines.Add(new Run(document.GetText(offset, lineEnd - offset))); } //If not last line add a new line if (lineNumber < lineCount) { item.Inlines.Add(new Run("\n")); } } }
void DisplayTooltip(MouseEventArgs e) { int line = GetLineFromMousePosition(e); if (line == 0) { return; } int startLine; bool added; string oldText = changeWatcher.GetOldVersionFromLine(line, out startLine, out added); TextEditor editor = this.TextView.GetService <TextEditor>(); markerService = this.TextView.GetService <ITextMarkerService>(); LineChangeInfo zeroLineInfo = changeWatcher.GetChange(0); int offset, length; bool hasNewVersion = changeWatcher.GetNewVersionFromLine(line, out offset, out length); if (line == 1 && zeroLineInfo.Change == ChangeType.Deleted) { int zeroStartLine; bool zeroAdded; startLine = 1; string deletedText = changeWatcher.GetOldVersionFromLine(0, out zeroStartLine, out zeroAdded); var docLine = editor.Document.GetLineByNumber(line); string newLine = DocumentUtilities.GetLineTerminator(changeWatcher.CurrentDocument, 1); deletedText += newLine; deletedText += editor.Document.GetText(docLine.Offset, docLine.Length); if (oldText != null) { oldText = deletedText + newLine + oldText; } else { oldText = deletedText; } if (!hasNewVersion) { offset = 0; length = docLine.Length; hasNewVersion = true; } } if (hasNewVersion) { if (marker != null) { markerService.Remove(marker); } if (length <= 0) { marker = null; length = 0; } else { marker = markerService.Create(offset, length); marker.BackgroundColor = Colors.LightGreen; } } if (oldText != null) { LineChangeInfo currLineInfo = changeWatcher.GetChange(startLine); if (currLineInfo.Change == ChangeType.Deleted && !(line == 1 && zeroLineInfo.Change == ChangeType.Deleted)) { var docLine = editor.Document.GetLineByNumber(startLine); if (docLine.DelimiterLength == 0) { oldText = DocumentUtilities.GetLineTerminator(changeWatcher.CurrentDocument, startLine) + oldText; } oldText = editor.Document.GetText(docLine.Offset, docLine.TotalLength) + oldText; } DiffControl differ = new DiffControl(); differ.CopyEditorSettingsAndHighlighting(editor); differ.editor.Document.Text = oldText; if (oldText == string.Empty) { differ.editor.Visibility = Visibility.Collapsed; differ.copyButton.Visibility = Visibility.Collapsed; } else { if (differ.editor.SyntaxHighlighting != null) { var baseDocument = new ReadOnlyDocument(changeWatcher.BaseDocument, TextView.Document.FileName); var mainHighlighter = new DocumentHighlighter(baseDocument, differ.editor.SyntaxHighlighting); var popupHighlighter = differ.editor.TextArea.GetService(typeof(IHighlighter)) as DocumentHighlighter; popupHighlighter.InitialSpanStack = mainHighlighter.GetSpanStack(currLineInfo.OldStartLineNumber); } } differ.revertButton.Click += delegate { if (hasNewVersion) { Document.Replace(offset, length, oldText); tooltip.IsOpen = false; } }; const double borderThickness = 1; tooltip.Child = new Border { Child = differ, BorderBrush = editor.TextArea.Foreground, BorderThickness = new Thickness(borderThickness) }; if (tooltip.IsOpen) { tooltip.IsOpen = false; } tooltip.Closed += delegate { if (marker != null) { markerService.Remove(marker); } }; tooltip.HorizontalOffset = -borderThickness - TextView.ScrollOffset.X; tooltip.VerticalOffset = TextView.GetVisualTopByDocumentLine(startLine) - TextView.ScrollOffset.Y; tooltip.Placement = PlacementMode.Top; tooltip.PlacementTarget = this.TextView; tooltip.IsOpen = true; } }