This class is the main class of the text model. Basically, it is a System.Text.StringBuilder with events.
Thread safety:

However, there is a single method that is thread-safe: CreateSnapshot() (and its overloads).

Inheritance: ITextSource, INotifyPropertyChanged
		public void SetUpFixture()
		{
			AvalonEdit.TextEditor textEditor = new AvalonEdit.TextEditor();
			document = textEditor.Document;
			textEditor.Text = GetTextEditorCode();

			RubyParser parser = new RubyParser();
			ICompilationUnit compilationUnit = parser.Parse(new DefaultProjectContent(), @"test.py", document.Text);

			using (DesignSurface designSurface = new DesignSurface(typeof(UserControl))) {
				IDesignerHost host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
				UserControl userControl = (UserControl)host.RootComponent;			
				userControl.ClientSize = new Size(489, 389);
				
				PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(userControl);
				PropertyDescriptor namePropertyDescriptor = descriptors.Find("Name", false);
				namePropertyDescriptor.SetValue(userControl, "userControl1");
				
				DesignerSerializationManager serializationManager = new DesignerSerializationManager(host);
				using (serializationManager.CreateSession()) {
					AvalonEditDocumentAdapter docAdapter = new AvalonEditDocumentAdapter(document, null);
					RubyDesignerGenerator generator = new RubyDesignerGenerator(new MockTextEditorOptions());
					generator.Merge(host, docAdapter, compilationUnit, serializationManager);
				}
			}
		}
Esempio n. 2
0
		void AddClassMemberBookmarks(IClass c, TextDocument document)
		{
			if (c.IsSynthetic) return;
			if (!c.Region.IsEmpty) {
				bookmarks.Add(new ClassBookmark(c, document));
			}
			foreach (IClass innerClass in c.InnerClasses) {
				AddClassMemberBookmarks(innerClass, document);
			}
			foreach (IMethod m in c.Methods) {
				if (m.Region.IsEmpty || m.IsSynthetic) continue;
				bookmarks.Add(new ClassMemberBookmark(m, document));
			}
			foreach (IProperty p in c.Properties) {
				if (p.Region.IsEmpty || p.IsSynthetic) continue;
				bookmarks.Add(new ClassMemberBookmark(p, document));
			}
			foreach (IField f in c.Fields) {
				if (f.Region.IsEmpty || f.IsSynthetic) continue;
				bookmarks.Add(new ClassMemberBookmark(f, document));
			}
			foreach (IEvent e in c.Events) {
				if (e.Region.IsEmpty || e.IsSynthetic) continue;
				bookmarks.Add(new ClassMemberBookmark(e, document));
			}
		}
		public void Initialize(IDocument document)
		{
			if (this.document == null) {
				this.document = document;
				this.textDocument = (TextDocument)document.GetService(typeof(TextDocument));
				this.changeList = new CompressingTreeList<LineChangeInfo>((x, y) => x.Equals(y));
			}
			
			var fileName = ((ITextEditor)document.GetService(typeof(ITextEditor))).FileName;
			
			InitializeBaseDocument();
			if (watcher != null)
				watcher.Dispose();
			
			if (usedProvider != null)
				watcher = usedProvider.WatchBaseVersionChanges(fileName, HandleBaseVersionChanges);
			
			SetupInitialFileState(fileName != currentFileName);
			currentFileName = fileName;
			
			if (!this.textDocument.LineTrackers.Contains(this)) {
				this.textDocument.LineTrackers.Add(this);
				this.textDocument.UndoStack.PropertyChanged += UndoStackPropertyChanged;
			}
		}
        protected override void Initialize()
        {
            base.Initialize();

            // Duplicate the text so it is more easily accessible from a different thread
            mirroredText = new Rope <char>(Asset.TextAccessor.Get());

            // Text document and container needs to be owned by the UI thread
            TextContainer = Dispatcher.Invoke(() =>
            {
                // Load initial text from asset and create a text document
                var textDocument = new TextDocument(Asset.TextAccessor.Get());
                textDocument.UndoStack.PropertyChanged += UndoStackOnPropertyChanged;

                // Replace the text accessor with one using custom save logic
                Asset.TextAccessor = new ScriptTextAccessor(this);

                textDocument.Changed += TextDocumentOnChanged;

                return(new AvalonEditTextContainer(textDocument));
            });

            // Track document
            TrackDocument();
        }
Esempio n. 5
0
		public HeightTree(TextDocument document, double defaultLineHeight)
		{
			this.document = document;
			weakLineTracker = WeakLineTracker.Register(document, this);
			this.DefaultLineHeight = defaultLineHeight;
			RebuildDocument();
		}
Esempio n. 6
0
		/// <summary>
		/// Create <see cref="NewFolding"/>s for the specified document.
		/// </summary>
		public IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, XmlReader reader, out int firstErrorOffset)
		{
			Stack<XmlFoldStart> stack = new Stack<XmlFoldStart>();
			List<NewFolding> foldMarkers = new List<NewFolding>();
			try {
				while (reader.Read()) {
					switch (reader.NodeType) {
						case XmlNodeType.Element:
							if (!reader.IsEmptyElement) {
								XmlFoldStart newFoldStart = CreateElementFoldStart(document, reader);
								stack.Push(newFoldStart);
							}
							break;
							
						case XmlNodeType.EndElement:
							XmlFoldStart foldStart = stack.Pop();
							CreateElementFold(document, foldMarkers, reader, foldStart);
							break;
							
						case XmlNodeType.Comment:
							CreateCommentFold(document, foldMarkers, reader);
							break;
					}
				}
				firstErrorOffset = -1;
			} catch (XmlException ex) {
				// ignore errors
				firstErrorOffset = document.GetOffset(ex.LineNumber, ex.LinePosition);
			}
			foldMarkers.Sort((a,b) => a.StartOffset.CompareTo(b.StartOffset));
			return foldMarkers;
		}
Esempio n. 7
0
        public override int GetFirstInterestedOffset(int startOffset)
        {
            ICSharpCode.AvalonEdit.Document.TextDocument document = CurrentContext.Document;
            int firstOffset = CurrentContext.VisualLine.FirstDocumentLine.Offset;

            if (firstOffset == startOffset)
            {
                return(firstOffset);
            }
            else
            {
                return(-1);
            }

            int endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;

            for (int i = startOffset; i < endOffset; i++)
            {
                char c = document.GetCharAt(i);
                if (c == ':')
                {
                    return(i + 1);
                }
            }
            return(-1);
        }
Esempio n. 8
0
        /// <summary>
        /// Creates a HTML fragment from a part of a document.
        /// </summary>
        /// <param name="document">The document to create HTML from.</param>
        /// <param name="highlighter">The highlighter used to highlight the document. <c>null</c> is valid and will create HTML without any highlighting.</param>
        /// <param name="segment">The part of the document to create HTML for. You can pass <c>null</c> to create HTML for the whole document.</param>
        /// <param name="options">The options for the HTML creation.</param>
        /// <returns>HTML code for the document part.</returns>
        public static string CreateHtmlFragment(TextDocument document, IHighlighter highlighter, ISegment segment, HtmlOptions options)
        {
            if (document == null)
                throw new ArgumentNullException("document");
            if (options == null)
                throw new ArgumentNullException("options");
            if (highlighter != null && highlighter.Document != document)
                throw new ArgumentException("Highlighter does not belong to the specified document.");
            if (segment == null)
                segment = new SimpleSegment(0, document.TextLength);

            StringBuilder html = new StringBuilder();
            int segmentEndOffset = segment.EndOffset;
            DocumentLine line = document.GetLineByOffset(segment.Offset);
            while (line != null && line.Offset < segmentEndOffset) {
                HighlightedLine highlightedLine;
                if (highlighter != null)
                    highlightedLine = highlighter.HighlightLine(line.LineNumber);
                else
                    highlightedLine = new HighlightedLine(document, line);
                SimpleSegment s = segment.GetOverlap(line);
                if (html.Length > 0)
                    html.AppendLine("<br>");
                html.Append(highlightedLine.ToHtml(s.Offset, s.EndOffset, options));
                line = line.NextLine;
            }
            return html.ToString();
        }
        public virtual void IndentLine(TextDocument document, DocumentLine line)
        {
            if(line == null)
                throw new ArgumentNullException("line");

            formatting_strategy.IndentLine(editor, editor.Document.GetLineByNumber(line.LineNumber));
        }
		public void Initialize(IDocument document)
		{
			if (changeList != null && changeList.Any())
				return;
			
			this.document = document;
			this.textDocument = (TextDocument)document.GetService(typeof(TextDocument));
			this.changeList = new CompressingTreeList<LineChangeInfo>((x, y) => x.Equals(y));
			
			Stream baseFileStream = GetBaseVersion();
			
			// TODO : update baseDocument on VCS actions
			if (baseFileStream != null) {
				// ReadAll() is taking care of closing the stream
				baseDocument = DocumentUtilitites.LoadReadOnlyDocumentFromBuffer(new StringTextBuffer(ReadAll(baseFileStream)));
			} else {
				if (baseDocument == null) {
					// if the file is not under subversion, the document is the opened document
					var doc = new TextDocument(textDocument.Text);
					baseDocument = new AvalonEditDocumentAdapter(doc, null);
				}
			}
			
			SetupInitialFileState(false);
			
			this.textDocument.LineTrackers.Add(this);
			this.textDocument.UndoStack.PropertyChanged += UndoStackPropertyChanged;
		}
Esempio n. 11
0
        void AttachEvents()
        {
            document = TextArea.Document;
            if (document != null)
            {
                document.Changing += textArea_Document_Changing;
            }
            // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729
            TextArea.LostKeyboardFocus += TextAreaLostFocus;
            TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged;
            TextArea.DocumentChanged += TextAreaDocumentChanged;
            if (parentWindow != null)
            {
                parentWindow.LocationChanged += parentWindow_LocationChanged;
            }

            // close previous completion windows of same type
            foreach (InputHandler x in TextArea.StackedInputHandlers.OfType<InputHandler>())
            {
                if (x.window.GetType() == GetType())
                    TextArea.PopStackedInputHandler(x);
            }

            myInputHandler = new InputHandler(this);
            TextArea.PushStackedInputHandler(myInputHandler);
        }
Esempio n. 12
0
 public BreakpointMarker(TextMarkerService markerStrategy, Breakpoint bp, TextDocument doc, int line_begin, int line_end)
     : base(markerStrategy, doc, line_begin, line_end)
 {
     this.Breakpoint = bp;
     MarkerType = TextMarkerType.None;
     BackgroundColor = Colors.Red;
 }
Esempio n. 13
0
 public BracketSearchResult SearchBracket(TextDocument document, int offset)
 {
     BracketSearchResult result;
     if (offset > 0)
     {
         var charAt = document.GetCharAt(offset - 1);
         var num = "([{".IndexOf(charAt);
         var num2 = -1;
         if (num > -1)
         {
             num2 = SearchBracketForward(document, offset, "([{"[num], ")]}"[num]);
         }
         num = ")]}".IndexOf(charAt);
         if (num > -1)
         {
             num2 = SearchBracketBackward(document, offset - 2, "([{"[num], ")]}"[num]);
         }
         if (num2 > -1)
         {
             result = new BracketSearchResult(Math.Min(offset - 1, num2), 1, Math.Max(offset - 1, num2), 1);
             return result;
         }
     }
     result = null;
     return result;
 }
		public void SetUpFixture()
		{
			string python = "class Test:\r\n" +
							"\tdef foo(self):\r\n" +
							"\t\tpass";
			
			DefaultProjectContent projectContent = new DefaultProjectContent();
			PythonParser parser = new PythonParser();
			compilationUnit = parser.Parse(projectContent, @"C:\test.py", python);			
			if (compilationUnit.Classes.Count > 0) {
				c = compilationUnit.Classes[0];
				if (c.Methods.Count > 0) {
					method = c.Methods[0];
				}
				
				TextArea textArea = new TextArea();
				document = new TextDocument();
				textArea.Document = document;
				textArea.Document.Text = python;
				
				ParserFoldingStrategy foldingStrategy = new ParserFoldingStrategy(textArea);
				
				ParseInformation parseInfo = new ParseInformation(compilationUnit);
				foldingStrategy.UpdateFoldings(parseInfo);
				List<FoldingSection> folds = new List<FoldingSection>(foldingStrategy.FoldingManager.AllFoldings);
				
				if (folds.Count > 0) {
					classFold = folds[0];
				}
				if (folds.Count > 1) {
					methodFold = folds[1];
				}
			}
		}
Esempio n. 15
0
        public DocumentViewModel(
            IDialogService dialogService,
            IWindowManager windowManager,
            ISiteContextGenerator siteContextGenerator,
            Func<string, IMetaWeblogService> getMetaWeblog,
            ISettingsProvider settingsProvider,
            IDocumentParser documentParser)
        {
            this.dialogService = dialogService;
            this.windowManager = windowManager;
            this.siteContextGenerator = siteContextGenerator;
            this.getMetaWeblog = getMetaWeblog;
            this.settingsProvider = settingsProvider;
            this.documentParser = documentParser;

            FontSize = GetFontSize();

            title = "New Document";
            Original = "";
            Document = new TextDocument();
            Post = new Post();
            timer = new DispatcherTimer();
            timer.Tick += TimerTick;
            timer.Interval = delay;
        }
			public LineAdapter(TextDocument document, DocumentLine line)
			{
				Debug.Assert(document != null);
				Debug.Assert(line != null);
				this.document = document;
				this.line = line;
			}
Esempio n. 17
0
        public void UpdateFoldings(FoldingManager manager, ICSharpCode.AvalonEdit.Document.TextDocument document)
        {
            int firstErrorOffset;
            IEnumerable <NewFolding> newFoldings = CreateNewFoldings(document, out firstErrorOffset);

            manager.UpdateFoldings(newFoldings, firstErrorOffset);
        }
Esempio n. 18
0
		public void SetUpFixture()
		{
			resourceWriter = new MockResourceWriter();
			resourceService = new MockResourceService();
			resourceService.SetResourceWriter(resourceWriter);
			
			AvalonEdit.TextEditor textEditor = new AvalonEdit.TextEditor();
			document = textEditor.Document;
			textEditor.Text = GetTextEditorCode();
			
			PythonParser parser = new PythonParser();
			ICompilationUnit compilationUnit = parser.Parse(new DefaultProjectContent(), @"test.py", document.Text);

			using (DesignSurface designSurface = new DesignSurface(typeof(Form))) {
				IDesignerHost host = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
				Form form = (Form)host.RootComponent;
				form.ClientSize = new Size(499, 309);

				PropertyDescriptorCollection descriptors = TypeDescriptor.GetProperties(form);
				PropertyDescriptor namePropertyDescriptor = descriptors.Find("Name", false);
				namePropertyDescriptor.SetValue(form, "MainForm");
				
				DesignerSerializationManager serializationManager = new DesignerSerializationManager(host);
				using (serializationManager.CreateSession()) {
					AvalonEditDocumentAdapter adapter = new AvalonEditDocumentAdapter(document, null);
					MockTextEditorOptions options = new MockTextEditorOptions();
					PythonDesignerGenerator generator = new PythonDesignerGenerator(options);
					generator.Merge(host, adapter, compilationUnit, serializationManager);
				}
			}
		}
Esempio n. 19
0
        /// <summary>
        /// Gets the first offset >= startOffset where the generator wants to construct
        /// an element.
        /// Return -1 to signal no interest.
        /// </summary>
        public override int GetFirstInterestedOffset(int startOffset)
        {
            if (LineOfInterest <= 0)
            {
                return(-1);
            }
            ICSharpCode.AvalonEdit.Document.TextDocument document = CurrentContext.Document;
            int start = document.GetLineByNumber(LineOfInterest).Offset;

            //            int length = document.GetLineByOffset(startOffset).Length;
            //            string text = document.Text.Substring(start, length);

            if (start == startOffset)
            {
                return(start);
            }
            else
            {
                //    DocumentLine nextLine = document.GetLineByOffset(startOffset).NextLine;

                //  if (nextLine == null)
                return(-1);

                //    return nextLine.Offset;
            }

            //int firstOffset = CurrentContext.VisualLine.FirstDocumentLine.Offset;
            ////Match m = FindMatch(startOffset);
            //if (firstOffset >= startOffset)
            //    return firstOffset;
            //else return -1;
        }
Esempio n. 20
0
		internal DocumentLine(TextDocument document)
		{
			#if DEBUG
			Debug.Assert(document != null);
			this.document = document;
			#endif
		}
Esempio n. 21
0
 public void IndentLine(TextDocument document, DocumentLine line)
 {
     if (document == null || line == null)
     {
         return;
     }
     DocumentLine previousLine = line.PreviousLine;
     if (previousLine != null)
     {
         ISegment indentationSegment = TextUtilities.GetWhitespaceAfter(document, previousLine.Offset);
         string indentation = document.GetText(indentationSegment);
         if (Program.OptionsObject.Editor_AgressiveIndentation)
         {
             string currentLineTextTrimmed = (document.GetText(line)).Trim();
             string lastLineTextTrimmed = (document.GetText(previousLine)).Trim();
             char currentLineFirstNonWhitespaceChar = ' ';
             if (currentLineTextTrimmed.Length > 0)
             {
                 currentLineFirstNonWhitespaceChar = currentLineTextTrimmed[0];
             }
             char lastLineLastNonWhitespaceChar = ' ';
             if (lastLineTextTrimmed.Length > 0)
             {
                 lastLineLastNonWhitespaceChar = lastLineTextTrimmed[lastLineTextTrimmed.Length - 1];
             }
             if (lastLineLastNonWhitespaceChar == '{' && currentLineFirstNonWhitespaceChar != '}')
             {
                 indentation += "\t";
             }
             else if (currentLineFirstNonWhitespaceChar == '}')
             {
                 if (indentation.Length > 0)
                 {
                     indentation = indentation.Substring(0, indentation.Length - 1);
                 }
                 else
                 {
                     indentation = string.Empty;
                 }
             }
             /*if (lastLineTextTrimmed == "{" && currentLineTextTrimmed != "}")
             {
                 indentation += "\t";
             }
             else if (currentLineTextTrimmed == "}")
             {
                 if (indentation.Length > 0)
                 {
                     indentation = indentation.Substring(0, indentation.Length - 1);
                 }
                 else
                 {
                     indentation = string.Empty;
                 }
             }*/
         }
         indentationSegment = TextUtilities.GetWhitespaceAfter(document, line.Offset);
         document.Replace(indentationSegment, indentation);
     }
 }
Esempio n. 22
0
		public static Block ConvertTextDocumentToBlock(TextDocument document, IHighlighter highlighter)
		{
			if (document == null)
				throw new ArgumentNullException("document");
//			Table table = new Table();
//			table.Columns.Add(new TableColumn { Width = GridLength.Auto });
//			table.Columns.Add(new TableColumn { Width = new GridLength(1, GridUnitType.Star) });
//			TableRowGroup trg = new TableRowGroup();
//			table.RowGroups.Add(trg);
			Paragraph p = new Paragraph();
			foreach (DocumentLine line in document.Lines) {
				int lineNumber = line.LineNumber;
//				TableRow row = new TableRow();
//				trg.Rows.Add(row);
//				row.Cells.Add(new TableCell(new Paragraph(new Run(lineNumber.ToString()))) { TextAlignment = TextAlignment.Right });
				HighlightedInlineBuilder inlineBuilder = new HighlightedInlineBuilder(document.GetText(line));
				if (highlighter != null) {
					HighlightedLine highlightedLine = highlighter.HighlightLine(lineNumber);
					int lineStartOffset = line.Offset;
					foreach (HighlightedSection section in highlightedLine.Sections)
						inlineBuilder.SetHighlighting(section.Offset - lineStartOffset, section.Length, section.Color);
				}
//				Paragraph p = new Paragraph();
//				row.Cells.Add(new TableCell(p));
				p.Inlines.AddRange(inlineBuilder.CreateRuns());
				p.Inlines.Add(new LineBreak());
			}
			return p;
		}
Esempio n. 23
0
        public void IndentLine(ICSharpCode.AvalonEdit.Document.TextDocument document, DocumentLine line, bool TakeCaret)
        {
            if (line.PreviousLine == null)
            {
                return;
            }

            if (!DSettings.Instance.EnableSmartIndentation)
            {
                var t = document.GetText(line);
                int c = 0;
                for (; c < t.Length && (t[c] == ' ' || t[c] == '\t'); c++)
                {
                    ;
                }

                RawlyIndentLine(t.Length == 0 ? string.Empty : t.Substring(0, c + 1), document, line);

                return;
            }

            var tr        = document.CreateReader();
            var newIndent = D_Parser.Formatting.Indent.IndentEngineWrapper.CalculateIndent(tr, line.LineNumber, dEditor.Editor.Options.ConvertTabsToSpaces, dEditor.Editor.Options.IndentationSize);

            tr.Close();

            RawlyIndentLine(newIndent, document, line);
        }
 /// <summary>
 /// Creates a new HighlightingColorizer instance.
 /// </summary>
 /// <param name="ruleSet">The root highlighting rule set.</param>
 public PythonConsoleHighlightingColorizer(HighlightingRuleSet ruleSet, TextDocument document)
     : base(ruleSet)
 {
     if (document == null)
         throw new ArgumentNullException("document");
     this.document = document;
 }
 protected override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document)
 {
     string name = null;
     int? startOffset = null;
     int? endOffset = null;
     foreach (var line in document.Lines)
     {
         var text = document.GetText(line);
         var isFunction = _functionRegex.IsMatch(text);
         if (isFunction)
         {
             if (startOffset != null && endOffset != null)
             {
                 yield return new NewFolding { StartOffset = startOffset.Value, EndOffset = endOffset.Value, Name = name, IsDefinition = true };
             }
             name = text;
             startOffset = line.Offset;
             endOffset = null;
             continue;
         }
         if (startOffset == null || string.IsNullOrWhiteSpace(text)) continue;
         var firstChar = text.First(c => !char.IsWhiteSpace(c));
         if (!firstChar.Equals(Gherkin.Comment) && !firstChar.Equals(Gherkin.Tag)) endOffset = line.EndOffset;
     }
     if (startOffset != null && endOffset != null)
     {
         yield return new NewFolding { StartOffset = startOffset.Value, EndOffset = endOffset.Value, Name = name, IsDefinition = true };
     }
 }
Esempio n. 26
0
		/// <summary>
		/// Deregisters the weak line tracker.
		/// </summary>
		public void Deregister()
		{
			if (textDocument != null) {
				textDocument.LineTrackers.Remove(this);
				textDocument = null;
			}
		}
Esempio n. 27
0
		public ClassMemberBookmark(IMember member, TextDocument document)
		{
			this.member = member;
			int lineNr = member.Region.BeginLine;
			if (document != null && lineNr > 0 && lineNr <= document.LineCount)
				this.line = document.GetLineByNumber(lineNr);
		}
		public void SetUpFixture()
		{
			string ruby = "class Test\r\n" +
							"\tdef initialize\r\n" +
							"\t\tputs 'test'\r\n" +
							"\tend\r\n" +
							"end";
			
			DefaultProjectContent projectContent = new DefaultProjectContent();
			RubyParser parser = new RubyParser();
			compilationUnit = parser.Parse(projectContent, @"C:\test.rb", ruby);			
			if (compilationUnit.Classes.Count > 0) {
				c = compilationUnit.Classes[0];
				if (c.Methods.Count > 0) {
					method = c.Methods[0];
				}
				
				TextArea textArea = new TextArea();
				document = new TextDocument();
				textArea.Document = document;
				textArea.Document.Text = ruby;
				
				// Get folds.
				ParserFoldingStrategy foldingStrategy = new ParserFoldingStrategy(textArea);
				
				ParseInformation parseInfo = new ParseInformation(compilationUnit);
				foldingStrategy.UpdateFoldings(parseInfo);
				List<FoldingSection> folds = new List<FoldingSection>(foldingStrategy.FoldingManager.AllFoldings);
			
				if (folds.Count > 1) {
					classFold = folds[0];
					methodFold = folds[1];
				}
			}
		}
Esempio n. 29
0
 public TextMarkerService(TextDocument document)
 {
     if (document == null)
         throw new ArgumentNullException("document");
     this.document = document;
     this.markers = new TextSegmentCollection<TextMarker>(document);
 }
Esempio n. 30
0
        public void RawlyIndentLine(string indentString, ICSharpCode.AvalonEdit.Document.TextDocument document, DocumentLine line)
        {
            if (!_doBeginUpdateManually)
            {
                document.BeginUpdate();
            }

            // 1)
            int prevInd = 0;
            int curOff  = line.Offset;

            if (curOff < document.TextLength)
            {
                char curChar = '\0';
                while (curOff < document.TextLength && ((curChar = document.GetCharAt(curOff)) == ' ' || curChar == '\t'))
                {
                    prevInd++;
                    curOff++;
                }

                document.Remove(line.Offset, prevInd);
            }

            document.Insert(line.Offset, indentString);
            if (!_doBeginUpdateManually)
            {
                document.EndUpdate();
            }
        }
Esempio n. 31
0
		/// <summary>
		/// Creates a new mutable document from the specified text buffer.
		/// </summary>
		/// <remarks>
		/// Use the more efficient <see cref="LoadReadOnlyDocumentFromBuffer"/> if you only need a read-only document.
		/// </remarks>
		public static IDocument LoadDocumentFromBuffer(ITextBuffer buffer)
		{
			if (buffer == null)
				throw new ArgumentNullException("buffer");
			var doc = new TextDocument(GetTextSource(buffer));
			return new AvalonEditDocumentAdapter(doc, null);
		}
		/// <summary>
		/// Creates a new AvalonEditDocumentAdapter instance.
		/// </summary>
		/// <param name="document">The document to wrap.</param>
		/// <param name="parentServiceProvider">The service provider used for GetService calls.</param>
		public AvalonEditDocumentAdapter(TextDocument document, IServiceProvider parentServiceProvider)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			this.document = document;
			this.parentServiceProvider = parentServiceProvider;
		}
Esempio n. 33
0
 public RawData(string name, uint offset, string format, uint address, string value, int length, uint pluginLine)
     : base(name, offset, address, pluginLine)
 {
     _document = new TextDocument(new StringTextSource(value));
     _length = length;
     _format = format;
 }
Esempio n. 34
0
		/// <summary>
		/// Creates a new <see cref="FixedHighlighter"/> for a copy of a portion
		/// of the input document (including the original highlighting).
		/// </summary>
		public static FixedHighlighter CreateView(IHighlighter highlighter, int offset, int endOffset)
		{
			var oldDocument = highlighter.Document;
			// ReadOnlyDocument would be better; but displaying the view in AvalonEdit
			// requires a TextDocument
			var newDocument = new TextDocument(oldDocument.CreateSnapshot(offset, endOffset - offset));
			
			var oldStartLine = oldDocument.GetLineByOffset(offset);
			var oldEndLine = oldDocument.GetLineByOffset(endOffset);
			int oldStartLineNumber = oldStartLine.LineNumber;
			HighlightedLine[] newLines = new HighlightedLine[oldEndLine.LineNumber - oldStartLineNumber + 1];
			highlighter.BeginHighlighting();
			try {
				for (int i = 0; i < newLines.Length; i++) {
					HighlightedLine oldHighlightedLine = highlighter.HighlightLine(oldStartLineNumber + i);
					IDocumentLine newLine = newDocument.GetLineByNumber(1 + i);
					HighlightedLine newHighlightedLine = new HighlightedLine(newDocument, newLine);
					MoveSections(oldHighlightedLine.Sections, -offset, newLine.Offset, newLine.EndOffset, newHighlightedLine.Sections);
					newHighlightedLine.ValidateInvariants();
					newLines[i] = newHighlightedLine;
				}
			} finally {
				highlighter.EndHighlighting();
			}
			return new FixedHighlighter(newDocument, newLines);
		}
 /// <summary>
 /// Creates a new HighlightingColorizer instance.
 /// </summary>
 /// <param name="ruleSet">The root highlighting rule set.</param>
 public PythonConsoleHighlightingColorizer(IHighlightingDefinition highlightingDefinition, TextDocument document)
     : base(new DocumentHighlighter(document, highlightingDefinition  ))
 {
     if (document == null)
         throw new ArgumentNullException("document");
     this.document = document;
 }
		/// <summary>
		/// Reindents a set of lines.
		/// </summary>
		/// <param name="document"></param>
		/// <param name="beginLine"></param>
		/// <param name="endLine"></param>
		public void IndentLines(TextDocument document, int beginLine, int endLine)
		{
			for (var i = beginLine; i <= endLine; i++)
			{
				IndentLine(document, document.GetLineByNumber(i));
			}
		}
Esempio n. 37
0
        public AvalonEditTextDocument(ICSharpCode.AvalonEdit.Document.TextDocument avalonEditTextDocument, Encoding encodingForAlphanumericLiterals, ColumnsLayout columnsLayout)
        {
            // Document source name and text format
            Source = new TextSourceInfo(_avalonEditTextDocument.FileName, encodingForAlphanumericLiterals, columnsLayout);

            _avalonEditTextDocument = avalonEditTextDocument;
            // Listen to all line changes in the editor
            _avalonEditTextDocument.VerifyAccess();
            _weakLineTracker = WeakLineTracker.Register(_avalonEditTextDocument, this);
        }
Esempio n. 38
0
        private Match FindMatch(int startOffset)
        {
            // fetch the end offset of the VisualLine being generated
            int endOffset = CurrentContext.VisualLine.LastDocumentLine.EndOffset;

            ICSharpCode.AvalonEdit.Document.TextDocument document = CurrentContext.Document;
            string relevantText = document.GetText(startOffset, endOffset - startOffset);

            return(imageRegex.Match(relevantText));
        }
Esempio n. 39
0
        private void codeEditor_TextEntered(object sender, TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                ICSharpCode.AvalonEdit.Editing.TextArea      area = (sender as ICSharpCode.AvalonEdit.Editing.TextArea);
                ICSharpCode.AvalonEdit.Document.TextDocument doc  = area.Document;
                int startoff = area.Caret.Offset - 1;
                int off      = area.Caret.Offset - 2;
                while (true)
                {
                    char o = doc.GetCharAt(off);
                    if (!char.IsLetter(o))
                    {
                        break;
                    }
                    if (off == 0)
                    {
                        break;
                    }
                    off--;
                }
                string prevToken = doc.GetText(off, startoff - off);

                // Open code completion after the user has pressed dot:
                completionWindow        = new CompletionWindow(CodeEditor.TextArea);
                completionWindow.Margin = new Thickness(0);
                IList <ICompletionData> data = completionWindow.CompletionList.CompletionData;
                try
                {
                    List <string> items = CompletionDatabase.completionDatabase[prevToken];
                    foreach (string item in items)
                    {
                        data.Add(new CompletionData(item));
                    }
                    completionWindow.Show();
                    completionWindow.Closed += delegate
                    {
                        completionWindow = null;
                    };
                }catch (Exception)
                {
                }
            }
        }
Esempio n. 40
0
        public void RawlyIndentLine(int tabsToInsert, ICSharpCode.AvalonEdit.Document.TextDocument document, DocumentLine line)
        {
            if (!_doBeginUpdateManually)
            {
                document.BeginUpdate();
            }

            /*
             * 1) Remove old indentation
             * 2) Insert new one
             */

            // 1)
            int prevInd = 0;
            int curOff  = line.Offset;

            if (curOff < document.TextLength)
            {
                char curChar = '\0';
                while (curOff < document.TextLength && ((curChar = document.GetCharAt(curOff)) == ' ' || curChar == '\t'))
                {
                    prevInd++;
                    curOff++;
                }

                document.Remove(line.Offset, prevInd);
            }

            // 2)
            string indentString = "";

            for (int i = 0; i < tabsToInsert; i++)
            {
                indentString += dEditor.Editor.Options.IndentationString;
            }

            document.Insert(line.Offset, indentString);
            if (!_doBeginUpdateManually)
            {
                document.EndUpdate();
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Constructs an element at the specified offset.
        /// May return null if no element should be constructed.
        /// </summary>
        public override VisualLineElement ConstructElement(int offset)
        {
            //Match m = FindMatch(offset);
            // check whether there's a match exactly at offset
            //if (m.Success && m.Index == 0) {
            ICSharpCode.AvalonEdit.Document.TextDocument document = CurrentContext.Document;
            int start = document.GetLineByOffset(offset).Offset;

            if (frameworkElement == null)
            {
                return(null);
            }

            if (start == offset)
            {
                DocumentLine documentLine = document.GetLineByOffset(offset);

                int height = (int)frameworkElement.Height;// (int)CurrentContext.VisualLine.Height;

                //            BitmapImage bitmap = bitmapImage;// LoadBitmap(m.Groups[1].Value);
                ////if (bitmap != null) {
                //	Image image = new Image();
                //	image.Source = bitmap;
                //	image.Width = bitmap.PixelWidth;
                //            image.Height = height;// bitmap.PixelHeight;
                //                              // Pass the length of the match to the 'documentLength' parameter
                //                              // of InlineObjectElement.

                var es = new InlineObjectElementExtended(1 /*m.Length*/, frameworkElement);

                //es.obs = documentLine.obs;

                //image.Tag = es;

                //es.Element.MouseDown += Element_MouseDown;

                return(es);
            }
            //}
            return(null);
        }
Esempio n. 42
0
        protected override void OnSave()
        {
            // Important: The constructor StreamWriter(stream) uses UTF-8 encoding without a
            // Byte-Order Mark (BOM). Many tools, such as the DirectX effect compiler (fxc.exe),
            // cannot read files with BOM.
            using (var stream = new FileStream(Uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (var writer = new StreamWriter(stream))
                {
                    _encoding = writer.Encoding;
                    AvalonEditDocument.WriteTextTo(writer);
                }
            }

            // Place marker in Undo stack to mark current state as "original".
            AvalonEditDocument.UndoStack.MarkAsOriginalFile();

            _fileInfo = new FileInfo(Uri.LocalPath);

            BeginInvokeUpdateProperties();
        }
Esempio n. 43
0
        public TextDocument(IEditorService editor, DocumentType documentType)
            : base(editor, documentType)
        {
            // Optional services:
            _searchService     = editor.Services.GetInstance <ISearchService>().WarnIfMissing();
            _propertiesService = editor.Services.GetInstance <IPropertiesService>().WarnIfMissing();

            AvalonEditDocument = new AvalonEditDocument();
            SelectionMarkers   = new TextSegmentCollection <Marker>();
            SearchMarkers      = new TextSegmentCollection <Marker>();
            ErrorMarkers       = new TextSegmentCollection <Marker>();

            InitializeSearch();

            // The UndoStack indicates whether changes were made to the document.
            AvalonEditDocument.UndoStack.PropertyChanged += OnUndoStackChanged;
            AvalonEditDocument.TextChanged += OnTextChanged;

            Editor.ActiveDockTabItemChanged += OnEditorDockTabItemChanged;

            BeginInvokeUpdateProperties();
        }
Esempio n. 44
0
        /// <summary>
        /// Loads the content of a source file in the editor
        /// </summary>
        public TypeCobolEditor(CobolFile sourceFile)
        {
            TextView textView = TextArea.TextView;

            // Default text style
            FontFamily = new FontFamily("Consolas");
            FontSize   = 13;

            // Show line numbers
            ShowLineNumbers = true;

            // Activate search box
            SearchPanel.Install(this);

            // Plug in TypeCobol syntax highlighting
            syntaxHighlighter = new SyntaxHighlighter();
            textView.LineTransformers.Add(syntaxHighlighter);

            // Plug in TypeCobol error marker
            errorMarker = new ErrorMarker(this);
            textView.BackgroundRenderers.Add(errorMarker);
            textView.LineTransformers.Add(errorMarker);

            // Tooltip management
            tooltipManager               = new TooltipManager(this, errorMarker);
            textView.MouseHover         += tooltipManager.MouseHover;
            textView.MouseHoverStopped  += tooltipManager.MouseHoverStopped;
            textView.VisualLinesChanged += tooltipManager.VisualLinesChanged;

            // Initial load of the cobol file if necessary
            if (sourceFile != null)
            {
                Document = new ICSharpCode.AvalonEdit.Document.TextDocument(sourceFile.ReadChars());
            }

            // Wrap the AvalonEdit.Document in a ITextDocument interface
            textDocument = new AvalonEditTextDocument(Document, IBMCodePages.GetDotNetEncodingFromIBMCCSID(1147), ColumnsLayout.CobolReferenceFormat);
        }
Esempio n. 45
0
 public void IndentLines(ICSharpCode.AvalonEdit.Document.TextDocument document, int beginLine, int endLine)
 {
 }
Esempio n. 46
0
 public void IndentLine(ICSharpCode.AvalonEdit.Document.TextDocument document, DocumentLine line)
 {
     IndentLine(document, line, false);
 }
Esempio n. 47
0
 public void SetUp()
 {
     document = new TextDocument();
 }
 public TextAnchorTree(TextDocument document)
 {
     this.document = document;
 }
Esempio n. 49
0
 protected override IHighlighter CreateHighlighter(TextView textView, TextDocument document)
 {
     return(new LinqPadHightlighter(document, this.documentId));
 }
 /// <summary>
 /// Creates a new AnchorSegment that creates new anchors.
 /// </summary>
 public AnchorSegment(TextDocument document, ISegment segment)
     : this(document, ThrowUtil.CheckNotNull(segment, "segment").Offset, segment.Length)
 {
 }
Esempio n. 51
0
        public static string GetWordUnderMouse(ICSharpCode.AvalonEdit.Document.TextDocument document, TextViewPosition position)
        {
            string wordHovered = string.Empty;

            var line   = position.Line;
            var column = position.Column - 1;

            var offset = document.GetOffset(line, column);

            if (offset >= document.TextLength)
            {
                offset--;
            }

            var textAtOffset = document.GetText(offset, 1);

            // Get text backward of the mouse position, until the first space
            while (!string.IsNullOrWhiteSpace(textAtOffset))
            {
                wordHovered = textAtOffset + wordHovered;

                offset--;

                if (offset < 0)
                {
                    break;
                }

                textAtOffset = document.GetText(offset, 1);

                if (textAtOffset == "(" || textAtOffset == ")" || textAtOffset == "<" || textAtOffset == ">" || textAtOffset == "," || textAtOffset == ";")
                {
                    break;
                }
            }

            // Get text forward the mouse position, until the first space
            offset = document.GetOffset(line, column);
            if (offset < document.TextLength - 1)
            {
                offset++;

                textAtOffset = document.GetText(offset, 1);

                while (!string.IsNullOrWhiteSpace(textAtOffset))
                {
                    wordHovered = wordHovered + textAtOffset;

                    offset++;

                    if (offset >= document.TextLength)
                    {
                        break;
                    }

                    textAtOffset = document.GetText(offset, 1);

                    if (textAtOffset == "(" || textAtOffset == ")" || textAtOffset == "<" || textAtOffset == ">" || textAtOffset == "," || textAtOffset == ";")
                    {
                        break;
                    }
                }
            }

            return(wordHovered);
        }
Esempio n. 52
0
        public void TypesWithDelay(int KeyChar, ICSharpCode.AvalonEdit.Document.TextDocument textDocument, TextEditor textEditor, string FileName, int offset)
        {
            //_runnings = true;

            //	this.BeginInvoke(new Action(() =>
            {
                //
                //Point p = Selection.GetCursor();
                //
                //int offset = Caret.Offset;
                //
                //Row r = Document[p.Y];
                //

                if (vp == null)
                {
                    return;
                }

                shouldUpdate = false;

                this.textEditor = textEditor;

                TextViewPosition textViewPosition = new TextViewPosition(textEditor.TextArea.Caret.Location);

                string name = GetWordUnderMouse(textDocument, textViewPosition);

                WordUnderCaret = name;

                //if (WordUnderCaret == "pp")
                //    MessageBox.Show("");

                string names = name;

                if (name == "this.")
                {
                    name         = "this";
                    shouldUpdate = true;
                }
                else
                if (name.EndsWith("."))
                {
                    shouldUpdate = true;
                }
                else if (name.Length == 1)
                {
                    shouldUpdate = true;
                    name         = "";
                }
                else
                if (name.Length > 1 && !name.Contains("."))
                {
                    //sns = new List<ISymbol>();
                    return;
                }
                else
                {
                    name = "";
                }

                // offset = RealOffset(offset);

                List <Microsoft.CodeAnalysis.ISymbol> sn = LoadProjectTypes(vp, FileName, textDocument.Text, offset, name, "");

                sns = sn;

                if (sn.Count <= 0)
                {
                    if (name.Contains("."))
                    {
                        //MessageBox.Show("Check for static class members - " + WordUnderCaret);
                    }
                }

                //ArrayList L = new ArrayList();

                foreach (var b in sn)
                {
                    //if (b.Kind == SymbolKind.Local)
                    //  if (b is INamedTypeSymbol)

                    //        if (((INamedTypeSymbol)b).TypeKind == TypeKind.Class)
                    //            sn.Remove(b);
                }

                {
                    //			if (ins != null)
                    //			{
                    //				ins.Show();
                    //				form.Show();
                    //			}

                    //var c = Selection.GetCaretWords();

                    //string cc = "";
                    //foreach (string s in c)
                    //{
                    //    cc += s;
                    //}
                    //cc = cc.Trim();
                    //if (cc.EndsWith("="))
                    //{
                    //    string[] nc = Selection.GetCaretString().Trim().Split("=".ToCharArray());
                    //    if (nc.Length > 1)
                    //    {
                    //        List<Microsoft.CodeAnalysis.ISymbol> symbols = new List<Microsoft.CodeAnalysis.ISymbol>();
                    //        string data = nc[nc.Length - 2].Trim();
                    //        Microsoft.CodeAnalysis.ISymbol symbol = ins.GetSymbol(data);
                    //        if (symbol is IParameterSymbol)
                    //        {
                    //            IParameterSymbol ps = symbol as IParameterSymbol;
                    //            MessageBox.Show("template = detected for " + symbol.Name + " of type " + ps.Type.Name);
                    //            //Selection.AppendToCaretString(" " + ps.Type.Name);
                    //            symbols.Add(symbol);
                    //        }
                    //        else if (symbol is IPropertySymbol)
                    //        {
                    //            IPropertySymbol ps = symbol as IPropertySymbol;
                    //            MessageBox.Show("template = detected for " + symbol.Name + " of type " + ps.Type.Name);
                    //            //Selection.AppendToCaretString(" " + ps.Type.Name);
                    //            symbols.Add(symbol);
                    //        }
                    //        else if (symbol is IFieldSymbol)
                    //        {
                    //            IFieldSymbol ps = symbol as IFieldSymbol;
                    //            MessageBox.Show("template = detected for " + symbol.Name + " of type " + ps.Type.Name);
                    //            //Selection.AppendToCaretString(" " + ps.Type.Name);
                    //            symbols.Add(symbol);
                    //        }
                    //        else if (symbol != null)
                    //            MessageBox.Show("template = detected for " + symbol.Name);

                    //        ins.LoadFast(symbols);

                    //        //				ins.SetVirtualMode();

                    //        //				ins.AutoSize();

                    //        //				ins.Refresh();

                    //        return;
                    //    }
                    //}
                    //       string[] words = cc.Trim().Split(".".ToCharArray()).Select(s => s).Where(t => t != "").ToArray();

                    //       string name = "";

                    //       Parse(Selection.GetCaretString(), offset);

                    //       if (cc.StartsWith(".this"))
                    //           name = "this";
                    //       else
                    //       if (KeyChar == 8 && words.Length > 1)
                    //       {
                    //           //ins.Hide();
                    //           //form.Hide();
                    //           //if (dfs != null)
                    //           //	dfs.Close();
                    //           return;
                    //       }
                    //       else if (cc.StartsWith("."))
                    //       {
                    //           name = words[0];
                    //           if (/*name.Contains(")") && */name.Contains("("))
                    //           {
                    //               string[] dd = name.Split("(".ToCharArray());

                    //               //name = "." + dd[0];
                    //               name = dd[dd.Length - 1];//dd[0]
                    //           }
                    //       }
                    //       else if (cc.StartsWith("("))
                    //       {
                    //           name = words[0];
                    //           if (name.Contains("("))
                    //               if (name.Contains(")"))
                    //               {
                    //                   string[] dd = name.Split(",".ToCharArray());
                    //                   if (Selection.IsCaretInWord())
                    //                       name = "";
                    //               }
                    //       }
                    //       else if (cc.StartsWith(")"))
                    //       {
                    //           name = words[0];
                    //           if (name.Contains("("))
                    //               if (name.Contains(")"))
                    //               {
                    //                   if (Selection.IsCaretInWord())
                    //                       name = "";
                    //               }
                    //       }
                    //       Point pp = Selection.GetCursor();
                    //       pp.X = pp.X * ActiveViewControl.View.CharWidth;
                    //       pp.Y = (ActiveViewControl.Document[p.Y].VisibleIndex - ActiveViewControl.View.FirstVisibleRow + 1) * ActiveViewControl.View.RowHeight + 3;
                    //  //     form.Location = this.PointToScreen(pp);
                    //       List<Microsoft.CodeAnalysis.ISymbol> sn = ins.LoadProjectTypes(vp, FileName, Document.Text, offset, name, cc);
                    //       if (name.StartsWith("("))
                    //       {
                    //           //ins.Hide();
                    //           //form.Hide();
                    ////           LoadDefinition(sn, this.PointToScreen(pp));
                    //           methods = sn;
                    //           return;
                    //       }
                    //       else if (name.StartsWith(")"))
                    //       {
                    //           //ins.Hide();
                    //           //form.Hide();
                    //           //if (dfs != null)
                    //           //	dfs.Hide();
                    //           return;
                    //       }
                    //       //ins.SetVirtualMode();

                    //         ins.FindSimilarWords(w);

                    //ins.AutoSize();

                    //ins.Refresh();
                }

                //			if (form.Visible == true)
                //				form.SetTopMost();

                //		this.Focus();

                //		_runnings = false;
            }
        }
Esempio n. 53
0
 public DocumentChangeOperation(TextDocument document, DocumentChangeEventArgs change)
 {
     this.document = document;
     this.change   = change;
 }
Esempio n. 54
0
 /// <summary>
 /// Create <see cref="NewFolding"/>s for the specified document.
 /// </summary>
 public IEnumerable <NewFolding> CreateNewFoldings(ICSharpCode.AvalonEdit.Document.TextDocument document, out int firstErrorOffset)
 {
     firstErrorOffset = -1;
     return(CreateNewFoldings(document));
 }
Esempio n. 55
0
 internal TextAnchor(TextDocument document)
 {
     this.document = document;
 }
Esempio n. 56
0
 public DocAdapter(ICSharpCode.AvalonEdit.Document.TextDocument doc)
 {
     this.document = doc;
 }
 internal void AttachToDocument(TextDocument document)
 {
     document.UpdateStarted  += document_UpdateStarted;
     document.UpdateFinished += document_UpdateFinished;
     document.Changing       += document_Changing;
 }
Esempio n. 58
0
        public LineManager(IList <char> textBuffer, DocumentLineTree documentLineTree, TextDocument document)
        {
            this.document         = document;
            this.textBuffer       = textBuffer;
            this.documentLineTree = documentLineTree;
            UpdateListOfLineTrackers();

            Rebuild();
        }