This class can syntax-highlight a document. It automatically manages invalidating the highlighting when the document changes.
Наследование: ILineTracker, IHighlighter
Пример #1
0
        /// <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(document, 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();
        }
        void OnDocumentChanged()
        {
            if (highlighter != null && isInTextView)
            {
                textView.Services.RemoveService(typeof(DocumentHighlighter));
                textView.Services.RemoveService(typeof(IHighlighter));
            }

            TextDocument document = textView.Document;

            if (document != null)
            {
                highlighter = new TextViewDocumentHighlighter(this, document, ruleSet);
            }
            else
            {
                highlighter = null;
            }

            if (highlighter != null && isInTextView)
            {
                // for backward compatiblity, we're registering using both the interface and concrete types
                textView.Services.AddService(typeof(DocumentHighlighter), highlighter);
                textView.Services.AddService(typeof(IHighlighter), highlighter);
            }
        }
Пример #3
0
		/// <summary>
		/// Converts a readonly TextDocument to a Block and applies the provided highlighting definition.
		/// </summary>
		public static Block ConvertTextDocumentToBlock(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
		{
			IHighlighter highlighter;
			if (highlightingDefinition != null)
				highlighter = new DocumentHighlighter(document, highlightingDefinition);
			else
				highlighter = null;
			return ConvertTextDocumentToBlock(document, highlighter);
		}
		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);
		}
		void OnDocumentChanged()
		{
			if (highlighter != null && isInTextView) {
				textView.Services.RemoveService(typeof(DocumentHighlighter));
			}
			
			TextDocument document = textView.Document;
			if (document != null)
				highlighter = new TextViewDocumentHighlighter(this, document, ruleSet);
			else
				highlighter = null;
			
			if (highlighter != null && isInTextView) {
				textView.Services.AddService(typeof(DocumentHighlighter), highlighter);
			}
		}
Пример #6
0
		void OnDocumentChanged()
		{
			if (highlighter != null && isInTextView) {
				textView.Services.RemoveService(typeof(DocumentHighlighter));
				textView.Services.RemoveService(typeof(IHighlighter));
			}
			
			TextDocument document = textView.Document;
			if (document != null)
				highlighter = new TextViewDocumentHighlighter(this, document, ruleSet);
			else
				highlighter = null;
			
			if (highlighter != null && isInTextView) {
				// for backward compatiblity, we're registering using both the interface and concrete types
				textView.Services.AddService(typeof(DocumentHighlighter), highlighter);
				textView.Services.AddService(typeof(IHighlighter), highlighter);
			}
		}
        /// <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());
        }
Пример #8
0
        void OnDocumentChanged()
        {
            if (highlighter != null && isInTextView)
            {
                textView.Services.RemoveService(typeof(DocumentHighlighter));
            }

            TextDocument document = textView.Document;

            if (document != null)
            {
                highlighter = new TextViewDocumentHighlighter(this, document, ruleSet);
            }
            else
            {
                highlighter = null;
            }

            if (highlighter != null && isInTextView)
            {
                textView.Services.AddService(typeof(DocumentHighlighter), highlighter);
            }
        }
Пример #9
0
		public HtmlClipboardTests()
		{
			document = new TextDocument("using System.Text;\n\tstring text = SomeMethod();");
			highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#").MainRuleSet);
		}
		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();
		}
		protected override void OnMouseMove(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);
					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;
			}
			
			base.OnMouseMove(e);
		}
Пример #12
0
        public void DetectState(TextEditor editor)
        {
            //Don't do anything if currently disabled
            if (this.State == AutoCompleteState.Disabled) return;

            //Then call the derived classes internal state detection (if any)
            this.DetectStateInternal(editor);

            //Work out what sort of token we are currently in and set our State appropriately
            DocumentHighlighter h = new DocumentHighlighter(editor.Document, Syntax.SyntaxManager.GetHighlighter("Turtle").MainRuleSet);
            DocumentLine line = editor.Document.GetLineByOffset(editor.CaretOffset);
            HighlightedLine result = h.HighlightLine(line);

            HighlightedSection current = result.Sections.FirstOrDefault(s => s.Offset <= editor.CaretOffset && (s.Offset + s.Length) > editor.CaretOffset);
            if (current != null)
            {
                if (current.Color != null)
                {
                    switch (current.Color.Name)
                    {
                        case "Keyword":
                            this.State = AutoCompleteState.Keyword;
                            this.StartOffset = current.Offset;
                            break;

                        case "URI":
                            this.State = AutoCompleteState.Uri;
                            this.StartOffset = current.Offset;
                            break;

                        case "QName":
                            this.State = AutoCompleteState.QName;
                            this.StartOffset = current.Offset;
                            break;

                        case "String":
                            String lit = editor.Document.GetText(current.Offset, current.Length);
                            if (lit.StartsWith("\"\"\""))
                            {
                                this.State = AutoCompleteState.LongLiteral;
                            }
                            else
                            {
                                this.State = AutoCompleteState.Literal;
                            }
                            break;

                        case "Comment":
                            this.State = AutoCompleteState.Comment;
                            this.StartOffset = current.Offset;
                            break;

                        case "BNode":
                            this.State = AutoCompleteState.BNode;
                            this.StartOffset = current.Offset;
                            break;

                        case "Variables":
                            this.State = AutoCompleteState.Variable;
                            this.StartOffset = current.Offset;
                            break;

                        default:
                            this.State = AutoCompleteState.None;
                            break;
                    }
                }
            }
        }
Пример #13
0
		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;
			
			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 = DocumentUtilitites.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 = DocumentUtilitites.GetLineTerminator(changeWatcher.CurrentDocument, startLine) + oldText;
					oldText = editor.Document.GetText(docLine.Offset, docLine.TotalLength) + oldText;
				}
				
				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;
				
				if (oldText == string.Empty) {
					differ.editor.Visibility = Visibility.Collapsed;
					differ.copyButton.Visibility = Visibility.Collapsed;
				} else {
					var baseDocument = new TextDocument(DocumentUtilitites.GetTextSource(changeWatcher.BaseDocument));
					if (differ.editor.SyntaxHighlighting != null) {
						var mainHighlighter = new DocumentHighlighter(baseDocument, differ.editor.SyntaxHighlighting.MainRuleSet);
						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;
					}
				};
				
				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;
			}
		}
Пример #14
0
 public HtmlClipboardTests()
 {
     document    = new TextDocument("using System.Text;\n\tstring text = SomeMethod();");
     highlighter = new DocumentHighlighter(document, HighlightingManager.Instance.GetDefinition("C#").MainRuleSet);
 }
        // 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"));
                }
            }
        }