void RefreshMarkers()
		{
			TypeReferencesResult res=null;
			try
			{
				var ParseCache = DResolverWrapper.CreateCacheList(Document);

				res = TypeReferenceFinder.Scan(SyntaxTree, ParseCache);

				RemoveMarkers(false);

				var txtDoc = Document.Editor.Document;

				DocumentLine curLine=null;
				int ln=-1;
				int len = 0;
				foreach (var id in res.TypeMatches)
				{
					var loc = DeepASTVisitor.ExtractIdLocation(id, out len);
					if(ln!=loc.Line)
						curLine = Document.Editor.GetLine(ln = loc.Line);

					var segment = new TextSegment(curLine.Offset,len);
					var m = new UnderlineTextSegmentMarker("keyword.semantic.type", loc.Column, TypeReferenceFinder.ExtractId(id));

					txtDoc.AddMarker(m);
					markers.Add(m);
				}
			}
			catch
			{
				
			}
		}
        public void GetSegmentsToRenameTest2()
        {
            string text = "";
            RenameProvider target;
            TextSegment segment = new TextSegment ();

            text        = "<expr>!*some comments*!     {myset}\r\n" +
                        "keyword = 'keyword' <expr>!another comment\r\n"+
                        "myterm = '<'{myset}'>'keyword";
            //in <expr>
            target = new RenameProvider (text, 1);
            segment = target.SelectedTextSegment;
            Assert.AreEqual ("expr".Length, segment.Length);
            Assert.AreEqual (1, segment.Offset);

            //in keyword - cursor is at 40, and item starts at 37
            target = new RenameProvider (text, 40);
            segment = target.SelectedTextSegment;
            Assert.AreEqual ("keyword".Length, segment.Length);
            Assert.AreEqual (37, segment.Offset);

            //in {myset}
            target = new RenameProvider (text, 29);
            segment = target.SelectedTextSegment;
            Assert.AreEqual ("myset".Length, segment.Length);
            Assert.AreEqual (29, segment.Offset);

            //in <expr> (2nd occurence)
            target = new RenameProvider (text, 60);
            segment = target.SelectedTextSegment;
            Assert.AreEqual ("expr".Length, segment.Length);
            Assert.AreEqual (58, segment.Offset);
        }
Beispiel #3
0
		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 ();
		}
Beispiel #4
0
		protected override void Execute()
		{
			foreach (var node in _bindVariable.Nodes.Where(n => _allOccurences || n == CurrentNode))
			{
				var textSegment =
					new TextSegment
					{
						IndextStart = node.ParentNode.SourcePosition.IndexStart,
						Length = node.ParentNode.SourcePosition.Length
					};
				
				switch (_bindVariable.DataType)
				{
					case TerminalValues.Number:
						textSegment.Text = Convert.ToString(_bindVariable.Value);
						break;
					case TerminalValues.Date:
						textSegment.Text = $"DATE'{_bindVariable.Value}'";
						break;
					case TerminalValues.Timestamp:
						textSegment.Text = $"TIMESTAMP'{_bindVariable.Value}'";
						break;
					default:
						textSegment.Text = $"'{_bindVariable.Value}'";
						break;
				}

				ExecutionContext.SegmentsToReplace.Add(textSegment);
			}
		}
		protected override ISegment CreateTrackedSegment(int offset, int length)
		{
			var segment = new TextSegment();
			segment.StartOffset = offset;
			segment.Length = length;
			textSegmentCollection.Add(segment);
			return segment;
		}
		public bool Equals (TextSegment other)
		{
			if (other == null)
				return false;
			
			return Equals (Text, other.Text) &&
				StartLocation == other.StartLocation &&
				EndLocation == other.EndLocation;
		}
 private UnderlineTextSegmentMarker CreateMarker(TextSegment segment, 
                                                 Color color)
 {
     return new UnderlineTextSegmentMarker(color, segment)
     {
         IsVisible = true,
         Wave = false
     };
 }
Beispiel #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GoldAddin.RenameProvider"/> class.
 /// </summary>
 /// <param name="text">The document text</param>
 /// <param name="documentPosition">Position within the text</param>
 public RenameProvider(string text, int documentPosition)
 {
     textSegmentList = new List<TextSegment> ();
     primarySegment = new TextSegment ();
     symbolType = DefinitionType.None;
     if (!string.IsNullOrEmpty (text))
     {
         findSegmentsForRenaming (text, documentPosition);
     }
 }
 private static MenuItem SpellSuggestMenuItem(string header, TextSegment segment)
 {
     return new MenuItem
     {
         Header = header,
         FontWeight = FontWeights.Bold,
         Command = EditingCommands.CorrectSpellingError,
         CommandParameter = new Tuple<string, TextSegment>(header, segment)
     };
 }
        public static void Run()
        {
            // ExStart:AddTOC
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

            // Load an existing PDF files
            Document doc = new Document(dataDir + "AddTOC.pdf");

            // Get access to first page of PDF file
            Page tocPage = doc.Pages.Insert(1);

            // Create object to represent TOC information
            TocInfo tocInfo = new TocInfo();
            TextFragment title = new TextFragment("Table Of Contents");
            title.TextState.FontSize = 20;
            title.TextState.FontStyle = FontStyles.Bold;

            // Set the title for TOC
            tocInfo.Title = title;
            tocPage.TocInfo = tocInfo;

            // Create string objects which will be used as TOC elements
            string[] titles = new string[4];
            titles[0] = "First page";
            titles[1] = "Second page";
            titles[2] = "Third page";
            titles[3] = "Fourth page";
            for (int i = 0; i < 2; i++)
            {
                // Create Heading object
                Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
                TextSegment segment2 = new TextSegment();
                heading2.TocPage = tocPage;
                heading2.Segments.Add(segment2);

                // Specify the destination page for heading object
                heading2.DestinationPage = doc.Pages[i + 2];

                // Destination page
                heading2.Top = doc.Pages[i + 2].Rect.Height;

                // Destination coordinate
                segment2.Text = titles[i];

                // Add heading to page containing TOC
                tocPage.Paragraphs.Add(heading2);
            }
            dataDir = dataDir + "TOC_out.pdf";
            // Save the updated document
            doc.Save(dataDir);
            // ExEnd:AddTOC
            Console.WriteLine("\nTOC added successfully to an existing PDF.\nFile saved at " + dataDir);
        }
        public static void MoveToSegment(MonoDevelop.Ide.Gui.Document doc, TextSegment segment)
        {
            if(segment.IsInvalid || segment.IsEmpty)
                return;

            TextEditorData data = doc.Editor;
            data.Caret.Offset = segment.Offset;
            data.Parent.ScrollTo(segment.EndOffset);

            var loc = data.Document.OffsetToLocation(segment.EndOffset);
            if(data.Parent.TextViewMargin.ColumnToX(data.Document.GetLine (loc.Line), loc.Column) < data.HAdjustment.PageSize)
                data.HAdjustment.Value = 0;
        }
        public static void Main(string[] args)
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            // Load an existing PDF files
            Document doc = new Document(dataDir + "input.pdf");

            // Get access to first page of PDF file
            Page tocPage = doc.Pages.Insert(1);

            // Create object to represent TOC information
            TocInfo tocInfo = new TocInfo();
            TextFragment title = new TextFragment("Table Of Contents");
            title.TextState.FontSize = 20;
            title.TextState.FontStyle = FontStyles.Bold;

            // Set the title for TOC
            tocInfo.Title = title;
            tocPage.TocInfo = tocInfo;

            // Create string objects which will be used as TOC elements
            string[] titles = new string[4];
            titles[0] = "First page";
            titles[1] = "Second page";
            titles[2] = "Third page";
            titles[3] = "Fourth page";
            for (int i = 0; i < 2; i++)
            {
                // Create Heading object
                Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
                TextSegment segment2 = new TextSegment();
                heading2.TocPage = tocPage;
                heading2.Segments.Add(segment2);

                // Specify the destination page for heading object
                heading2.DestinationPage = doc.Pages[i + 2];

                // Destination page
                heading2.Top = doc.Pages[i + 2].Rect.Height;

                // Destination coordinate
                segment2.Text = titles[i];

                // Add heading to page containing TOC
                tocPage.Paragraphs.Add(heading2);
            }
            // Save the updated document
            doc.Save(dataDir + "TOC_Output.pdf");
        }
Beispiel #13
0
		public static List<List<ColoredSegment>> GetChunks (TextEditorData data, TextSegment selectedSegment)
		{
			int startLineNumber = data.OffsetToLineNumber (selectedSegment.Offset);
			int endLineNumber = data.OffsetToLineNumber (selectedSegment.EndOffset);
			var copiedColoredChunks = new List<List<ColoredSegment>> ();
			foreach (var line in data.Document.GetLinesBetween (startLineNumber, endLineNumber)) {
				copiedColoredChunks.Add (
					data.GetChunks (
					line, 
					System.Math.Max (selectedSegment.Offset, line.Offset),
					System.Math.Max (selectedSegment.EndOffset, line.EndOffset) - line.Offset
					)
					.Select (chunk => new ColoredSegment (chunk, data.Document))
					.ToList ()
				);
			}
			return copiedColoredChunks;
		}
Beispiel #14
0
		public static string GenerateHtml (TextDocument doc, Mono.TextEditor.Highlighting.ISyntaxMode mode, Mono.TextEditor.Highlighting.ColorScheme style, ITextEditorOptions options)
		{
			var htmlText = new StringBuilder ();

			htmlText.Append (@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN""><HTML><BODY>");

			var selection = new TextSegment (0, doc.TextLength);
			int startLineNumber = doc.OffsetToLineNumber (selection.Offset);
			int endLineNumber = doc.OffsetToLineNumber (selection.EndOffset);
			htmlText.Append ("<FONT face = '" + options.Font.Family + "'>");
			bool first = true;
			foreach (var line in doc.GetLinesBetween (startLineNumber, endLineNumber)) {
				if (!first) {
					htmlText.Append ("<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;
				}

				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.Bold)
							htmlText.Append ("font-weight:bold;");
						if (chunkStyle.Italic)
							htmlText.Append ("font-style:italic;");
						htmlText.Append ("color:" + ((HslColor)chunkStyle.Foreground).ToPangoString () + ";");
						htmlText.Append ("' >");
						AppendHtmlText (htmlText, doc, options, start, end);
						htmlText.Append ("</SPAN>");
					}
				}
			}
			htmlText.Append ("</FONT>");
			htmlText.Append ("</BODY></HTML>");
			return htmlText.ToString ();
		}
Beispiel #15
0
		public static TextEditorData Create (string input, bool reverse)
		{
			TextEditorData data = new Mono.TextEditor.TextEditorData ();
			
			int offset1 = input.IndexOf ('[');
			int offset2 = input.IndexOf (']');
			var selection = new TextSegment (offset1, offset2 - offset1 - 1);

			data.Text = input.Substring (0, offset1) + input.Substring (offset1 + 1, (offset2 - offset1) - 1) + input.Substring (offset2 + 1);
			if (reverse) {
				data.Caret.Offset = selection.Offset;
				data.SelectionAnchor = selection.EndOffset;
				data.ExtendSelectionTo (selection.Offset);
			} else {
				data.Caret.Offset = selection.EndOffset;
				data.SelectionAnchor = selection.Offset;
				data.ExtendSelectionTo (selection.EndOffset);
			}
			return data;
		}
		public CodeSegmentPreviewWindow (TextEditor editor, bool hideCodeSegmentPreviewInformString, TextSegment segment, int width, int height, bool removeIndent = true) : base (Gtk.WindowType.Popup)
		{
			this.HideCodeSegmentPreviewInformString = hideCodeSegmentPreviewInformString;
			this.Segment = segment;
			this.editor = editor;
			this.AppPaintable = true;
			this.SkipPagerHint = this.SkipTaskbarHint = true;
			this.TypeHint = WindowTypeHint.Menu;
			layout = PangoUtil.CreateLayout (this);
			informLayout = PangoUtil.CreateLayout (this);
			informLayout.SetText (CodeSegmentPreviewInformString);
			
			fontDescription = Pango.FontDescription.FromString (editor.Options.FontName);
			fontDescription.Size = (int)(fontDescription.Size * 0.8f);
			layout.FontDescription = fontDescription;
			layout.Ellipsize = Pango.EllipsizeMode.End;
			// setting a max size for the segment (40 lines should be enough), 
			// no need to markup thousands of lines for a preview window
			SetSegment (segment, removeIndent);
			CalculateSize (width);
		}
        // ExStart:DrawBox
        private static void DrawBox(PdfContentEditor editor, int page, TextSegment segment, System.Drawing.Color color)
        {

            var lineInfo = new LineInfo();

            lineInfo.VerticeCoordinate = new[] {

            (float)segment.Rectangle.LLX, (float)segment.Rectangle.LLY,

            (float)segment.Rectangle.LLX, (float)segment.Rectangle.URY,

            (float)segment.Rectangle.URX, (float)segment.Rectangle.URY,

            (float)segment.Rectangle.URX, (float)segment.Rectangle.LLY

            };

            lineInfo.Visibility = true;

            lineInfo.LineColor = color;

            editor.CreatePolygon(lineInfo, page, new System.Drawing.Rectangle(0, 0, 0, 0), null);

        }
Beispiel #18
0
        void WriteStreamHeader(ref uint offset, TextSegment heap, string name)
        {
            var length = (uint) text_map.GetLength (heap);
            if (length == 0)
                return;

            WriteUInt32 (offset);
            WriteUInt32 (length);
            WriteBytes (GetZeroTerminatedString (name));
            offset += length;
        }
Beispiel #19
0
        RVA GetStart(TextSegment segment)
        {
            var index = (int)segment;

            return(index == 0 ? ImageWriter.text_rva : ComputeStart(index));
        }
Beispiel #20
0
        /// <summary>
        /// Modifies the passed in TextAnchor to contain its relative
        /// complement to the set of text segments passed in.  The resulting
        /// TextAnchor contains those segments or portions of segments that do
        /// not overlap with the passed in segments in anyway.  If after trimming
        /// the anchor has no more segments, null is returned instead.  Callers
        /// should assign the result of this method to the anchor they passed in.
        /// </summary>
        /// <param name="anchor">the anchor to trim</param>
        /// <param name="textSegments">the text segments to calculate relative complement with</param>
        /// <remarks>Note: textSegments is expected to be ordered and contain no overlapping segments</remarks>
        internal static TextAnchor TrimToRelativeComplement(TextAnchor anchor, ICollection <TextSegment> textSegments)
        {
            Invariant.Assert(anchor != null, "Anchor must not be null.");
            Invariant.Assert(textSegments != null, "TextSegments must not be null.");

            textSegments = SortTextSegments(textSegments, true);

            IEnumerator <TextSegment> enumerator = textSegments.GetEnumerator();
            bool        hasMore      = enumerator.MoveNext();
            int         currentIndex = 0;
            TextSegment current;
            TextSegment otherSegment = TextSegment.Null;

            while (currentIndex < anchor._segments.Count && hasMore)
            {
                Invariant.Assert(otherSegment.Equals(TextSegment.Null) || otherSegment.Equals(enumerator.Current) || otherSegment.End.CompareTo(enumerator.Current.Start) <= 0, "TextSegments are overlapping or not ordered.");

                current      = anchor._segments[currentIndex];
                otherSegment = enumerator.Current;

                // Current segment is after other segment, no overlap
                // Also, done with the other segment, move to the next one
                if (current.Start.CompareTo(otherSegment.End) >= 0)
                {
                    hasMore = enumerator.MoveNext();
                    continue;  // No increment, still processing the current segment
                }

                // Current segment starts after other segment starts and ...
                if (current.Start.CompareTo(otherSegment.Start) >= 0)
                {
                    // ends before other segment ends, complete overlap, remove the segment
                    if (current.End.CompareTo(otherSegment.End) <= 0)
                    {
                        anchor._segments.RemoveAt(currentIndex);
                        continue;  // No increment, happens implicitly because of the removal
                    }
                    else
                    {
                        // ends after other segment, first portion of current overlaps,
                        // create new segment from end of other segment to end of current
                        anchor._segments[currentIndex] = CreateNormalizedSegment(otherSegment.End, current.End);
                        // Done with the other segment, move to the next one
                        hasMore = enumerator.MoveNext();
                        continue; // No increment, need to process just created segment
                    }
                }
                // Current segment starts before other segment starts and ...
                else
                {
                    // ends after it starts, first portion of current does not overlap,
                    // create new segment for that portion
                    if (current.End.CompareTo(otherSegment.Start) > 0)
                    {
                        anchor._segments[currentIndex] = CreateNormalizedSegment(current.Start, otherSegment.Start);
                        // If there's any portion of current after other segment, create a new segment for that which
                        // will be the next one processed
                        if (current.End.CompareTo(otherSegment.End) > 0)
                        {
                            // Overlap ends before current segment's end, we create a new segment with the remainder of current segment
                            anchor._segments.Insert(currentIndex + 1, CreateNormalizedSegment(otherSegment.End, current.End));
                            // Done with the other segment, move to the next one
                            hasMore = enumerator.MoveNext();
                        }
                    }
                    // ends before it starts, current is completely before other, no overlap, do nothing
                }

                currentIndex++;
            }

            if (anchor._segments.Count > 0)
            {
                return(anchor);
            }
            else
            {
                return(null);
            }
        }
Beispiel #21
0
 public AddChildCommand(IPanel canvas, RectangleSegment newRect, LineSegment lineChild, TextSegment textSegmentChild
                        , ButtonObject childBtnObject, Guid nodeID, List <RectangleSegment> rectChild, List <MindmapTree> child, RectangleSegment node)
 {
     this.childBtnObject   = childBtnObject;
     this.textSegmentChild = textSegmentChild;
     this.newRect          = newRect;
     this.lineChild        = lineChild;
     this.canvas           = canvas;
     this.nodeID           = nodeID;
     this.rectChild        = rectChild;
     this.child            = child;
     this.node             = node;
 }
Beispiel #22
0
        protected override void DocumentParsed()
        {
            var parsedDocument = documentContext.ParsedDocument;

            if (parsedDocument == null)
            {
                return;
            }
            var resolver = parsedDocument.GetAst <SemanticModel> ();

            if (resolver == null)
            {
                return;
            }
            CancelHighlightingTask();
            var token = src.Token;
            var theme = editor.Options.GetEditorTheme();

            Task.Run(async delegate {
                try {
                    var root    = await resolver.SyntaxTree.GetRootAsync(token);
                    var newTree = new HighlightingSegmentTree();

                    var visitor = new HighlightingVisitior(theme, resolver, newTree.Add, token, TextSegment.FromBounds(0, root.FullSpan.Length));
                    visitor.Visit(root);

                    if (!token.IsCancellationRequested)
                    {
                        Gtk.Application.Invoke(delegate {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            if (highlightTree != null)
                            {
                                highlightTree.RemoveListener();
                            }
                            highlightTree = newTree;
                            highlightTree.InstallListener(editor);
                            NotifySemanticHighlightingUpdate();
                        });
                    }
                } catch (OperationCanceledException) {
                } catch (AggregateException ae) {
                    ae.Flatten().Handle(x => x is OperationCanceledException);
                }
            }, token);
        }
            //this runs as a glib idle handler so it can add/remove text editor markers
            //in order to to block the GUI thread, we batch them in UPDATE_COUNT
            bool IdleHandler()
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }
                var editor = ext.Editor;

                if (editor == null)
                {
                    return(false);
                }
                //clear the old results out at the same rate we add in the new ones
                for (int i = 0; oldMarkers > 0 && i < UPDATE_COUNT; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    editor.RemoveMarker(ext.markers.Dequeue());
                    oldMarkers--;
                }
                //add in the new markers
                for (int i = 0; i < UPDATE_COUNT; i++)
                {
                    if (!enumerator.MoveNext())
                    {
                        ext.tasks = builder.ToImmutable();
                        ext.OnTasksUpdated(EventArgs.Empty);
                        return(false);
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    var currentResult = (Result)enumerator.Current;
                    if (currentResult.InspectionMark != IssueMarker.None)
                    {
                        int start = currentResult.Region.Start;
                        int end   = currentResult.Region.End;
                        if (start >= end)
                        {
                            continue;
                        }
                        if (currentResult.InspectionMark == IssueMarker.GrayOut)
                        {
                            var marker = TextMarkerFactory.CreateGenericTextSegmentMarker(editor, TextSegmentMarkerEffect.GrayOut, TextSegment.FromBounds(start, end));
                            marker.IsVisible = currentResult.Underline;
                            marker.Tag       = currentResult;
                            editor.AddMarker(marker);
                            ext.markers.Enqueue(marker);
//							editor.Parent.TextViewMargin.RemoveCachedLine (editor.GetLineByOffset (start));
//							editor.Parent.QueueDraw ();
                        }
                        else
                        {
                            var effect = currentResult.InspectionMark == IssueMarker.DottedLine ? TextSegmentMarkerEffect.DottedLine : TextSegmentMarkerEffect.WavedLine;
                            var marker = TextMarkerFactory.CreateGenericTextSegmentMarker(editor, effect, TextSegment.FromBounds(start, end));
                            marker.Color     = GetColor(editor, currentResult);
                            marker.IsVisible = currentResult.Underline;
                            marker.Tag       = currentResult;
                            editor.AddMarker(marker);
                            ext.markers.Enqueue(marker);
                        }
                    }
                    builder.Add(new QuickTask(currentResult.Message, currentResult.Region.Start, currentResult.Level));
                }

                return(true);
            }
		public CodeSegmentPreviewWindow (TextEditor editor, bool hideCodeSegmentPreviewInformString, TextSegment segment, bool removeIndent = true) : this(editor, hideCodeSegmentPreviewInformString, segment, DefaultPreviewWindowWidth, DefaultPreviewWindowHeight, removeIndent)
		{
		}
Beispiel #25
0
 public void AddMap(TextSegment segment, Range range)
 {
     this.map[(int)segment] = range;
 }
Beispiel #26
0
        private uint GetStart(TextSegment segment)
        {
            int index = (int)segment;

            return((index == 0) ? 0x2000 : this.ComputeStart(index));
        }
Beispiel #27
0
 public uint GetRVA(TextSegment segment) =>
 this.map[(int)segment].Start;
Beispiel #28
0
 public Range GetRange(TextSegment segment) =>
 this.map[(int)segment];
Beispiel #29
0
        public uint GetNextRVA(TextSegment segment)
        {
            int index = (int)segment;

            return(this.map[index].Start + this.map[index].Length);
        }
Beispiel #30
0
 public int GetLength(TextSegment segment) =>
 ((int)this.map[(int)segment].Length);
Beispiel #31
0
        public DataDirectory GetDataDirectory(TextSegment segment)
        {
            Range range = this.map[(int)segment];

            return(new DataDirectory((range.Length == 0) ? 0 : range.Start, range.Length));
        }
Beispiel #32
0
			static string GenerateRtf (TextDocument doc, Mono.TextEditor.Highlighting.ISyntaxMode mode, Mono.TextEditor.Highlighting.ColorScheme style, ITextEditorOptions options)
			{
				StringBuilder rtfText = new StringBuilder ();
				List<Gdk.Color> 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;
					foreach (Chunk 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);
						ChunkStyle 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;
							}
							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;
								}
							}
						}
					}
					rtfText.Append (@"\par");
					rtfText.AppendLine ();
				}
				
				// color table

				StringBuilder colorTable = new StringBuilder ();
				colorTable.Append (@"{\colortbl ;");
				for (int i = 0; i < colorList.Count; i++) {
					Gdk.Color color = colorList[i];
					colorTable.Append (@"\red");
					colorTable.Append (color.Red / 256);
					colorTable.Append (@"\green");
					colorTable.Append (color.Green / 256); 
					colorTable.Append (@"\blue");
					colorTable.Append (color.Blue / 256);
					colorTable.Append (";");
				}
				colorTable.Append ("}");
				
				StringBuilder 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 (colorTable.ToString ());
				
				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("}");
//				System.Console.WriteLine(rtf);
				return rtf.ToString ();
			}
		void ShowTooltip (TextSegment segment, Rectangle hintRectangle)
		{
			if (previewWindow != null && previewWindow.Segment == segment)
				return;
			CancelCodeSegmentTooltip ();
			HideCodeSegmentPreviewWindow ();
			if (segment.IsInvalid || segment.Length == 0)
				return;
			codeSegmentTooltipTimeoutId = GLib.Timeout.Add (650, delegate {
				previewWindow = new CodeSegmentPreviewWindow (textEditor, false, segment);
				if (previewWindow.IsEmptyText) {
					previewWindow.Destroy ();
					previewWindow = null;
					return false;
				}
					
				int ox = 0, oy = 0;
				this.textEditor.GdkWindow.GetOrigin (out ox, out oy);
				ox += textEditor.Allocation.X;
				oy += textEditor.Allocation.Y;

				int x = hintRectangle.Right;
				int y = hintRectangle.Bottom;
				previewWindow.CalculateSize ();
				var req = previewWindow.SizeRequest ();
				int w = req.Width;
				int h = req.Height;

				var geometry = this.textEditor.Screen.GetUsableMonitorGeometry (this.textEditor.Screen.GetMonitorAtPoint (ox + x, oy + y));

				if (x + ox + w > geometry.X + geometry.Width)
					x = hintRectangle.Left - w;
				if (y + oy + h > geometry.Y + geometry.Height)
					y = hintRectangle.Top - h;
				int destX = System.Math.Max (0, ox + x);
				int destY = System.Math.Max (0, oy + y);
				previewWindow.Move (destX, destY);
				previewWindow.ShowAll ();
				return false;
			});
		}
            //this runs as a glib idle handler so it can add/remove text editor markers
            //in order to to block the GUI thread, we batch them in UPDATE_COUNT
            bool IdleHandler()
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }
                var editor = ext.Editor;

                if (editor == null || editor.Document == null)
                {
                    return(false);
                }
                //clear the old results out at the same rate we add in the new ones
                for (int i = 0; oldMarkers > 0 && i < UPDATE_COUNT; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    editor.Document.RemoveMarker(ext.markers.Dequeue());
                    oldMarkers--;
                }
                //add in the new markers
                for (int i = 0; i < UPDATE_COUNT; i++)
                {
                    if (!enumerator.MoveNext())
                    {
                        ext.OnTasksUpdated(EventArgs.Empty);
                        return(false);
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    var currentResult = (Result)enumerator.Current;

                    if (currentResult.InspectionMark != IssueMarker.None)
                    {
                        int start = editor.LocationToOffset(currentResult.Region.Begin);
                        int end   = editor.LocationToOffset(currentResult.Region.End);
                        if (start >= end)
                        {
                            continue;
                        }
                        if (currentResult.InspectionMark == IssueMarker.GrayOut)
                        {
                            var marker = new GrayOutMarker(currentResult, TextSegment.FromBounds(start, end));
                            marker.IsVisible = currentResult.Underline;
                            editor.Document.AddMarker(marker);
                            ext.markers.Enqueue(marker);
                            editor.Parent.TextViewMargin.RemoveCachedLine(editor.GetLineByOffset(start));
                            editor.Parent.QueueDraw();
                        }
                        else
                        {
                            var marker = new ResultMarker(currentResult, TextSegment.FromBounds(start, end));
                            marker.IsVisible = currentResult.Underline;
                            editor.Document.AddMarker(marker);
                            ext.markers.Enqueue(marker);
                        }
                    }
                    ext.tasks.Add(new QuickTask(currentResult.Message, currentResult.Region.Begin, currentResult.Level));
                }

                return(true);
            }
Beispiel #35
0
 public void AddMap(TextSegment segment, int length, int align)
 {
     align--;
     this.AddMap(segment, (int)((length + align) & ~align));
 }
Beispiel #36
0
 public virtual void VisitTextSegment(TextSegment text)
 {
 }
        public static void Run()
        {
            // ExStart:ApplyNumberStyle
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Headings();

            Document pdfDoc = new Document();

            pdfDoc.PageInfo.Width         = 612.0;
            pdfDoc.PageInfo.Height        = 792.0;
            pdfDoc.PageInfo.Margin        = new Aspose.Pdf.MarginInfo();
            pdfDoc.PageInfo.Margin.Left   = 72;
            pdfDoc.PageInfo.Margin.Right  = 72;
            pdfDoc.PageInfo.Margin.Top    = 72;
            pdfDoc.PageInfo.Margin.Bottom = 72;

            Aspose.Pdf.Page pdfPage = pdfDoc.Pages.Add();
            pdfPage.PageInfo.Width         = 612.0;
            pdfPage.PageInfo.Height        = 792.0;
            pdfPage.PageInfo.Margin        = new Aspose.Pdf.MarginInfo();
            pdfPage.PageInfo.Margin.Left   = 72;
            pdfPage.PageInfo.Margin.Right  = 72;
            pdfPage.PageInfo.Margin.Top    = 72;
            pdfPage.PageInfo.Margin.Bottom = 72;

            Aspose.Pdf.FloatingBox floatBox = new Aspose.Pdf.FloatingBox();
            floatBox.Margin = pdfPage.PageInfo.Margin;

            pdfPage.Paragraphs.Add(floatBox);

            TextFragment textFragment = new TextFragment();
            TextSegment  segment      = new TextSegment();

            Aspose.Pdf.Heading heading = new Aspose.Pdf.Heading(1);
            heading.IsInList       = true;
            heading.StartNumber    = 1;
            heading.Text           = "List 1";
            heading.Style          = NumberingStyle.NumeralsRomanLowercase;
            heading.IsAutoSequence = true;

            floatBox.Paragraphs.Add(heading);

            Aspose.Pdf.Heading heading2 = new Aspose.Pdf.Heading(1);
            heading2.IsInList       = true;
            heading2.StartNumber    = 13;
            heading2.Text           = "List 2";
            heading2.Style          = NumberingStyle.NumeralsRomanLowercase;
            heading2.IsAutoSequence = true;

            floatBox.Paragraphs.Add(heading2);

            Aspose.Pdf.Heading heading3 = new Aspose.Pdf.Heading(2);
            heading3.IsInList       = true;
            heading3.StartNumber    = 1;
            heading3.Text           = "the value, as of the effective date of the plan, of property to be distributed under the plan onaccount of each allowed";
            heading3.Style          = NumberingStyle.LettersLowercase;
            heading3.IsAutoSequence = true;

            floatBox.Paragraphs.Add(heading3);
            dataDir = dataDir + "ApplyNumberStyle_out.pdf";
            pdfDoc.Save(dataDir);
            // ExEnd:ApplyNumberStyle
            Console.WriteLine("\nNumber style applied successfully in headings.\nFile saved at " + dataDir);
        }
		public void SetSegment (TextSegment segment, bool removeIndent)
		{
			int startLine = editor.Document.OffsetToLineNumber (segment.Offset);
			int endLine = editor.Document.OffsetToLineNumber (segment.EndOffset);
			
			bool pushedLineLimit = endLine - startLine > maxLines;
			if (pushedLineLimit)
				segment = new TextSegment (segment.Offset, editor.Document.GetLine (startLine + maxLines).Offset - segment.Offset);
			layout.Ellipsize = Pango.EllipsizeMode.End;
			layout.SetMarkup (editor.GetTextEditorData ().GetMarkup (segment.Offset, segment.Length, removeIndent) + (pushedLineLimit ? Environment.NewLine + "..." : ""));
			QueueDraw ();
		}
Beispiel #39
0
        private void DrawChild(int xStart, int yStart, int xFinish, int yFinish, int addX, int addY, int divisor, int modder, int startingpointX, int startingpointY, int counterside)
        {
            //this.X = node.VX1 + 75 * NumofChild();
            //this.Y = (node.VY1 - 120);
            int newRectStart = 0, newRectFinish = 0, newRectStagnan = 0;
            int multiplier = 0;

            if (counterside % 2 == 0)
            {
                if (counterside == 0)
                {
                    this.X = xStart + addX * (NumofChild() % modder);
                    this.Y = yStart + addY;
                }
                else
                {
                    this.X = xStart + addX * ((NumofChild() + 1) % modder);
                    this.Y = yStart + addY;
                }
            }
            else
            {
                this.X = xStart + addX;
                this.Y = yStart + addY * (NumofChild() % modder);
            }

            /*if (counterside == 0)
             * {
             *  this.X = xStart + addX * (NumofChild() % modder);
             *  this.Y = yStart + addY;
             * }
             * else if (counterside == 2)
             * {
             *  this.X = xStart + addX * (NumofChild()+1 % modder);
             *  this.Y = yStart + addY;
             * }
             */
            this.newRect = new RectangleSegment(X, Y, 70, 50);

            rectChild.Add(newRect);
            this.canvas.AddDrawingObject(newRect);
            this.canvas.AddRectangleObject(newRect);
            if (counterside == 0)
            {
                multiplier = NumofChild() % modder;
            }
            else if (counterside == 2)
            {
                multiplier = (NumofChild() % modder) + 1;
            }
            //set koordinat VX1
            this.newRect.VX1 = this.newRect.X;
            this.newRect.VY1 = this.newRect.Y;

            //set koordinat VX2, VY2
            this.newRect.VX2 = this.newRect.VX1 + this.newRect.Width;
            this.newRect.VY2 = this.newRect.VY1;

            this.newRect.VX3 = this.newRect.VX1;
            this.newRect.VY3 = this.newRect.VY1 + this.newRect.Height;

            this.newRect.VX4 = this.newRect.VX1 + this.newRect.Width;
            this.newRect.VY4 = this.newRect.VY1 + this.newRect.Height;

            if (counterside == 0)
            {
                newRectStart   = this.newRect.VX3;
                newRectFinish  = this.newRect.VX4;
                newRectStagnan = this.newRect.VY3;
                lineChild      = new LineSegment(new System.Drawing.Point(((xFinish - xStart) / divisor) * multiplier + startingpointX, startingpointY), new System.Drawing.Point((newRectStart + newRectFinish) / 2, newRectStagnan));
            }
            else if (counterside == 1)
            {
                newRectStart   = this.newRect.VY1;
                newRectFinish  = this.newRect.VY3;
                newRectStagnan = this.newRect.VX1;
                lineChild      = new LineSegment(new System.Drawing.Point(((xFinish - xStart) / divisor) * multiplier + startingpointX, startingpointY), new System.Drawing.Point(newRectStagnan, 50));
                //lineChild = new LineSegment(new System.Drawing.Point( startingpointX, ((yFinish - yStart) / divisor) * multiplier + startingpointY), new System.Drawing.Point(newRectStagnan, (newRectFinish - newRectStart) / 2));
                //  Debug.WriteLine("HASIL PADA COUNTERSIDE 1 koordinat Y : " + ((yFinish - yStart) / divisor) * multiplier + startingpointY + " FINISH : " + (newRectStart + newRectFinish) / 2);
            }
            else if (counterside == 2)
            {
                newRectStart   = this.newRect.VX1;
                newRectFinish  = this.newRect.VX2;
                newRectStagnan = this.newRect.VY1;
                lineChild      = new LineSegment(new System.Drawing.Point(((xFinish - xStart) / divisor) * multiplier + startingpointX, startingpointY), new System.Drawing.Point((newRectStart + newRectFinish) / 2, newRectStagnan));
            }
            else if (counterside == 3)
            {
                newRectStart   = this.newRect.VY2;
                newRectFinish  = this.newRect.VY4;
                newRectStagnan = this.newRect.VX2;
                lineChild      = new LineSegment(new System.Drawing.Point(startingpointX, ((yFinish - yStart) / divisor) * multiplier + startingpointY), new System.Drawing.Point(newRectStagnan, (newRectStart + newRectFinish) / 2));
            }
            //lineChild = new LineSegment(new System.Drawing.Point(((node.VX2 - node.VX1) / 4) * NumofChild() + node.VX1, node.VY1), new System.Drawing.Point((newRect.VX3 + newRect.VX4) / 2, newRect.VY3));
            lineChild = new LineSegment(new System.Drawing.Point(((xFinish - xStart) / divisor) * multiplier + startingpointX, startingpointY), new System.Drawing.Point((newRectStart + newRectFinish) / 2, newRectStagnan));
            this.canvas.AddDrawingObject(lineChild);
            node.Subscribe(lineChild);
            newRect.Subscribe(lineChild);
            lineChild.AddVertexStartObject(node);
            lineChild.AddVertexEndObject(newRect);

            MindmapTree mindmapTree = new MindmapTree(newRect, this.canvas);

            child.Add(mindmapTree);
            this.canvas.AddMindmapObject(mindmapTree);
            childBtnObject = new ButtonObject(X, Y, newRect.ID, this.canvas);
            this.canvas.AddButtonObject(childBtnObject);
            textSegmentChild          = new TextSegment();
            textSegmentChild.Value    = "Child";
            textSegmentChild.Position = new System.Drawing.PointF((float)((newRect.X + (newRect.X + newRect.Width)) / 2), (float)((newRect.Y + (newRect.Y + newRect.Height)) / 2));
            bool added = newRect.Add(textSegmentChild);

            newRect.SetTextSegment(textSegmentChild);
            newRect.Select();
            Debug.WriteLine("Jumlah Node : " + NumofChild());
        }
		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<Cairo.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.FontWeight == Xwt.Drawing.FontWeight.Bold)) {
							isBold = chunkStyle.FontWeight == Xwt.Drawing.FontWeight.Bold;
							rtfText.Append (isBold ? @"\b" : @"\b0");
							appendSpace = true;
						}
						if (isItalic != (chunkStyle.FontStyle == Xwt.Drawing.FontStyle.Italic)) {
							isItalic = chunkStyle.FontStyle == Xwt.Drawing.FontStyle.Italic;
							rtfText.Append (isItalic ? @"\i" : @"\i0");
							appendSpace = true;
						}
						var foreground = style.GetForeground (chunkStyle);
						if (!colorList.Contains (foreground)) 
							colorList.Add (foreground);
						int color = colorList.IndexOf (foreground);
						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 ();
		}
Beispiel #41
0
        /// <summary>
        /// Modifies the text anchor's TextSegments so all of them
        /// overlap with the passed in text segments.  This is used
        /// for instance to clamp a TextAnchor to a set of visible
        /// text segments.  If after trimming the anchor has no more
        /// segments, null is returned instead.  Callers should
        /// assign the result of this method to the anchor they
        /// passed in.
        /// </summary>
        /// <remarks>
        /// Note: This method assumes textSegments is ordered and do not overlap amongs themselves
        ///
        /// The target of the method is to trim this anchor's segments to overlap with the passed in segments.
        /// The loop handles the following three cases -
        /// 1. Current segment is after other segment, the other segment doesn't contribute at all, we move to the next other segment
        /// 2. Current segment is before other segment, no overlap, remove current segment
        /// 3. Current segment starts before other segment, and ends after other segment begins,
        ///    therefore the portion from current's start to other's start should be trimmed
        /// 4. Current segment starts in the middle of other segment, two possibilities
        ///      a. current segment is completely within other segment, the whole segment overlaps
        ///         so we move on to the next current segment
        ///      b. current segment ends after other segment ends, we split current into the
        ///         overlapped portion and the remainder which will be looked at separately
        /// </remarks>
        /// <param name="anchor">the anchor to trim</param>
        /// <param name="textSegments">collection of text segments to intersect with</param>
        internal static TextAnchor TrimToIntersectionWith(TextAnchor anchor, ICollection <TextSegment> textSegments)
        {
            Invariant.Assert(anchor != null, "Anchor must not be null.");
            Invariant.Assert(textSegments != null, "TextSegments must not be null.");

            textSegments = SortTextSegments(textSegments, true);
            TextSegment currentSegment, otherSegment = TextSegment.Null;

            int current = 0;
            IEnumerator <TextSegment> enumerator = textSegments.GetEnumerator();
            bool hasMore = enumerator.MoveNext();

            while (current < anchor._segments.Count && hasMore)
            {
                Invariant.Assert(otherSegment.Equals(TextSegment.Null) || otherSegment.Equals(enumerator.Current) || otherSegment.End.CompareTo(enumerator.Current.Start) <= 0, "TextSegments are overlapping or not ordered.");

                currentSegment = anchor._segments[current];
                otherSegment   = enumerator.Current;

                // Current segment is after other segment, so try the next other segment
                if (currentSegment.Start.CompareTo(otherSegment.End) >= 0)
                {
                    hasMore = enumerator.MoveNext(); // point to the next other
                    continue;                        // Do not increment, we are still on the same current
                }

                // Current segment is before other segment, no overlap so remove it and continue
                if (currentSegment.End.CompareTo(otherSegment.Start) <= 0)
                {
                    anchor._segments.RemoveAt(current);
                    continue; // Do not increment, it happens implicitly because of the remove
                }

                //
                // We know from here down that there is some overlap.
                //

                // Current starts before the other segment and ends after other segment begins, the first portion of current segment doesn't overlap so we remove it
                if (currentSegment.Start.CompareTo(otherSegment.Start) < 0)
                {
                    anchor._segments[current] = CreateNormalizedSegment(otherSegment.Start, currentSegment.End);
                    continue;  // Do not increment, we need to look at this just created segment
                }
                // Current segment begins in the middle of other segment...
                else
                {
                    // and ends after other segment does, we split current into the portion that is overlapping and the remainder
                    if (currentSegment.End.CompareTo(otherSegment.End) > 0)
                    {
                        anchor._segments[current] = CreateNormalizedSegment(currentSegment.Start, otherSegment.End);
                        // This segment will be the first one looked at next
                        anchor._segments.Insert(current + 1, CreateNormalizedSegment(otherSegment.End, currentSegment.End));
                        hasMore = enumerator.MoveNext();
                    }
                    // and ends at the same place as other segment, its completely overlapping, we move on to the next other
                    else if (currentSegment.End.CompareTo(otherSegment.End) == 0)
                    {
                        hasMore = enumerator.MoveNext();
                    }
                    // and ends within other segment, its completely overlapping, but we aren't done with other so we just continue
                }

                current++;
            }

            // If we finished and there are no more other segments, then any remaining segments
            // in our list must not overlap, so we remove them.
            if (!hasMore && current < anchor._segments.Count)
            {
                anchor._segments.RemoveRange(current, anchor._segments.Count - current);
            }

            if (anchor._segments.Count == 0)
            {
                return(null);
            }
            else
            {
                return(anchor);
            }
        }
		protected override bool OnMotionNotifyEvent (EventMotion evnt)
		{
			RemovePreviewPopupTimeout ();

			if (IsInGrab ()) {
				var yDelta = evnt.Y - grabY;
				MovePosition (grabCenter + yDelta);
			} else {
				UpdatePrelightState (evnt.X, evnt.Y);
			}

			const ModifierType buttonMask = ModifierType.Button1Mask | ModifierType.Button2Mask |
				ModifierType.Button3Mask | ModifierType.Button4Mask | ModifierType.Button5Mask;

			if ((evnt.State & buttonMask & ModifierType.ShiftMask) == ModifierType.ShiftMask) {
				int line = YToLine (evnt.Y);
				
				line = Math.Max (1, line - 2);
				int lastLine = Math.Min (TextEditor.LineCount, line + 5);
				var start = TextEditor.GetLine (line);
				var end = TextEditor.GetLine (lastLine);
				if (start == null || end == null) {
					return base.OnMotionNotifyEvent (evnt);
				}
				var showSegment = new TextSegment (start.Offset, end.Offset + end.Length - start.Offset);
				
				if (previewWindow != null) {
					previewWindow.SetSegment (showSegment, false);
					PositionPreviewWindow ((int)evnt.Y);
				} else {
					var popup = new PreviewPopup (this, showSegment, TextEditor.Allocation.Width * 4 / 7, (int)evnt.Y);
					previewPopupTimeout = GLib.Timeout.Add (450, new GLib.TimeoutHandler (popup.Run));
				}
			} else {
				RemovePreviewPopupTimeout ();
				DestroyPreviewWindow ();
			}
			return base.OnMotionNotifyEvent (evnt);
		}
        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());
        }
            //this runs as a glib idle handler so it can add/remove text editor markers
            //in order to to block the GUI thread, we batch them in UPDATE_COUNT
            bool IdleHandler()
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(false);
                }
                var editor = ext.Editor;

                if (editor == null)
                {
                    return(false);
                }
                if (id == null)
                {
                    foreach (var markerQueue in ext.markers)
                    {
                        foreach (var marker in markerQueue.Value)
                        {
                            editor.RemoveMarker(marker);
                        }
                        PutBackCachedList(markerQueue.Value);
                    }
                    ext.markers.Clear();
                }

                if (id == null)
                {
                    lock (ext.tasks)
                        ext.tasks.Clear();
                    ext.OnTasksUpdated(EventArgs.Empty);
                    return(false);
                }

                //clear the old results out at the same rate we add in the new ones
                for (int i = 0; oldMarkerIndex < oldMarkers.Count && i < UPDATE_COUNT; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    var oldMarker = oldMarkers [oldMarkerIndex++];

                    if (curResult < results.Count && results [curResult].Equals((Result)oldMarker.Tag, oldMarker.Offset))
                    {
                        oldMarker.Tag = results [curResult];
                        newMarkers.Add(oldMarker);
                        curResult++;
                        continue;
                    }
                    editor.RemoveMarker(oldMarker);
                }

                //add in the new markers
                for (int i = 0; i < UPDATE_COUNT; i++)
                {
                    if (curResult >= results.Count)
                    {
                        lock (ext.tasks)
                            ext.tasks [id] = builder.ToImmutable();
                        ext.OnTasksUpdated(EventArgs.Empty);
                        // remove remaining old markers
                        while (oldMarkerIndex < oldMarkers.Count)
                        {
                            editor.RemoveMarker(oldMarkers[oldMarkerIndex]);
                            oldMarkerIndex++;
                        }

                        PutBackCachedList(ext.markers [id]);
                        ext.markers [id] = newMarkers;

                        return(false);
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(false);
                    }
                    var currentResult = results [curResult++];
                    if (currentResult.InspectionMark != IssueMarker.None)
                    {
                        int start = currentResult.Region.Start;
                        int end   = currentResult.Region.End;
                        if (start > end)
                        {
                            continue;
                        }

                        // In case a diagnostic has a 0 length span, force it to 1.
                        if (start == end)
                        {
                            end = end + 1;
                        }

                        var marker = TextMarkerFactory.CreateGenericTextSegmentMarker(editor, GetSegmentMarkerEffect(currentResult.InspectionMark), TextSegment.FromBounds(start, end));
                        marker.Tag       = currentResult;
                        marker.IsVisible = currentResult.Underline;

                        if (currentResult.InspectionMark != IssueMarker.GrayOut)
                        {
                            marker.Color      = GetColor(editor, currentResult);
                            marker.IsVisible &= currentResult.Level != DiagnosticSeverity.Hidden;
                        }
                        editor.AddMarker(marker);
                        newMarkers.Add(marker);
                    }
                    builder.Add(new QuickTask(currentResult.Message, currentResult.Region.Start, currentResult.Level));
                }
                return(true);
            }
Beispiel #45
0
 public int GetLength(TextSegment segment)
 {
     return((int)map [(int)segment].Length);
 }
Beispiel #46
0
 public string DocumentGetText(TextSegment segment)
 {
     throw new NotImplementedException();
 }
		public SearchInSelectionMarker (TextSegment textSegment) : base (textSegment)
		{
		}
Beispiel #48
0
 public ResultMarker(Result result, TextSegment segment) : base("", segment)
 {
     this.result = result;
 }
		TextSegment GetFirstSearchResult (int startOffset, int endOffset)
		{
			if (startOffset < endOffset && this.selectedRegions.Count > 0) {
				var region = new TextSegment (startOffset, endOffset - startOffset);
				int min = 0;
				int max = selectedRegions.Count - 1;
				do {
					int mid = (min + max) / 2;
					TextSegment segment = selectedRegions [mid];
					if (segment.Contains (startOffset) || segment.Contains (endOffset) || region.Contains (segment)) {
						if (mid == 0)
							return segment;
						TextSegment prevSegment = selectedRegions [mid - 1];
						if (!(prevSegment.Contains (startOffset) || prevSegment.Contains (endOffset) || region.Contains (prevSegment)))
							return segment;
						max = mid - 1;
						continue;
					}

					if (segment.Offset < endOffset) {
						min = mid + 1;
					} else {
						max = mid - 1;
					}

				} while (min <= max);
			}
			return TextSegment.Invalid;
		}
Beispiel #50
0
 public GrayOutMarker(Result result, TextSegment segment) : base(result, segment)
 {
 }
Beispiel #51
0
		public void Rename (ISymbol symbol)
		{

			var solution = IdeApp.ProjectOperations.CurrentSelectedSolution;
			var ws = TypeSystemService.GetWorkspace (solution);

			var currentSolution = ws.CurrentSolution;
			var newSolution = Renamer.RenameSymbolAsync (currentSolution, symbol, "_" + symbol.Name + "_", ws.Options).Result;
			var projectChanges = currentSolution.GetChanges (newSolution).GetProjectChanges ().ToList ();

			if (projectChanges.Count != 1) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}

			var projectChange = projectChanges [0];
			var changes = projectChange.GetChangedDocuments ().ToList ();
			if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType) {
				using (var dlg = new RenameItemDialog (symbol, this))
					MessageService.ShowCustomDialog (dlg);
				return;
			}
			var doc = IdeApp.Workbench.ActiveDocument;
			var editor = doc.Editor;
			
			var links = new List<TextLink> ();
			var link = new TextLink ("name");

			var cd = changes [0];
			var oldDoc = projectChange.OldProject.GetDocument (cd);
			var newDoc = projectChange.NewProject.GetDocument (cd);
			var oldVersion = editor.Version;
			foreach (var textChange in oldDoc.GetTextChangesAsync (newDoc).Result) {
				var segment = new TextSegment (textChange.Span.Start, textChange.Span.Length);
				if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset) {
					link.Links.Insert (0, segment); 
				} else {
					link.AddLink (segment);
				}
			}
			
			links.Add (link);
			editor.StartTextLinkMode (new TextLinkModeOptions (links, args => {
				if (!args.Success)
					return;

				var version = editor.Version;
				var span = symbol.Locations.First ().SourceSpan;
				var newName = link.CurrentText;
				var textChanges = version.GetChangesTo (oldVersion).ToList ();
				foreach (var v in textChanges) {
					editor.ReplaceText (v.Offset, v.RemovalLength, v.InsertedText);
				}
				var parsedDocument = doc.UpdateParseDocument ().Result;
				if (parsedDocument == null) {
					Rollback (editor, textChanges);
					return;
				}
				var model = parsedDocument.GetAst<SemanticModel> ();
				if (model == null) {
					Rollback (editor, textChanges);
					return;
				}
				var node = model.SyntaxTree.GetRoot ().FindNode (span);
				if (node == null) {
					Rollback (editor, textChanges);
					return;
				}
				var sym = model.GetDeclaredSymbol (node);
				if (sym == null) {
					Rollback (editor, textChanges);
					return;
				}
				if (!Rename (sym, newName))
					Rollback (editor, textChanges);
			}));
		}
Beispiel #52
0
        /// <summary>
        /// 替换单个占位符(图片)
        /// </summary>
        /// <param name="paragraph"></param>
        /// <param name="replace"></param>
        private static void ReplacePictureInRun(XWPFParagraph paragraph, Models.Word.ReplacementBasic replace)
        {
            if (replace == null)
            {
                return;
            }
            var picList = replace.Pictures;

            if (picList == null || picList.Count() == 0)
            {
                return;
            }
            TextSegment ts = paragraph.SearchText(replace.Placeholder, new PositionInParagraph());

            if (ts == null)
            {
                return;
            }

            var beginIndex = ts.BeginRun;
            var endIndex   = ts.EndRun;
            var runs       = paragraph.Runs;
            var begin_run  = runs[beginIndex];

            //再beginrun的位置插入图片
            foreach (var picture in picList)
            {
                var pictureData = picture.PictureData;
                if (pictureData == null || pictureData.Length == 0)
                {
                    try
                    {
                        pictureData = File.OpenRead(picture.PictureUrl);
                    }
                    catch (Exception)
                    {
                    }
                }

                if (pictureData == null || pictureData.Length == 0)
                {
                    continue;
                }

                int height = (int)(Math.Ceiling(picture.Height * NPOI_PICTURE_LENGTH_EVERY_CM));
                int width  = (int)(Math.Ceiling(picture.Width * NPOI_PICTURE_LENGTH_EVERY_CM));
                begin_run.AddPicture(pictureData, picture.PictureType.GetHashCode(), picture.FileName, width, height);

                NPOI.OpenXmlFormats.Dml.WordProcessing.CT_Inline inline = begin_run.GetCTR().GetDrawingList()[0].inline[0];
                inline.docPr.id = 1;

                pictureData.Dispose();
            }
            //然后清空所有run
            for (int i = beginIndex; i <= endIndex; i++)
            {
                runs[i].SetText("", 0);
            }

            //利用递归处理同一个占位符
            ReplacePictureInRun(paragraph, replace);
        }
Beispiel #53
0
        /// <summary>
        /// Don't use this unless you're implementing ICodeTemplateWidget. Use Insert instead.
        /// </summary>
        public TemplateResult InsertTemplateContents(TextEditor editor, DocumentContext context)
        {
            var data   = editor;
            int offset = data.CaretOffset;
//			string leadingWhiteSpace = GetLeadingWhiteSpace (editor, editor.CursorLine);

            var templateCtx = new TemplateContext {
                Template        = this,
                DocumentContext = context,
                Editor          = editor,
                //ParsedDocument = context.ParsedDocument != null ? context.ParsedDocument.ParsedFile : null,
                InsertPosition = data.CaretLocation,
                InsertOffset   = data.CaretOffset,
                LineIndent     = data.GetLineIndent(data.CaretLocation.Line),
                TemplateCode   = Code
            };

            if (data.IsSomethingSelected)
            {
                int start = data.SelectionRange.Offset;
                while (Char.IsWhiteSpace(data.GetCharAt(start)))
                {
                    start++;
                }
                int end = data.SelectionRange.EndOffset;
                while (start < end && Char.IsWhiteSpace(data.GetCharAt(end - 1)))
                {
                    end--;
                }
                templateCtx.LineIndent   = data.GetLineIndent(data.OffsetToLineNumber(start));
                templateCtx.SelectedText = start < end?RemoveIndent(data.GetTextBetween(start, end), templateCtx.LineIndent) : "";

                data.RemoveText(start, end - start);
                offset = start;
            }
            else
            {
                string word = GetTemplateShortcutBeforeCaret(data).Trim();
                if (word.Length > 0)
                {
                    offset = DeleteTemplateShortcutBeforeCaret(data);
                }
            }

            TemplateResult template = FillVariables(templateCtx);

            template.InsertPosition = offset;
            editor.InsertText(offset, template.Code);

            int newoffset;

            if (template.CaretEndOffset >= 0)
            {
                newoffset = offset + template.CaretEndOffset;
            }
            else
            {
                newoffset = offset + template.Code.Length;
            }

            editor.CaretLocation = editor.OffsetToLocation(newoffset);
            editor.FixVirtualIndentation();

            var prettyPrinter = CodeFormatterService.GetFormatter(data.MimeType);

            if (prettyPrinter != null && prettyPrinter.SupportsOnTheFlyFormatting)
            {
                int endOffset  = template.InsertPosition + template.Code.Length;
                var oldVersion = data.Version;

                try {
                    prettyPrinter.OnTheFlyFormat(editor, context, TextSegment.FromBounds(template.InsertPosition, editor.CaretOffset));
                    endOffset = oldVersion.MoveOffsetTo(data.Version, endOffset);
                    if (editor.CaretOffset < endOffset)
                    {
                        prettyPrinter.OnTheFlyFormat(editor, context, TextSegment.FromBounds(editor.CaretOffset, endOffset));
                    }
                } catch (Exception e) {
                    LoggingService.LogInternalError(e);
                }
                foreach (var textLink in template.TextLinks)
                {
                    for (int i = 0; i < textLink.Links.Count; i++)
                    {
                        var segment          = textLink.Links [i];
                        var translatedOffset = segment.Offset;
                        foreach (var args in oldVersion.GetChangesTo(data.Version))
                        {
                            foreach (var change in args.TextChanges)
                            {
                                if (change.Offset > template.InsertPosition + segment.Offset)
                                {
                                    break;
                                }
                                if (change.Offset + change.RemovalLength < template.InsertPosition + segment.Offset)
                                {
                                    translatedOffset += change.InsertionLength - change.RemovalLength;
                                }
                                else
                                {
                                    translatedOffset += GetDeltaInsideChange(change.InsertedText, change.RemovedText, template.InsertPosition + segment.Offset - change.Offset);
                                }
                            }
                        }
                        textLink.Links [i] = new TextSegment(translatedOffset, segment.Length);
                    }
                }
            }
            return(template);
        }
Beispiel #54
0
 public void AddMap(TextSegment segment, int length)
 {
     this.map[(int)segment] = new Range(this.GetStart(segment), (uint)length);
 }
Beispiel #55
0
		public GenericUnderlineMarker (TextSegment segment, MonoDevelop.Ide.Editor.TextSegmentMarkerEffect effect) : base ("", segment)
		{
			this.effect = effect;
		}
            //this runs as a glib idle handler so it can add/remove text editor markers
            //in order to to block the GUI thread, we batch them in UPDATE_COUNT
            bool IdleHandler()
            {
                try {
                    var editor = ext.Editor;
                    if (editor == null)
                    {
                        return(false);
                    }
                    if (id == null)
                    {
                        ext.RemoveAllMarkers();
                        lock (ext.tasks)
                            ext.tasks.Clear();
                        ext.OnTasksUpdated(EventArgs.Empty);
                        return(false);
                    }

                    if (cancellationToken.IsCancellationRequested)
                    {
                        FinishUpdateRun();
                        return(false);
                    }

                    //clear the old results out at the same rate we add in the new ones
                    if (oldMarkers != null)
                    {
                        for (int i = 0; oldMarkerIndex < oldMarkers.Count && i < UPDATE_COUNT; i++)
                        {
                            var oldMarker = oldMarkers [oldMarkerIndex++];

                            var oldResult = (Result)oldMarker.Tag;
                            if (oldResult != null && curResult < results.Count)
                            {
                                Result currentResult = results [curResult];
                                if (currentResult.Equals(oldResult, oldMarker.Offset))
                                {
                                    oldMarker.Tag = currentResult;
                                    newMarkers.Add(oldMarker);
                                    if (oldResult.QuickTask != null)
                                    {
                                        currentResult.QuickTask = oldResult.QuickTask;
                                        builder.Add(currentResult.QuickTask);
                                    }
                                    curResult++;
                                    continue;
                                }
                            }
                            editor.RemoveMarker(oldMarker);
                        }
                    }

                    //add in the new markers
                    for (int i = 0; i < UPDATE_COUNT; i++)
                    {
                        if (curResult >= results.Count)
                        {
                            FinishUpdateRun();
                            return(false);
                        }
                        var currentResult = results [curResult++];
                        if (currentResult.InspectionMark != IssueMarker.None)
                        {
                            int start = currentResult.Region.Start;
                            int end   = currentResult.Region.End;
                            if (start > end)
                            {
                                continue;
                            }

                            // In case a diagnostic has a 0 length span, force it to 1.
                            if (start == end)
                            {
                                end = end + 1;
                            }

                            var marker = TextMarkerFactory.CreateGenericTextSegmentMarker(editor, GetSegmentMarkerEffect(currentResult.InspectionMark), TextSegment.FromBounds(start, end));
                            marker.Tag       = currentResult;
                            marker.IsVisible = currentResult.Underline;

                            if (currentResult.InspectionMark != IssueMarker.GrayOut)
                            {
                                marker.Color      = GetColor(editor, currentResult);
                                marker.IsVisible &= currentResult.Level != DiagnosticSeverity.Hidden;
                            }
                            editor.AddMarker(marker);
                            newMarkers.Add(marker);
                        }
                        builder.Add(currentResult.QuickTask = new QuickTask(currentResult.Message, currentResult.Region.Start, currentResult.Level));
                    }
                    return(true);
                } catch (Exception ex) {
                    LoggingService.LogInternalError("Error while ResutsUpdater.IdleHandler", ex);
                    return(false);
                }
            }
Beispiel #57
0
		public bool Contains (TextSegment segment)
		{
			return Offset <= segment.Offset && segment.EndOffset <= EndOffsetIncludingDelimiter;
		}
Beispiel #58
0
            public Task <HighlightedLine> GetColoredSegments(ITextSource text, int startOffset, int length)
            {
                if (ContextStack.IsEmpty)
                {
                    return(Task.FromResult(new HighlightedLine(new TextSegment(startOffset, length), new [] { new ColoredSegment(0, length, ScopeStack.Empty) })));
                }
                SyntaxContext        currentContext = null;
                List <SyntaxContext> lastContexts   = new List <SyntaxContext> ();
                Match       match              = null;
                SyntaxMatch curMatch           = null;
                var         segments           = new List <ColoredSegment> ();
                int         offset             = 0;
                int         curSegmentOffset   = 0;
                int         endOffset          = offset + length;
                int         lastMatch          = -1;
                var         highlightedSegment = new TextSegment(startOffset, length);
                string      lineText           = text.GetTextAt(startOffset, length);
                var         initialState       = state.Clone();
                int         timeoutOccursAt;

                unchecked {
                    timeoutOccursAt = Environment.TickCount + (int)matchTimeout.TotalMilliseconds;
                }
restart:
                if (lastMatch == offset)
                {
                    if (lastContexts.Contains(currentContext))
                    {
                        offset++;
                        length--;
                    }
                    else
                    {
                        lastContexts.Add(currentContext);
                    }
                }
                else
                {
                    lastContexts.Clear();
                    lastContexts.Add(currentContext);
                }
                if (offset >= lineText.Length)
                {
                    goto end;
                }
                lastMatch      = offset;
                currentContext = ContextStack.Peek();
                match          = null;
                curMatch       = null;
                foreach (var m in currentContext.Matches)
                {
                    if (m.GotTimeout)
                    {
                        continue;
                    }
                    var r = m.GetRegex();
                    if (r == null)
                    {
                        continue;
                    }
                    try {
                        Match possibleMatch;
                        if (r.pattern == "(?<=\\})" && offset > 0)                           // HACK to fix typescript highlighting.
                        {
                            possibleMatch = r.Match(lineText, offset - 1, length, matchTimeout);
                        }
                        else
                        {
                            possibleMatch = r.Match(lineText, offset, length, matchTimeout);
                        }
                        if (possibleMatch.Success)
                        {
                            if (match == null || possibleMatch.Index < match.Index)
                            {
                                match    = possibleMatch;
                                curMatch = m;
                                // Console.WriteLine (match.Index + " possible match : " + m + "/" + possibleMatch.Index + "-" + possibleMatch.Length);
                            }
                            else
                            {
                                // Console.WriteLine (match.Index + " skip match : " + m + "/" + possibleMatch.Index + "-" + possibleMatch.Length);
                            }
                        }
                        else
                        {
                            // Console.WriteLine ("fail match : " + m);
                        }
                    } catch (RegexMatchTimeoutException) {
                        LoggingService.LogWarning("Warning: Regex " + m.Match + " timed out on line:" + text.GetTextAt(offset, length));
                        m.GotTimeout = true;
                        continue;
                    }
                }
                if (length <= 0 && curMatch == null)
                {
                    goto end;
                }

                if (Environment.TickCount >= timeoutOccursAt)
                {
                    curMatch.GotTimeout = true;
                    goto end;
                }

                if (match != null)
                {
                    // Console.WriteLine (match.Index + " taken match : " + curMatch + "/" + match.Index + "-" + match.Length);
                    var matchEndOffset = match.Index + match.Length;
                    if (curSegmentOffset < match.Index && match.Length > 0)
                    {
                        segments.Add(new ColoredSegment(curSegmentOffset, match.Index - curSegmentOffset, ScopeStack));
                        curSegmentOffset = match.Index;
                    }
                    if (curMatch.Pop)
                    {
                        PopMetaContentScopeStack(currentContext, curMatch);
                    }

                    PushScopeStack(curMatch.Scope);

                    if (curMatch.Captures.Groups.Count > 0)
                    {
                        for (int i = 0; i < curMatch.Captures.Groups.Count; ++i)
                        {
                            var capture = curMatch.Captures.Groups[i];
                            var grp     = match.Groups [capture.Item1];
                            if (grp == null || grp.Length == 0)
                            {
                                continue;
                            }
                            if (curSegmentOffset < grp.Index)
                            {
                                ReplaceSegment(segments, new ColoredSegment(curSegmentOffset, grp.Index - curSegmentOffset, ScopeStack));
                            }
                            ReplaceSegment(segments, new ColoredSegment(grp.Index, grp.Length, ScopeStack.Push(capture.Item2)));
                            curSegmentOffset = Math.Max(curSegmentOffset, grp.Index + grp.Length);
                        }
                    }

                    if (curMatch.Captures.NamedGroups.Count > 0)
                    {
                        for (int i = 0; i < curMatch.Captures.NamedGroups.Count; ++i)
                        {
                            var capture = curMatch.Captures.NamedGroups[i];
                            var grp     = match.Groups [capture.Item1];
                            if (grp == null || grp.Length == 0)
                            {
                                continue;
                            }
                            if (curSegmentOffset < grp.Index)
                            {
                                ReplaceSegment(segments, new ColoredSegment(curSegmentOffset, grp.Index - curSegmentOffset, ScopeStack));
                            }
                            ReplaceSegment(segments, new ColoredSegment(grp.Index, grp.Length, ScopeStack.Push(capture.Item2)));
                            curSegmentOffset = grp.Index + grp.Length;
                        }
                    }

                    if (curMatch.Scope.Count > 0 && curSegmentOffset < matchEndOffset && match.Length > 0)
                    {
                        segments.Add(new ColoredSegment(curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
                        curSegmentOffset = matchEndOffset;
                    }

                    if (curMatch.Pop)
                    {
                        if (matchEndOffset - curSegmentOffset > 0)
                        {
                            segments.Add(new ColoredSegment(curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
                        }
                        //if (curMatch.Scope != null)
                        //	scopeStack = scopeStack.Pop ();
                        PopStack(currentContext, curMatch);
                        curSegmentOffset = matchEndOffset;
                    }
                    else if (curMatch.Set != null)
                    {
                        // if (matchEndOffset - curSegmentOffset > 0)
                        //	segments.Add (new ColoredSegment (curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
                        //if (curMatch.Scope != null)
                        //	scopeStack = scopeStack.Pop ();
                        PopMetaContentScopeStack(currentContext, curMatch);
                        PopStack(currentContext, curMatch);
                        //curSegmentOffset = matchEndOffset;
                        var nextContexts = curMatch.Set.GetContexts(currentContext);
                        PushStack(curMatch, nextContexts);
                        goto skip;
                    }
                    else if (curMatch.Push != null)
                    {
                        var nextContexts = curMatch.Push.GetContexts(currentContext);
                        PushStack(curMatch, nextContexts);
                    }
                    else
                    {
                        if (curMatch.Scope.Count > 0)
                        {
                            for (int i = 0; i < curMatch.Scope.Count; i++)
                            {
                                ScopeStack = ScopeStack.Pop();
                            }
                        }
                    }

                    if (curSegmentOffset < matchEndOffset && match.Length > 0)
                    {
                        segments.Add(new ColoredSegment(curSegmentOffset, matchEndOffset - curSegmentOffset, ScopeStack));
                        curSegmentOffset = matchEndOffset;
                    }
skip:
                    length -= curSegmentOffset - offset;
                    offset  = curSegmentOffset;
                    goto restart;
                }

end:
                if (endOffset - curSegmentOffset > 0)
                {
                    segments.Add(new ColoredSegment(curSegmentOffset, endOffset - curSegmentOffset, ScopeStack));
                }

                return(Task.FromResult(new HighlightedLine(highlightedSegment, segments)
                {
                    IsContinuedBeyondLineEnd = !initialState.Equals(state)
                }));
            }
			public PreviewPopup (QuickTaskOverviewMode strip, TextSegment segment, int w, int y)
			{
				this.strip = strip;
				this.segment = segment;
				this.w = w;
				this.y = y;
			}
Beispiel #60
0
 void MoveToRVA(TextSegment segment)
 {
     MoveToRVA(text, text_map.GetRVA(segment));
 }