/// <summary>
        /// Creates a new ReadOnlyDocument from the given text source.
        /// </summary>
        public ReadOnlyDocument(ITextSource textSource)
        {
            if (textSource == null)
            {
                throw new ArgumentNullException("textSource");
            }
            // ensure that underlying buffer is immutable
            this.textSource = textSource.CreateSnapshot();
            List <int> lines = new List <int>();

            lines.Add(0);
            int offset     = 0;
            int textLength = textSource.TextLength;

            while ((offset = textSource.IndexOfAny(newline, offset, textLength - offset)) >= 0)
            {
                offset++;
                if (textSource.GetCharAt(offset - 1) == '\r' && offset < textLength && textSource.GetCharAt(offset) == '\n')
                {
                    offset++;
                }
                lines.Add(offset);
            }
            this.lines = lines.ToArray();
        }
Example #2
0
        public ParseInformation Parse(FileName fileName, ITextSource fileContent, bool fullParseInformationRequested,
                                      IProject parentProject, CancellationToken cancellationToken)
        {
            AXmlParser             parser = new AXmlParser();
            AXmlDocument           document;
            IncrementalParserState newParserState;

            if (fileContent.Version is OnDiskTextSourceVersion)
            {
                document       = parser.Parse(fileContent, cancellationToken);
                newParserState = null;
            }
            else
            {
                document = parser.ParseIncremental(parserState, fileContent, out newParserState, cancellationToken);
            }
            parserState = newParserState;
            XamlUnresolvedFile unresolvedFile = XamlUnresolvedFile.Create(fileName, fileContent, document);
            ParseInformation   parseInfo;

            if (fullParseInformationRequested)
            {
                parseInfo = new XamlFullParseInformation(unresolvedFile, document, fileContent.CreateSnapshot());
            }
            else
            {
                parseInfo = new ParseInformation(unresolvedFile, fileContent.Version, false);
            }
            AddTagComments(document, parseInfo, fileContent);
            return(parseInfo);
        }
Example #3
0
        // gets the text from a text source, directly retrieving the underlying rope where possible
        static IEnumerable <char> GetTextFromTextSource(ITextSource textSource)
        {
            if (textSource == null)
            {
                throw new ArgumentNullException("textSource");
            }

                        #if NREFACTORY
            if (textSource is ReadOnlyDocument)
            {
                textSource = textSource.CreateSnapshot();                 // retrieve underlying text source, which might be a RopeTextSource
            }
#endif

            if (textSource is RopeTextSource rts)
            {
                return(rts.GetRope());
            }

            if (textSource is TextDocument doc)
            {
                return(doc.rope);
            }

            return(textSource.Text);
        }
Example #4
0
        /// <summary>
        /// Replaces text.
        /// </summary>
        /// <param name="offset">The starting offset of the text to be replaced.</param>
        /// <param name="length">The length of the text to be replaced.</param>
        /// <param name="text">The new text.</param>
        /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
        /// This affects how the anchors and segments inside the replaced region behave.
        /// If you pass null (the default when using one of the other overloads), the offsets are changed as
        /// in OffsetChangeMappingType.Normal mode.
        /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
        /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
        /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
        /// DocumentChangeEventArgs instance.
        /// </param>
        public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }
            text = text.CreateSnapshot();
            if (offsetChangeMap != null)
            {
                offsetChangeMap.Freeze();
            }

            // Ensure that all changes take place inside an update group.
            // Will also take care of throwing an exception if inDocumentChanging is set.
            BeginUpdate();
            try {
                // protect document change against corruption by other changes inside the event handlers
                inDocumentChanging = true;
                try {
                    // The range verification must wait until after the BeginUpdate() call because the document
                    // might be modified inside the UpdateStarted event.
                    ThrowIfRangeInvalid(offset, length);

                    DoReplace(offset, length, text, offsetChangeMap);
                } finally {
                    inDocumentChanging = false;
                }
            } finally {
                EndUpdate();
            }
        }
Example #5
0
 public MonoDevelopSourceText(ITextSource doc)
 {
     if (doc == null)
     {
         throw new ArgumentNullException(nameof(doc));
     }
     this.doc = doc.CreateSnapshot();
 }
Example #6
0
 /// <summary>
 /// Creates an immutable snapshot of a part of this text source.
 /// Unlike all other methods in this interface, this method is thread-safe.
 /// </summary>
 public static ITextSource CreateSnapshot(this ITextSource source, ISegment segment)
 {
     if (source == null)
     {
         throw new ArgumentNullException("source");
     }
     if (segment == null)
     {
         throw new ArgumentNullException("segment");
     }
     return(source.CreateSnapshot(segment.Offset, segment.Length));
 }
		public ITextSource Format (PolicyContainer policyParent, ITextSource input, ISegment segment = null)
		{
			try {
				if (segment == null)
					return formatter.Format (policyParent, mimeType, input);
				return formatter.Format (policyParent, mimeType, input, segment.Offset, segment.EndOffset);
			} catch (Exception e) {
				LoggingService.LogError ("Error while formatting text.", e);
				if (segment == null)
					return input;
				return input.CreateSnapshot (segment.Offset, segment.Length);
			}
		}
		public ITextSource Format (PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
		{
			if (startOffset < 0 || startOffset > input.Length)
				throw new ArgumentOutOfRangeException (nameof (startOffset), "should be >= 0 && < " + input.Length + " was:" + startOffset);
			if (length < 0 || startOffset + length > input.Length)
				throw new ArgumentOutOfRangeException (nameof (length), "should be >= 0 && < " + (input.Length - startOffset) + " was:" + length);
			try {
				return FormatImplementation (policyParent ?? PolicyService.DefaultPolicies, mimeType, input, startOffset, length);
			} catch (Exception e) {
				LoggingService.LogError ("Error while formatting text.", e);
			}
			return input.CreateSnapshot (startOffset, length);
		}
Example #9
0
		public ITextSource Format (PolicyContainer policyParent, string mimeType, ITextSource input, int startOffset, int length)
		{
			if (startOffset < 0 || startOffset > input.Length)
				throw new ArgumentOutOfRangeException (nameof (startOffset), "should be >= 0 && < " + input.Length + " was:" + startOffset);
			if (length < 0 || startOffset + length > input.Length)
				throw new ArgumentOutOfRangeException (nameof (length), "should be >= 0 && < " + (input.Length - startOffset) + " was:" + length);
			try {
				return FormatImplementation (policyParent ?? PolicyService.DefaultPolicies, mimeType, input, startOffset, length);
			} catch (Exception e) {
				LoggingService.LogError ("Error while formatting text.", e);
			}
			return input.CreateSnapshot (startOffset, length);
		}
Example #10
0
 public ITextSource Format(PolicyContainer policyParent, ITextSource input, ISegment segment = null)
 {
     try {
         if (segment == null)
         {
             return(formatter.Format(policyParent, mimeType, input));
         }
         return(formatter.Format(policyParent, mimeType, input, segment.Offset, segment.EndOffset));
     } catch (Exception e) {
         LoggingService.LogError("Error while formatting text.", e);
         if (segment == null)
         {
             return(input);
         }
         return(input.CreateSnapshot(segment.Offset, segment.Length));
     }
 }
 static IEnumerable <string> GetWords(ITextSource textSource)
 {
     using (var r = textSource.CreateSnapshot().CreateReader())
     {
         while (true)
         {
             var line = r.ReadLine();
             if (line == null)
             {
                 break;
             }
             foreach (var w in Regex.Split(line, @"[^\w]+"))
             {
                 yield return(w);
             }
         }
     }
 }
Example #12
0
		/// <summary>
		/// Creates a new ReadOnlyDocument from the given text source.
		/// </summary>
		public ReadOnlyDocument(ITextSource textSource)
		{
			if (textSource == null)
				throw new ArgumentNullException("textSource");
			// ensure that underlying buffer is immutable
			this.textSource = textSource.CreateSnapshot();
			List<int> lines = new List<int>();
			lines.Add(0);
			int offset = 0;
			int textLength = textSource.TextLength;
			while ((offset = textSource.IndexOfAny(newline, offset, textLength - offset)) >= 0) {
				offset++;
				if (textSource.GetCharAt(offset - 1) == '\r' && offset < textLength && textSource.GetCharAt(offset) == '\n') {
					offset++;
				}
				lines.Add(offset);
			}
			this.lines = lines.ToArray();
		}
Example #13
0
		// gets the text from a text source, directly retrieving the underlying rope where possible
		static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
		{
			if (textSource == null)
				throw new ArgumentNullException("textSource");
			

			if (textSource is ReadOnlyDocument)
				textSource = textSource.CreateSnapshot(); // retrieve underlying text source, which might be a RopeTextSource

			
			RopeTextSource rts = textSource as RopeTextSource;
			if (rts != null)
				return rts.GetRope();
			
			TextDocument doc = textSource as TextDocument;
			if (doc != null)
				return doc.rope;
			
			return textSource.Text;
		}
Example #14
0
		public ParseInformation Parse(FileName fileName, ITextSource fileContent, bool fullParseInformationRequested,
		                              IProject parentProject, CancellationToken cancellationToken)
		{
			AXmlParser parser = new AXmlParser();
			AXmlDocument document;
			IncrementalParserState newParserState;
			if (fileContent.Version is OnDiskTextSourceVersion) {
				document = parser.Parse(fileContent, cancellationToken);
				newParserState = null;
			} else {
				document = parser.ParseIncremental(parserState, fileContent, out newParserState, cancellationToken);
			}
			parserState = newParserState;
			XamlUnresolvedFile unresolvedFile = XamlUnresolvedFile.Create(fileName, fileContent, document);
			ParseInformation parseInfo;
			if (fullParseInformationRequested)
				parseInfo = new XamlFullParseInformation(unresolvedFile, document, fileContent.CreateSnapshot());
			else
				parseInfo = new ParseInformation(unresolvedFile, fileContent.Version, false);
			AddTagComments(document, parseInfo, fileContent);
			return parseInfo;
		}
		Task<ProjectEntry> DoParseAsync(ITextSource fileContent, IProject parentProject, bool requestFullParseInformation, CancellationToken cancellationToken)
		{
			// Create snapshot of file content, if required
			bool lookupOpenFileOnTargetThread;
			if (fileContent != null) {
				lookupOpenFileOnTargetThread = false;
				// File content was explicitly specified:
				// Let's make a snapshot in case the text source is mutable.
				fileContent = fileContent.CreateSnapshot();
			} else if (SD.MainThread.InvokeRequired) {
				// fileContent == null && not on the main thread:
				// Don't fetch the file content right now; if we need to SafeThreadCall() anyways,
				// it's better to do so from the background task.
				lookupOpenFileOnTargetThread = true;
			} else {
				// fileContent == null && we are on the main thread:
				// Let's look up the file in the list of open files right now
				// so that we don't need to SafeThreadCall() later on.
				lookupOpenFileOnTargetThread = false;
				fileContent = parser.GetFileContent(fileName);
			}
			Task<ProjectEntry> task;
			lock (this) {
				if (fileContent != null) {
					// Optimization:
					// don't start a background task if fileContent was specified and up-to-date parse info is available
					int index = FindIndexForProject(parentProject);
					int versionComparison = CompareVersions(fileContent.Version);
					if (versionComparison == 0 && index >= 0) {
						// Ensure we have parse info for the specified project (entry.UnresolvedFile is null for newly registered projects)
						// If full parse info is requested, ensure we have full parse info.
						if (entries[index].UnresolvedFile != null && !(requestFullParseInformation && entries[index].CachedParseInformation == null)) {
							// We already have the requested version parsed, just return it:
							return Task.FromResult(entries[index]);
						}
					}
					// Optimization:
					// if an equivalent task is already running, return that one instead
					if (runningAsyncParseTask != null && (!requestFullParseInformation || runningAsyncParseFullInfoRequested)
					    && runningAsyncParseProject == parentProject
					    && runningAsyncParseFileContentVersion.BelongsToSameDocumentAs(fileContent.Version)
					    && runningAsyncParseFileContentVersion.CompareAge(fileContent.Version) == 0)
					{
						return runningAsyncParseTask;
					}
				}
				task = new Task<ProjectEntry>(
					delegate {
						try {
							if (lookupOpenFileOnTargetThread) {
								fileContent = SD.FileService.GetFileContentForOpenFile(fileName);
							}
							return DoParse(fileContent, parentProject, requestFullParseInformation, cancellationToken);
						} finally {
							lock (this) {
								runningAsyncParseTask = null;
								runningAsyncParseFileContentVersion = null;
								runningAsyncParseProject = null;
							}
						}
					}, cancellationToken);
				if (fileContent != null && fileContent.Version != null && !cancellationToken.CanBeCanceled) {
					runningAsyncParseTask = task;
					runningAsyncParseFileContentVersion = fileContent.Version;
					runningAsyncParseProject = parentProject;
					runningAsyncParseFullInfoRequested = requestFullParseInformation;
				}
			}
			task.Start();
			return task;
		}
Example #16
0
 /// <summary>
 /// Creates an immutable snapshot of this text buffer.
 /// </summary>
 public virtual ITextBuffer CreateSnapshot()
 {
     return(new AvalonEditTextSourceAdapter(textSource.CreateSnapshot()));
 }
 /// <inheritdoc/>
 public ITextSource CreateSnapshot(int offset, int length)
 {
     return(textSource.CreateSnapshot(offset, length));
 }
Example #18
0
 public ITextSource ToTextSource()
 {
     return(_text.CreateSnapshot(_index, _length));
 }
        Task <ProjectEntry> DoParseAsync(ITextSource fileContent, IProject parentProject, bool requestFullParseInformation, CancellationToken cancellationToken)
        {
            // Create snapshot of file content, if required
            bool lookupOpenFileOnTargetThread;

            if (fileContent != null)
            {
                lookupOpenFileOnTargetThread = false;
                // File content was explicitly specified:
                // Let's make a snapshot in case the text source is mutable.
                fileContent = fileContent.CreateSnapshot();
            }
            else if (SD.MainThread.InvokeRequired)
            {
                // fileContent == null && not on the main thread:
                // Don't fetch the file content right now; if we need to SafeThreadCall() anyways,
                // it's better to do so from the background task.
                lookupOpenFileOnTargetThread = true;
            }
            else
            {
                // fileContent == null && we are on the main thread:
                // Let's look up the file in the list of open files right now
                // so that we don't need to SafeThreadCall() later on.
                lookupOpenFileOnTargetThread = false;
                if (parser != null)
                {
                    fileContent = parser.GetFileContent(fileName);
                }
            }
            Task <ProjectEntry> task;

            lock (runningAsyncParseLock) {
                if (fileContent != null)
                {
                    // Optimization:
                    // don't start a background task if fileContent was specified and up-to-date parse info is available
                    rwLock.EnterReadLock();
                    try {
                        int index             = FindIndexForProject(parentProject);
                        int versionComparison = CompareVersions(fileContent.Version);
                        if (versionComparison == 0 && index >= 0)
                        {
                            // Ensure we have parse info for the specified project (entry.UnresolvedFile is null for newly registered projects)
                            // If full parse info is requested, ensure we have full parse info.
                            if (entries[index].UnresolvedFile != null && !(requestFullParseInformation && entries[index].CachedParseInformation == null))
                            {
                                // We already have the requested version parsed, just return it:
                                return(Task.FromResult(entries[index]));
                            }
                        }
                    } finally {
                        rwLock.ExitReadLock();
                    }
                    // Optimization:
                    // if an equivalent task is already running, return that one instead
                    if (runningAsyncParseTask != null && (!requestFullParseInformation || runningAsyncParseFullInfoRequested) &&
                        runningAsyncParseProject == parentProject &&
                        runningAsyncParseFileContentVersion.BelongsToSameDocumentAs(fileContent.Version) &&
                        runningAsyncParseFileContentVersion.CompareAge(fileContent.Version) == 0)
                    {
                        return(runningAsyncParseTask);
                    }
                }
                task = new Task <ProjectEntry>(
                    delegate {
                    try {
                        if (lookupOpenFileOnTargetThread)
                        {
                            fileContent = SD.FileService.GetFileContentForOpenFile(fileName);
                        }
                        return(DoParse(fileContent, parentProject, requestFullParseInformation, cancellationToken));
                    } finally {
                        lock (runningAsyncParseLock) {
                            runningAsyncParseTask = null;
                            runningAsyncParseFileContentVersion = null;
                            runningAsyncParseProject            = null;
                        }
                    }
                }, cancellationToken);
                if (fileContent != null && fileContent.Version != null && !cancellationToken.CanBeCanceled)
                {
                    runningAsyncParseTask = task;
                    runningAsyncParseFileContentVersion = fileContent.Version;
                    runningAsyncParseProject            = parentProject;
                    runningAsyncParseFullInfoRequested  = requestFullParseInformation;
                }
            }
            task.Start();
            return(task);
        }
Example #20
0
        /*
         * Does a split. In the right-to-left case we reorder the
         * array to be forwards.
         */
        internal static ITextSource[] Split(Regex regex, ITextSource input, int count, int startat)
        {
            Match match;

            ITextSource[] result;

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            if (startat < 0 || startat > input.Length)
            {
                throw new ArgumentOutOfRangeException("startat");
            }

            if (count == 1)
            {
                result    = new ITextSource[1];
                result[0] = input;
                return(result);
            }

            count -= 1;

            match = regex.Match(input, startat);

            if (!match.Success)
            {
                result    = new ITextSource[1];
                result[0] = input;
                return(result);
            }
            else
            {
                List <ITextSource> al = new List <ITextSource>();

                if (!regex.RightToLeft)
                {
                    int prevat = 0;

                    for (;;)
                    {
                        al.Add(input.CreateSnapshot(prevat, match.Index - prevat));

                        prevat = match.Index + match.Length;

                        // add all matched capture groups to the list.
                        for (int i = 1; i < match.Groups.Count; i++)
                        {
                            if (match.IsMatched(i))
                            {
                                al.Add(match.Groups[i].ToTextSource());
                            }
                        }

                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();

                        if (!match.Success)
                        {
                            break;
                        }
                    }

                    al.Add(input.CreateSnapshot(prevat, input.Length - prevat));
                }
                else
                {
                    int prevat = input.Length;

                    for (;;)
                    {
                        al.Add(input.CreateSnapshot(match.Index + match.Length, prevat - match.Index - match.Length));

                        prevat = match.Index;

                        // add all matched capture groups to the list.
                        for (int i = 1; i < match.Groups.Count; i++)
                        {
                            if (match.IsMatched(i))
                            {
                                al.Add(match.Groups[i].ToTextSource());
                            }
                        }

                        if (--count == 0)
                        {
                            break;
                        }

                        match = match.NextMatch();

                        if (!match.Success)
                        {
                            break;
                        }
                    }

                    al.Add(input.CreateSnapshot(0, prevat));

                    al.Reverse(0, al.Count);
                }

                return(al.ToArray());
            }
        }
Example #21
0
 /// <inheritdoc/>
 public ITextSource CreateSnapshot()
 {
     return(baseTextSource.CreateSnapshot(viewedSegment.Offset, viewedSegment.Length));
 }
Example #22
0
        /// <summary>
        /// Replaces text.
        /// </summary>
        /// <param name="offset">The starting offset of the text to be replaced.</param>
        /// <param name="length">The length of the text to be replaced.</param>
        /// <param name="text">The new text.</param>
        /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text.
        /// This affects how the anchors and segments inside the replaced region behave.
        /// If you pass null (the default when using one of the other overloads), the offsets are changed as
        /// in OffsetChangeMappingType.Normal mode.
        /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode).
        /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>.
        /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting
        /// DocumentChangeEventArgs instance.
        /// </param>
        public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap)
        {
            if (text == null)
                throw new ArgumentNullException("text");
            text = text.CreateSnapshot();
            if (offsetChangeMap != null)
                offsetChangeMap.Freeze();

            // Ensure that all changes take place inside an update group.
            // Will also take care of throwing an exception if inDocumentChanging is set.
            BeginUpdate();
            try {
                // protect document change against corruption by other changes inside the event handlers
                inDocumentChanging = true;
                try {
                    // The range verification must wait until after the BeginUpdate() call because the document
                    // might be modified inside the UpdateStarted event.
                    ThrowIfRangeInvalid(offset, length);

                    DoReplace(offset, length, text, offsetChangeMap);
                } finally {
                    inDocumentChanging = false;
                }
            } finally {
                EndUpdate();
            }
        }
Example #23
0
        // gets the text from a text source, directly retrieving the underlying rope where possible
        static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
        {
            if (textSource == null)
                throw new ArgumentNullException("textSource");

            #if NREFACTORY
            if (textSource is ReadOnlyDocument)
                textSource = textSource.CreateSnapshot(); // retrieve underlying text source, which might be a RopeTextSource
            #endif

            RopeTextSource rts = textSource as RopeTextSource;
            if (rts != null)
                return rts.GetRope();

            TextDocument doc = textSource as TextDocument;
            if (doc != null)
                return doc.rope;

            return textSource.Text;
        }