public IndentationTrackerWrapper (Mono.TextEditor.TextEditorData textEditorData, IReadonlyTextDocument document, MonoDevelop.Ide.Editor.Extension.IndentationTracker indentationTracker)
		{
			if (textEditorData == null)
				throw new System.ArgumentNullException ("textEditorData");
			if (document == null)
				throw new System.ArgumentNullException ("document");
			if (indentationTracker == null)
				throw new System.ArgumentNullException ("indentationTracker");
			this.document = document;
			this.indentationTracker = indentationTracker;
		}
		public override async Task<BraceMatchingResult?> GetMatchingBracesAsync (IReadonlyTextDocument editor, DocumentContext context, int offset, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (context.ParsedDocument == null)
				return await fallback.GetMatchingBracesAsync (editor, context, offset, cancellationToken);

			var analysisDocument = context.AnalysisDocument;
			if (analysisDocument == null)
				return null;
			var partialDoc = await CSharpCompletionTextEditorExtension.WithFrozenPartialSemanticsAsync (analysisDocument, cancellationToken).ConfigureAwait (false);
			var root = await partialDoc.GetSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
			if (offset < 0 || root.Span.End <= offset)
				return null;
			var token = root.FindToken (offset);
			var tokenSpan = token.Span;
			if (offset < tokenSpan.Start || offset >= tokenSpan.End)
				return null;
			for (int i = 0; i < tokenPairs.Length / 2; i++) {
				var open = tokenPairs [i * 2];
				var close = tokenPairs [i * 2 + 1];
				SyntaxToken match;
				if (token.IsKind (open)) {
					if (TryFindMatchingToken (token, out match, open, close)) {
						return new BraceMatchingResult (new TextSegment (tokenSpan.Start, tokenSpan.Length), new TextSegment (match.Span.Start, match.Span.Length), true);
					}
				} else if (token.IsKind (close)) {
					if (TryFindMatchingToken (token, out match, open, close)) {
						return new BraceMatchingResult (new TextSegment (match.Span.Start, match.Span.Length), new TextSegment (tokenSpan.Start, tokenSpan.Length), false);
					}
				}
			}

			if (token.IsKind (SyntaxKind.StringLiteralToken) && token.ToString().EndsWith ("\"", StringComparison.Ordinal)) {
				if (token.IsVerbatimStringLiteral ()) {
					if (offset <= tokenSpan.Start)
						return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 2), new TextSegment (tokenSpan.End - 1, 1), true);
					if (offset >= tokenSpan.End - 1)
						return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 2), new TextSegment (tokenSpan.End - 1, 1), false);
				} else {
					if (offset <= tokenSpan.Start)
						return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), true);
					if (offset >= tokenSpan.End - 1)
						return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), false);
				}
			}

			if (token.IsKind (SyntaxKind.CharacterLiteralToken) && token.ToString().EndsWith ("\'", StringComparison.Ordinal)) {
				if (offset <= tokenSpan.Start)
					return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), true);
				if (offset >= tokenSpan.End - 1)
					return new BraceMatchingResult (new TextSegment (tokenSpan.Start, 1), new TextSegment (tokenSpan.End - 1, 1), false);
			}

			return null;
		}
		internal static List<InsertionPoint> GetInsertionPoints (IReadonlyTextDocument data, SemanticModel model, ITypeSymbol type, int part)
		{
			List<InsertionPoint> result = new List<InsertionPoint> ();

			type = model.GetEnclosingNamedType (part, default (CancellationToken)) as ITypeSymbol ?? type;
			var sourceSpan = new TextSpan (part, 0);

			var filePath = data.FileName;
			var declaringType = type.DeclaringSyntaxReferences.FirstOrDefault (dsr => dsr.SyntaxTree.FilePath == filePath && dsr.Span.Contains (sourceSpan)) ?? type.DeclaringSyntaxReferences.FirstOrDefault ();
			if (declaringType == null)
				return result;
			return GetInsertionPoints (data, type, result, sourceSpan, declaringType);
		}
		public override Task<BraceMatchingResult?> GetMatchingBracesAsync (IReadonlyTextDocument editor, DocumentContext context, int offset, CancellationToken cancellationToken)
		{
			BraceMatchingResult? result = null;

			var matching = SimpleBracketMatcher.GetMatchingBracketOffset (editor, offset, cancellationToken);
			if (matching >= 0) {
				int start = Math.Min (offset, matching);
				int end = Math.Max (offset, matching);
				result = new BraceMatchingResult (new TextSegment (start, 1), new TextSegment (end, 1), offset == start);
			}

			return Task.FromResult (result);
		}
Exemplo n.º 5
0
		public Task<Projection> CreateProjection (DocumentInfo info, IReadonlyTextDocument data, bool buildExpressions)
		{
			if (info == null)
				throw new ArgumentNullException ("info");
			if (data == null)
				throw new ArgumentNullException ("data");
			var document = new StringBuilder ();

			WriteUsings (info.Imports, document);
			var segBuilder = System.Collections.Immutable.ImmutableList<ProjectedSegment>.Empty.ToBuilder ();

			foreach (var node in info.XScriptBlocks) {
				var start = data.LocationToOffset (node.Region.Begin.Line, node.Region.Begin.Column) + 2;
				var end = data.LocationToOffset (node.Region.End.Line, node.Region.End.Column) - 2;

				segBuilder.Add (new ProjectedSegment (start, document.Length, end - start));

				document.AppendLine (data.GetTextBetween (start, end));
			}
			if (buildExpressions) {
				WriteClassDeclaration (info, document);
				document.AppendLine ("{");
				document.AppendLine ("void Generated ()");
				document.AppendLine ("{");
				//Console.WriteLine ("start:" + location.BeginLine  +"/" +location.BeginColumn);

				foreach (var node in info.XExpressions) {
					bool isBlock = node is WebFormsRenderBlock;

					var start = data.LocationToOffset (node.Region.Begin.Line, node.Region.Begin.Column) + 2;
					var end = data.LocationToOffset (node.Region.End.Line, node.Region.End.Column) - 2;

					if (!isBlock) {
						document.Append ("WriteLine (");
						start += 1;
					}

					string expr = data.GetTextBetween (start, end);
					segBuilder.Add (new ProjectedSegment (start, document.Length, expr.Length));
					document.Append (expr);
					if (!isBlock)
						document.Append (");");
				}
				document.AppendLine ("}");
				document.AppendLine ("}");
			}
			return Task.FromResult(new Projection (
				TextEditorFactory.CreateNewDocument (new StringTextSource (document.ToString ()), info.AspNetDocument.FileName + ".g.cs", "text/x-csharp"),
				segBuilder.ToImmutable ()
			));
		}
		static int StartsWithListMember (IReadonlyTextDocument document, IList<string> list, int offset)
		{
			if (document == null)
				throw new ArgumentNullException ("document");
			if (list == null)
				throw new ArgumentNullException ("list");
			for (int i = 0; i < list.Count; i++) {
				string item = list [i];
				if (offset + item.Length < document.Length) {
					if (document.GetTextAt (offset, item.Length) == item)
						return i;
				}
			}
			return -1;
		}
		public static List<InsertionPoint> GetInsertionPoints (IReadonlyTextDocument data, MonoDevelop.Ide.TypeSystem.ParsedDocument parsedDocument, ITypeSymbol type, int part)
		{
			if (data == null)
				throw new ArgumentNullException (nameof (data));
			if (parsedDocument == null)
				throw new ArgumentNullException (nameof (parsedDocument));
			if (type == null)
				throw new ArgumentNullException (nameof (type));
			if (!type.IsDefinedInSource ())
				throw new ArgumentException ("The given type needs to be defined in source code.", nameof (type));

			// update type from parsed document, since this is always newer.
			//type = parsedDocument.GetInnermostTypeDefinition (type.GetLocation ()) ?? type;
			//var realStartLocation = data.OffsetToLocation (offset);
			var model = parsedDocument.GetAst<SemanticModel> ();
			return GetInsertionPoints (data, model, type, part);
		}
		public static int GetMatchingBracketOffset (IReadonlyTextDocument document, int offset, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (offset < 0 || offset >= document.Length)
				return -1;
			char ch = document.GetCharAt (offset);
			int bracket = openBrackets.IndexOf (ch);
			int result;
			if (bracket >= 0) {
				result = SearchMatchingBracketForward (document, offset + 1, closingBrackets [bracket], openBrackets [bracket], cancellationToken);
			} else {
				bracket = closingBrackets.IndexOf (ch);
				if (bracket >= 0) {
					result = SearchMatchingBracketBackward (document, offset - 1, openBrackets [bracket], closingBrackets [bracket], cancellationToken);
				} else {
					result = -1;
				}
			}
			return result;
		}
		public static async Task<DebugDataTipInfo> ResolveAsync (IReadonlyTextDocument editor, DocumentContext document, int offset, CancellationToken cancellationToken)
		{
			var analysisDocument = document.AnalysisDocument;
			DebugDataTipInfo result;
			CompilationUnitSyntax compilationUnit = null;
			if (analysisDocument == null) {
				compilationUnit = SyntaxFactory.ParseCompilationUnit (editor.Text);
				result = GetInfo (compilationUnit, null, offset, default(CancellationToken));
			} else {
				compilationUnit = await analysisDocument.GetCSharpSyntaxRootAsync (cancellationToken).ConfigureAwait (false);
				var semantic = document.ParsedDocument?.GetAst<SemanticModel> ();
				if (semantic == null) {
					semantic = await analysisDocument.GetSemanticModelAsync (cancellationToken).ConfigureAwait (false);
				}
				result = GetInfo (compilationUnit, semantic, offset, default(CancellationToken));
			}
			if (result.IsDefault || !result.Span.Contains(offset)) {
				return new DebugDataTipInfo (result.Span, null);
			} else if (result.Text == null) {
				return new DebugDataTipInfo (result.Span, compilationUnit.GetText ().ToString (result.Span));
			} else {
				return result;
			}
		}
Exemplo n.º 10
0
        //		public static void QueueQuickFixAnalysis (Document doc, TextLocation loc, CancellationToken token, Action<List<CodeAction>> callback)
        //		{
        //			var ext = doc.GetContent<MonoDevelop.AnalysisCore.Gui.ResultsEditorExtension> ();
        //			var issues = ext != null ? ext.GetResultsAtOffset (doc.Editor.LocationToOffset (loc), token).OrderBy (r => r.Level).ToList () : new List<Result> ();
        //
        //			ThreadPool.QueueUserWorkItem (delegate {
        //				try {
        //					var result = new List<CodeAction> ();
        //					foreach (var r in issues) {
        //						if (token.IsCancellationRequested)
        //							return;
        //						var fresult = r as FixableResult;
        //						if (fresult == null)
        //							continue;
        ////						foreach (var action in FixOperationsHandler.GetActions (doc, fresult)) {
        ////							result.Add (new AnalysisContextActionProvider.AnalysisCodeAction (action, r) {
        ////								DocumentRegion = action.DocumentRegion
        ////							});
        ////						}
        //					}
        //					result.AddRange (GetValidActions (doc, loc).Result);
        //					callback (result);
        //				} catch (Exception ex) {
        //					LoggingService.LogError ("Error in analysis service", ex);
        //				}
        //			});
        //		}

        public static MonoDevelop.Ide.Editor.DocumentLocation GetCorrectResolveLocation(IReadonlyTextDocument editor, MonoDevelop.Ide.Editor.DocumentLocation location)
        {
            if (editor == null || location.Column == 1)
            {
                return(location);
            }

            /*if (editor is TextEditor) {
             *      if (((TextEditor)editor).IsSomethingSelected)
             *              return ((TextEditor)editor).SelectionRegion.Begin;
             * }*/
            var line = editor.GetLine(location.Line);

            if (line == null || location.Column > line.LengthIncludingDelimiter)
            {
                return(location);
            }
            int offset = editor.LocationToOffset(location);

            if (offset > 0 && !char.IsLetterOrDigit(editor.GetCharAt(offset)) && char.IsLetterOrDigit(editor.GetCharAt(offset - 1)))
            {
                return(new MonoDevelop.Ide.Editor.DocumentLocation(location.Line, location.Column - 1));
            }
            return(location);
        }
		static int SearchMatchingBracketBackward (IReadonlyTextDocument document, int offset, char openBracket, char closingBracket, CancellationToken cancellationToken)
		{
			bool isInBlockComment = false;
			bool isInLineComment = false;
			int curStringQuote = -1;

			IList<string> blockCommentStarts = GetList (document, "BlockCommentStart");
			IList<string> blockCommentEnds = GetList (document, "BlockCommentEnd");
			IList<string> stringQuotes = GetList (document, "StringQuote");

			bool startsInLineComment = StartsInLineComment (document, offset);
			int depth = -1;

			if (!startsInLineComment)
				offset = GetLastSourceCodePosition (document, offset);

			while (offset >= 0 && offset < document.Length) {
				if (offset % 100 == 0 && cancellationToken.IsCancellationRequested)
					return -1;
				char ch = document.GetCharAt (offset);

				// check block comments
				if (!isInLineComment && curStringQuote < 0) {
					if (!isInBlockComment) {
						isInBlockComment = StartsWithListMember (document, blockCommentEnds, offset) >= 0;
					} else {
						isInBlockComment = StartsWithListMember (document, blockCommentStarts, offset) < 0;
					}
				}

				if (!isInBlockComment && !isInLineComment) {
					int i = StartsWithListMember (document, stringQuotes, offset);
					if (i >= 0) {
						if (curStringQuote >= 0) {
							if (curStringQuote == i)
								curStringQuote = -1;
						} else {
							curStringQuote = i;
						}
					}
				}

				switch (ch) {
				case '\n':
				case '\r':
					if (startsInLineComment)
						return -1;
					offset--;
					while (offset > 0 && (document.GetCharAt (offset) == '\n' || document.GetCharAt (offset) == '\r')) {
						offset--;
					}
					offset = GetLastSourceCodePosition (document, offset) + 1;
					break;
				default:
					if (ch == closingBracket) {
						if (!(curStringQuote >= 0 || isInBlockComment))
							--depth;
					} else if (ch == openBracket) {
						if (!(curStringQuote >= 0 || isInBlockComment)) {
							++depth;
							if (depth == 0)
								return offset;
						}
					}
					break;
				}
				offset--;
			}
			return -1;
		}
		static bool StartsInLineComment (IReadonlyTextDocument document, int offset)
		{
			IList<string> lineComments = GetList (document, "LineComment");
			var line = document.GetLineByOffset (offset);
			for (int i = line.Offset; i < offset; i++) {
				if (StartsWithListMember (document, lineComments, i) >= 0)
					return true;
			}
			return false;
		}
Exemplo n.º 13
0
		public static TextEditor CreateNewEditor (IReadonlyTextDocument document, TextEditorType textEditorType = TextEditorType.Default)
		{
			if (document == null)
				throw new System.ArgumentNullException ("document");
			var result = new TextEditor (currentFactory.CreateNewEditor (document), textEditorType) {
				ZoomLevel = zoomLevel
			};
			result.ZoomLevelChanged += delegate {
				zoomLevel.Value = result.ZoomLevel;
			};
			return result;
		}
		public static string GetDiffAsString (this IReadonlyTextDocument document, IReadonlyTextDocument changedDocument, bool includeEol = true)
		{
			if (document == null)
				throw new ArgumentNullException ("document");
			if (changedDocument == null)
				throw new ArgumentNullException ("changedDocument");
			return Diff.GetDiffString (GetDiff (document, changedDocument, includeEol), document, changedDocument, document.FileName, changedDocument.FileName);
		}
		static int [] GetDiffCodes (IReadonlyTextDocument document, ref int codeCounter, Dictionary<string, int> codeDictionary, DiffOptions options)
		{
			int i = 0;
			var result = new int [document.LineCount];
			foreach (var line in document.GetLinesStartingAt (1)) {
				string lineText = document.GetTextAt (line.Offset, options.IncludeEol ? line.LengthIncludingDelimiter : line.Length);
				if (options.TrimLines)
					lineText = lineText.Trim ();
				int curCode;
				if (!codeDictionary.TryGetValue (lineText, out curCode)) {
					codeDictionary [lineText] = curCode = ++codeCounter;
				}
				result [i] = curCode;
				i++;
			}
			return result;
		}
Exemplo n.º 16
0
        public static MSBuildResolveResult Resolve(
            XmlParser parser, IReadonlyTextDocument document, MSBuildDocument context)
        {
            int offset = parser.Position;

            //clones and connects nodes to their parents
            parser = parser.GetTreeParser();

            var nodePath = parser.Nodes.ToList();

            nodePath.Reverse();

            //capture incomplete names, attributes and element values
            int i = offset;

            if (parser.CurrentState is XmlRootState && parser.Nodes.Peek() is XElement unclosedEl)
            {
                while (i < document.Length && InRootOrClosingTagState() && !unclosedEl.IsClosed)
                {
                    parser.Push(document.GetCharAt(i++));
                }
            }
            else
            {
                while (i < document.Length && InNameOrAttributeState())
                {
                    parser.Push(document.GetCharAt(i++));
                }
            }

            //if nodes are incomplete, they won't get connected
            //HACK: the only way to reconnect them is reflection
            if (nodePath.Count > 1)
            {
                for (int idx = 1; idx < nodePath.Count; idx++)
                {
                    var node = nodePath [idx];
                    if (node.Parent == null)
                    {
                        var parent = nodePath [idx - 1];
                        ParentProp.SetValue(node, parent);
                    }
                }
            }

            //need to look up element by walking how the path, since at each level, if the parent has special children,
            //then that gives us information to identify the type of its children
            MSBuildLanguageElement   languageElement   = null;
            MSBuildLanguageAttribute languageAttribute = null;
            XElement   el  = null;
            XAttribute att = null;

            foreach (var node in nodePath)
            {
                if (node is XAttribute xatt && xatt.Name.Prefix == null)
                {
                    att = xatt;
                    languageAttribute = languageElement?.GetAttribute(att.Name.Name);
                    break;
                }

                //if children of parent is known to be arbitrary data, don't go into it
                if (languageElement != null && languageElement.ValueKind == MSBuildValueKind.Data)
                {
                    break;
                }

                //code completion is forgiving, all we care about best guess resolve for deepest child
                if (node is XElement xel && xel.Name.Prefix == null)
                {
                    el = xel;
                    languageElement = MSBuildLanguageElement.Get(el.Name.Name, languageElement);
                    if (languageElement != null)
                    {
                        continue;
                    }
                }

                languageElement = null;
            }

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

            var rr = new MSBuildResolveResult {
                LanguageElement   = languageElement,
                LanguageAttribute = languageAttribute,
                XElement          = el,
                XAttribute        = att
            };

            var rv = new MSBuildResolveVisitor(offset, rr);

            rv.Run(el, languageElement, document.FileName, document, context);

            return(rr);

            bool InNameOrAttributeState() =>
            parser.CurrentState is XmlNameState ||
            parser.CurrentState is XmlAttributeState ||
            parser.CurrentState is XmlAttributeValueState;

            bool InRootOrClosingTagState() =>
            parser.CurrentState is XmlRootState ||
            parser.CurrentState is XmlNameState ||
            parser.CurrentState is XmlClosingTagState;
        }
Exemplo n.º 17
0
        static int SearchMatchingBracket(IReadonlyTextDocument editor, int offset, char openBracket, char closingBracket, int direction)
        {
            bool isInString       = false;
            bool isInChar         = false;
            bool isInBlockComment = false;
            int  depth            = -1;

            while (offset >= 0 && offset < editor.Length)
            {
                char ch = editor.GetCharAt(offset);
                switch (ch)
                {
                case '/':
                    if (isInBlockComment)
                    {
                        isInBlockComment = editor.GetCharAt(offset + direction) != '*';
                    }
                    if (!isInString && !isInChar && offset - direction < editor.Length)
                    {
                        isInBlockComment = offset > 0 && editor.GetCharAt(offset - direction) == '*';
                    }
                    break;

                case '"':
                    if (!isInChar && !isInBlockComment)
                    {
                        isInString = !isInString;
                    }
                    break;

                case '\'':
                    if (!isInString && !isInBlockComment)
                    {
                        isInChar = !isInChar;
                    }
                    break;

                default:
                    if (ch == closingBracket)
                    {
                        if (!(isInString || isInChar || isInBlockComment))
                        {
                            --depth;
                        }
                    }
                    else if (ch == openBracket)
                    {
                        if (!(isInString || isInChar || isInBlockComment))
                        {
                            ++depth;
                            if (depth == 0)
                            {
                                return(offset);
                            }
                        }
                    }
                    break;
                }
                offset += direction;
            }
            return(-1);
        }
Exemplo n.º 18
0
 internal Task <ParsedDocumentProjection> ParseProjection(Project project, IReadonlyTextDocument data, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ParseProjection(project, data.FileName, data.MimeType, data, cancellationToken));
 }
Exemplo n.º 19
0
 public Task <ParsedDocument> ParseFile(Project project, IReadonlyTextDocument data, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(ParseFile(project, data.FileName, data.MimeType, data, cancellationToken));
 }
Exemplo n.º 20
0
        public override async Task <BraceMatchingResult?> GetMatchingBracesAsync(IReadonlyTextDocument editor, DocumentContext context, int offset, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (context.ParsedDocument == null)
            {
                return(await fallback.GetMatchingBracesAsync(editor, context, offset, cancellationToken));
            }

            var analysisDocument = context.AnalysisDocument;

            if (analysisDocument == null)
            {
                return(null);
            }
            var partialDoc = analysisDocument.WithFrozenPartialSemantics(cancellationToken);
            var root       = await partialDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            if (offset < 0 || root.Span.End <= offset)
            {
                return(null);
            }
            var trivia = root.FindTrivia(offset).GetStructure() as DirectiveTriviaSyntax;

            if (trivia != null && (trivia.IsKind(SyntaxKind.RegionDirectiveTrivia) || trivia.IsKind(SyntaxKind.EndRegionDirectiveTrivia)))
            {
                var matching = trivia.GetMatchingDirective(cancellationToken);
                if (matching == null)
                {
                    return(null);
                }
                if (trivia.IsKind(SyntaxKind.RegionDirectiveTrivia))
                {
                    return(new BraceMatchingResult(
                               new TextSegment(trivia.Span.Start, trivia.Span.Length),
                               new TextSegment(matching.Span.Start, matching.Span.Length),
                               true,
                               BraceMatchingProperties.Hidden));
                }
                else
                {
                    return(new BraceMatchingResult(
                               new TextSegment(matching.Span.Start, matching.Span.Length),
                               new TextSegment(trivia.Span.Start, trivia.Span.Length),
                               false,
                               BraceMatchingProperties.Hidden));
                }
            }

            var token     = root.FindToken(offset);
            var tokenSpan = token.Span;

            if (offset < tokenSpan.Start || offset >= tokenSpan.End)
            {
                return(null);
            }
            for (int i = 0; i < tokenPairs.Length / 2; i++)
            {
                var         open  = tokenPairs [i * 2];
                var         close = tokenPairs [i * 2 + 1];
                SyntaxToken match;
                if (token.IsKind(open))
                {
                    if (TryFindMatchingToken(token, out match, open, close))
                    {
                        return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, tokenSpan.Length), new TextSegment(match.Span.Start, match.Span.Length), true));
                    }
                }
                else if (token.IsKind(close))
                {
                    if (TryFindMatchingToken(token, out match, open, close))
                    {
                        return(new BraceMatchingResult(new TextSegment(match.Span.Start, match.Span.Length), new TextSegment(tokenSpan.Start, tokenSpan.Length), false));
                    }
                }
            }

            if (token.IsKind(SyntaxKind.StringLiteralToken) && token.ToString().EndsWith("\"", StringComparison.Ordinal))
            {
                if (token.IsVerbatimStringLiteral())
                {
                    if (offset <= tokenSpan.Start)
                    {
                        return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 2), new TextSegment(tokenSpan.End - 1, 1), true));
                    }
                    if (offset >= tokenSpan.End - 1)
                    {
                        return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 2), new TextSegment(tokenSpan.End - 1, 1), false));
                    }
                }
                else
                {
                    if (offset <= tokenSpan.Start)
                    {
                        return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), true));
                    }
                    if (offset >= tokenSpan.End - 1)
                    {
                        return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), false));
                    }
                }
            }

            if (token.IsKind(SyntaxKind.CharacterLiteralToken) && token.ToString().EndsWith("\'", StringComparison.Ordinal))
            {
                if (offset <= tokenSpan.Start)
                {
                    return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), true));
                }
                if (offset >= tokenSpan.End - 1)
                {
                    return(new BraceMatchingResult(new TextSegment(tokenSpan.Start, 1), new TextSegment(tokenSpan.End - 1, 1), false));
                }
            }

            return(null);
        }
Exemplo n.º 21
0
 public PaketDependencyRulePart(IReadonlyTextDocument document, int start, int end)
 {
     Text      = document.GetTextAt(start, end - start);
     Offset    = start;
     EndOffset = end;
 }
Exemplo n.º 22
0
 public TestViewContent(IReadonlyTextDocument doc)
 {
     data = TextEditorFactory.CreateNewEditor(doc);
     Contents.Add(data);
     Name = "";
 }
Exemplo n.º 23
0
 ITextEditorImpl ITextEditorFactory.CreateNewEditor(IReadonlyTextDocument document)
 {
     return(new SourceEditorView(document));
 }
Exemplo n.º 24
0
        static List <InsertionPoint> GetInsertionPoints(IReadonlyTextDocument data, ITypeSymbol type, List <InsertionPoint> result, TextSpan sourceSpan, SyntaxReference declaringType)
        {
            var openBraceToken = declaringType.GetSyntax().ChildTokens().FirstOrDefault(t => t.IsKind(SyntaxKind.OpenBraceToken));

            if (!openBraceToken.IsMissing)
            {
                var domLocation = data.OffsetToLocation(openBraceToken.SpanStart);
                result.Add(GetInsertionPosition(data, domLocation.Line, domLocation.Column));
                //			result.Add (GetInsertionPosition (data, realStartLocation.Line, realStartLocation.Column));
                result [0].LineBefore = NewLineInsertion.None;
            }
            foreach (var member in type.GetMembers())
            {
                if (member.IsImplicitlyDeclared || !member.IsDefinedInSource())
                {
                    continue;
                }
                //var domLocation = member.BodyRegion.End;
                foreach (var loc in member.DeclaringSyntaxReferences)
                {
                    if (loc.SyntaxTree.FilePath != declaringType.SyntaxTree.FilePath || !declaringType.Span.Contains(sourceSpan))
                    {
                        continue;
                    }
                    var domLocation = data.OffsetToLocation(loc.Span.End);

                    if (domLocation.Line <= 0)
                    {
                        var lineSegment = data.GetLineByOffset(loc.Span.Start);
                        if (lineSegment == null)
                        {
                            continue;
                        }
                        domLocation = new DocumentLocation(lineSegment.LineNumber, lineSegment.Length + 1);
                    }
                    result.Add(GetInsertionPosition(data, domLocation.Line, domLocation.Column));
                    break;
                }
            }

            result [result.Count - 1].LineAfter = NewLineInsertion.None;
            CheckStartPoint(data, result [0], result.Count == 1);
            if (result.Count > 1)
            {
                result.RemoveAt(result.Count - 1);
                NewLineInsertion insertLine;
                var typeSyntaxReference = type.DeclaringSyntaxReferences.FirstOrDefault(r => r.SyntaxTree.FilePath == data.FileName && r.Span.Contains(sourceSpan));

                var lineBefore = data.GetLineByOffset(typeSyntaxReference.Span.End)?.PreviousLine;
                if (lineBefore != null && lineBefore.Length == lineBefore.GetIndentation(data).Length)
                {
                    insertLine = NewLineInsertion.None;
                }
                else
                {
                    insertLine = NewLineInsertion.Eol;
                }
                // search for line start
                var line = data.GetLineByOffset(typeSyntaxReference.Span.End);
                int col  = typeSyntaxReference.Span.End - line.Offset;
                if (line != null)
                {
                    var lineOffset = line.Offset;
                    col = Math.Min(line.Length, col);
                    while (lineOffset + col - 2 >= 0 && col > 1 && char.IsWhiteSpace(data.GetCharAt(lineOffset + col - 2)))
                    {
                        col--;
                    }
                }
                result.Add(new InsertionPoint(new DocumentLocation(line.LineNumber, col), insertLine, NewLineInsertion.Eol));
                CheckEndPoint(data, result [result.Count - 1], result.Count == 1);
            }

//			foreach (var region in parsedDocument.UserRegions.Where (r => type.BodyRegion.IsInside (r.Region.Begin))) {
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.BeginLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//			}
            result.Sort((left, right) => left.Location.CompareTo(right.Location));
            //foreach (var res in result)
            //	Console.WriteLine (res);
            return(result);
        }
Exemplo n.º 25
0
		ITextEditorImpl ITextEditorFactory.CreateNewEditor (IReadonlyTextDocument document)
		{
			return new SourceEditorView (document);
		}
		static InsertionPoint GetInsertionPosition (IReadonlyTextDocument doc, int line, int column)
		{
			int bodyEndOffset = doc.LocationToOffset (line, column) + 1;
			var curLine = doc.GetLine (line);
			if (curLine != null) {
				if (bodyEndOffset < curLine.Offset + curLine.Length) {
					// case1: positition is somewhere inside the start line
					return new InsertionPoint (new DocumentLocation (line, column + 1), NewLineInsertion.Eol, NewLineInsertion.BlankLine);
				}
			}

			// -> if position is at line end check next line
			var nextLine = doc.GetLine (line + 1);
			if (nextLine == null) // check for 1 line case.
				return new InsertionPoint (new DocumentLocation (line, column + 1), NewLineInsertion.BlankLine, NewLineInsertion.BlankLine);

			for (int i = nextLine.Offset; i < nextLine.EndOffset; i++) {
				char ch = doc.GetCharAt (i);
				if (!char.IsWhiteSpace (ch)) {
					// case2: next line contains non ws chars.
					return new InsertionPoint (new DocumentLocation (line + 1, 1), NewLineInsertion.Eol, NewLineInsertion.BlankLine);
				}
			}

			var nextLine2 = doc.GetLine (line + 2);
			if (nextLine2 != null) {
				for (int i = nextLine2.Offset; i < nextLine2.EndOffset; i++) {
					char ch = doc.GetCharAt (i);
					if (!char.IsWhiteSpace (ch)) {
						// case3: one blank line
						return new InsertionPoint (new DocumentLocation (line + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol);
					}
				}
			}
			// case4: more than 1 blank line
			return new InsertionPoint (new DocumentLocation (line + 1, 1), NewLineInsertion.Eol, NewLineInsertion.None);
		}
		public static IEnumerable<DiffHunk> GetDiff (this IReadonlyTextDocument document, IReadonlyTextDocument changedDocument, DiffOptions options)
		{
			if (document == null)
				throw new ArgumentNullException ("document");
			if (changedDocument == null)
				throw new ArgumentNullException ("changedDocument");
			var codeDictionary = new Dictionary<string, int> ();
			int codeCounter = 0;
			return Diff.GetDiff<int> (GetDiffCodes (document, ref codeCounter, codeDictionary, options),
				GetDiffCodes (changedDocument, ref codeCounter, codeDictionary, options));
		}
		internal static InsertionPoint GetSuitableInsertionPoint (IReadonlyTextDocument data, IEnumerable<InsertionPoint> points, ITypeSymbol cls, Location part, SyntaxNode member)
		{
			switch (member.Kind ()) {
			case SyntaxKind.FieldDeclaration:
				return GetNewFieldPosition (data, points, cls, part);
			case SyntaxKind.MethodDeclaration:
			case SyntaxKind.ConstructorDeclaration:
			case SyntaxKind.DestructorDeclaration:
			case SyntaxKind.OperatorDeclaration:
				return GetNewMethodPosition (data, points, cls, part);
			case SyntaxKind.EventDeclaration:
				return GetNewEventPosition (data, points, cls, part);
			case SyntaxKind.PropertyDeclaration:
				return GetNewPropertyPosition (data, points, cls, part);
			}
			throw new InvalidOperationException ("Invalid member type: " + member.Kind ());
		}
Exemplo n.º 29
0
		public static TextEditor CreateNewEditor (DocumentContext ctx, IReadonlyTextDocument document, TextEditorType textEditorType = TextEditorType.Default)
		{
			var result = CreateNewEditor (document, textEditorType);
			result.InitializeExtensionChain (ctx);
			return result;
		}
		static InsertionPoint GetNewEventPosition (IReadonlyTextDocument data, IEnumerable<InsertionPoint> points, ITypeSymbol cls, Location part)
		{
			if (!cls.GetMembers ().OfType<IEventSymbol> ().Any ()) 
				return GetNewMethodPosition (data, points, cls, part);
			var lastEvent = cls.GetMembers ().OfType<IEventSymbol> ().Last ();
			var begin = data.OffsetToLocation (lastEvent.Locations.First ().SourceSpan.Start);
			return points.FirstOrDefault (p => p.Location > begin);
		}
			public TextLineCollectionWrapper (MonoDevelopSourceText parent, IReadonlyTextDocument textDoc)
			{
				this.parent = parent;
				this.textDoc = textDoc;
			}
		static string [] GetList (IReadonlyTextDocument document, string name)
		{
			return TextEditorFactory.GetSyntaxProperties (document.MimeType, name) ?? emptyList;
		}
		static int GetLastSourceCodePosition (IReadonlyTextDocument document, int lineOffset)
		{
			var line = document.GetLineByOffset (lineOffset);
			bool isInBlockComment = false;
			bool isInLineComment = false;
			int curStringQuote = -1;

			IList<string> lineComments = GetList (document, "LineComment");
			IList<string> blockCommentStarts = GetList (document, "BlockCommentStart");
			IList<string> blockCommentEnds = GetList (document, "BlockCommentEnd");
			IList<string> stringQuotes = GetList (document, "StringQuote");

			for (int i = 0; i < line.Length; i++) {
				int offset = line.Offset + i;
				// check line comments
				if (!isInBlockComment && curStringQuote < 0) {
					isInLineComment = StartsWithListMember (document, lineComments, offset) >= 0;
					if (isInLineComment)
						return System.Math.Min (offset, lineOffset);
				}
				// check block comments
				if (!isInLineComment && curStringQuote < 0) {
					if (!isInBlockComment) {
						isInBlockComment = StartsWithListMember (document, blockCommentStarts, offset) >= 0;
					} else {
						isInBlockComment = StartsWithListMember (document, blockCommentEnds, offset) < 0;
					}
				}

				if (!isInBlockComment && !isInLineComment) {
					int j = StartsWithListMember (document, stringQuotes, offset);
					if (j >= 0) {
						if (curStringQuote >= 0) {
							if (curStringQuote == j)
								curStringQuote = -1;
						} else {
							curStringQuote = j;
						}
					}
				}
			}
			return lineOffset;
		}
		static int SearchMatchingBracketForward (IReadonlyTextDocument document, int offset, char openBracket, char closingBracket, CancellationToken cancellationToken)
		{
			bool isInBlockComment = false;
			bool isInLineComment = false;
			int curStringQuote = -1;

			bool startsInLineComment = StartsInLineComment (document, offset);

			var lineComments = GetList (document, "LineComment");
			var blockCommentStarts = GetList (document, "BlockCommentStart");
			var blockCommentEnds = GetList (document, "BlockCommentEnd");
			var stringQuotes = GetList (document, "StringQuote");
			int depth = -1;
			while (offset >= 0 && offset < document.Length) {
				if (offset % 100 == 0 && cancellationToken.IsCancellationRequested)
					return -1;
				if (curStringQuote < 0) {
					// check line comments
					if (!isInBlockComment && !isInLineComment)
						isInLineComment = StartsWithListMember (document, lineComments, offset) >= 0;

					// check block comments
					if (!isInLineComment) {
						if (!isInBlockComment) {
							isInBlockComment = StartsWithListMember (document, blockCommentStarts, offset) >= 0;
						} else {
							isInBlockComment = StartsWithListMember (document, blockCommentEnds, offset) < 0;
						}
					}
				}

				if (!isInBlockComment && !isInLineComment) {
					int i = StartsWithListMember (document, stringQuotes, offset);
					if (i >= 0) {
						if (curStringQuote >= 0) {
							if (curStringQuote == i)
								curStringQuote = -1;
						} else {
							curStringQuote = i;
						}
					}
				}

				char ch = document.GetCharAt (offset);
				switch (ch) {
				case '\n':
				case '\r':
					if (startsInLineComment)
						return -1;
					isInLineComment = false;
					break;
				default:
					if (ch == closingBracket) {
						if (!(isInLineComment || curStringQuote >= 0 || isInBlockComment))
							--depth;
					} else if (ch == openBracket) {
						if (!(isInLineComment || curStringQuote >= 0 || isInBlockComment)) {
							++depth;
							if (depth == 0)
								return offset;
						}
					}
					break;
				}
				offset++;
			}
			return -1;
		}
Exemplo n.º 35
0
 public static List <InsertionPoint> GetInsertionPoints(IReadonlyTextDocument data, SemanticModel model, ITypeSymbol type, Location location)
 {
     return(GetInsertionPoints(data, model, type, location.SourceSpan.Start));
 }
Exemplo n.º 36
0
        static bool IsBlankLine(IReadonlyTextDocument doc, int i)
        {
            var line = doc.GetLine(i);

            return(line.Length == line.GetIndentation(doc).Length);
        }
		static bool IsSemicolonalreadyPlaced (IReadonlyTextDocument data, int caretOffset)
		{
			for (int pos2 = caretOffset - 1; pos2-- > 0;) {
				var ch2 = data.GetCharAt (pos2);
				if (ch2 == ';') {
					return true;
				}
				if (!char.IsWhiteSpace (ch2))
					return false;
			}
			return false;
		}
		static bool IsBlankLine (IReadonlyTextDocument doc, int i)
		{
			var line = doc.GetLine (i);
			return line.Length == line.GetIndentation (doc).Length;
		}
		static List<InsertionPoint> GetInsertionPoints (IReadonlyTextDocument data, ITypeSymbol type, List<InsertionPoint> result, TextSpan sourceSpan, SyntaxReference declaringType)
		{
			var openBraceToken = declaringType.GetSyntax ().ChildTokens ().FirstOrDefault (t => t.IsKind (SyntaxKind.OpenBraceToken));
			if (!openBraceToken.IsMissing) {
				var domLocation = data.OffsetToLocation (openBraceToken.SpanStart);
				result.Add (GetInsertionPosition (data, domLocation.Line, domLocation.Column));
				//			result.Add (GetInsertionPosition (data, realStartLocation.Line, realStartLocation.Column));
				result [0].LineBefore = NewLineInsertion.None;
			}
			foreach (var member in type.GetMembers ()) {
				if (member.IsImplicitlyDeclared || !member.IsDefinedInSource ())
					continue;
				//var domLocation = member.BodyRegion.End;
				foreach (var loc in member.DeclaringSyntaxReferences) {
					if (loc.SyntaxTree.FilePath != declaringType.SyntaxTree.FilePath || !declaringType.Span.Contains (sourceSpan))
						continue;
					var domLocation = data.OffsetToLocation (loc.Span.End);

					if (domLocation.Line <= 0) {
						var lineSegment = data.GetLineByOffset (loc.Span.Start);
						if (lineSegment == null)
							continue;
						domLocation = new DocumentLocation (lineSegment.LineNumber, lineSegment.Length + 1);
					}
					result.Add (GetInsertionPosition (data, domLocation.Line, domLocation.Column));
					break;
				}
			}

			result [result.Count - 1].LineAfter = NewLineInsertion.None;
			CheckStartPoint (data, result [0], result.Count == 1);
			if (result.Count > 1) {
				result.RemoveAt (result.Count - 1); 
				NewLineInsertion insertLine;
				var typeSyntaxReference = type.DeclaringSyntaxReferences.FirstOrDefault (r => r.Span.Contains (sourceSpan));

				var lineBefore = data.GetLineByOffset (typeSyntaxReference.Span.End).PreviousLine;
				if (lineBefore != null && lineBefore.Length == lineBefore.GetIndentation (data).Length) {
					insertLine = NewLineInsertion.None;
				} else {
					insertLine = NewLineInsertion.Eol;
				}
				// search for line start
				var line = data.GetLineByOffset (typeSyntaxReference.Span.End);
				int col = typeSyntaxReference.Span.End - line.Offset;
				if (line != null) {
					var lineOffset = line.Offset;
					col = Math.Min (line.Length, col);
					while (lineOffset + col - 2 >= 0 && col > 1 && char.IsWhiteSpace (data.GetCharAt (lineOffset + col - 2)))
						col--;
				}
				result.Add (new InsertionPoint (new DocumentLocation (line.LineNumber, col), insertLine, NewLineInsertion.Eol));
				CheckEndPoint (data, result [result.Count - 1], result.Count == 1);
			}

//			foreach (var region in parsedDocument.UserRegions.Where (r => type.BodyRegion.IsInside (r.Region.Begin))) {
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.BeginLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//				result.Add (new InsertionPoint (new DocumentLocation (region.Region.EndLine + 1, 1), NewLineInsertion.Eol, NewLineInsertion.Eol));
//			}
			result.Sort ((left, right) => left.Location.CompareTo (right.Location));
			//foreach (var res in result)
			//	Console.WriteLine (res);
			return result;
		}
Exemplo n.º 40
0
 public static List <InsertionPoint> GetInsertionPoints(IReadonlyTextDocument data, ParsedDocument parsedDocument, ITypeSymbol type, Location location)
 {
     return(GetInsertionPoints(data, parsedDocument, type, location.SourceSpan.Start));
 }
		public static bool GuessSemicolonInsertionOffset (IReadonlyTextDocument data, MonoDevelop.Core.Text.ISegment curLine, int caretOffset, out int outOffset)
		{
			int lastNonWsOffset = caretOffset;
			char lastNonWsChar = '\0';
			outOffset = caretOffset;

			int max = curLine.EndOffset;

			int end = caretOffset;
			while (end > 1 && char.IsWhiteSpace (data.GetCharAt (end)))
				end--;
			int end2 = end;
			while (end2 > 1 && char.IsLetter (data.GetCharAt (end2 - 1)))
				end2--;
			if (end != end2) {
				string token = data.GetTextBetween (end2, end + 1);
				// guess property context
				if (token == "get" || token == "set")
					return false;
			}

			var offset = curLine.Offset;
			string lineText = data.GetTextAt (caretOffset, max - caretOffset);
			var lexer = new ICSharpCode.NRefactory.CSharp.Completion.CSharpCompletionEngineBase.MiniLexer (lineText);
			lexer.Parse ((ch, i) => {
				if (lexer.IsInSingleComment || lexer.IsInMultiLineComment)
					return true;
				if (ch == '}' && lexer.IsFistNonWs && !IsSemicolonalreadyPlaced (data, caretOffset)) {
					lastNonWsChar = ';';
					return true;
				}
				if (!char.IsWhiteSpace (ch)) {
					lastNonWsOffset = caretOffset + i;
					lastNonWsChar = ch;
				}
				return false;
			}); 
			// if the line ends with ';' the line end is not the correct place for a new semicolon.
			if (lastNonWsChar == ';')
				return false;
			outOffset = lastNonWsOffset;
			return true;
		}
		public abstract Task<BraceMatchingResult?> GetMatchingBracesAsync(IReadonlyTextDocument editor, DocumentContext context, int offset, CancellationToken cancellationToken = default(CancellationToken));
Exemplo n.º 43
0
		public SourceEditorView (IReadonlyTextDocument document = null)
		{
			Counters.LoadedEditors++;

			widget = new SourceEditorWidget (this);
			if (document != null) {
				var textDocument = document as TextDocument;
				if (textDocument != null) {
					widget.TextEditor.Document = textDocument;
				} else {
					widget.TextEditor.Document.Text = document.Text;
				}
			}

			widget.TextEditor.Document.TextReplaced += HandleTextReplaced;
			widget.TextEditor.Document.LineChanged += HandleLineChanged;
			widget.TextEditor.Document.LineInserted += HandleLineChanged;
			widget.TextEditor.Document.LineRemoved += HandleLineChanged;

			widget.TextEditor.Document.BeginUndo += HandleBeginUndo; 
			widget.TextEditor.Document.EndUndo += HandleEndUndo;

			widget.TextEditor.Document.TextReplacing += OnTextReplacing;
			widget.TextEditor.Document.TextReplaced += OnTextReplaced;
			widget.TextEditor.Document.ReadOnlyCheckDelegate = CheckReadOnly;
			widget.TextEditor.TextViewMargin.LineShown += TextViewMargin_LineShown;
			//			widget.TextEditor.Document.DocumentUpdated += delegate {
			//				this.IsDirty = Document.IsDirty;
			//			};
			
			widget.TextEditor.Caret.PositionChanged += HandlePositionChanged; 
			widget.TextEditor.IconMargin.ButtonPressed += OnIconButtonPress;

			ClipbardRingUpdated += UpdateClipboardRing;
			
			TextEditorService.FileExtensionAdded += HandleFileExtensionAdded;
			TextEditorService.FileExtensionRemoved += HandleFileExtensionRemoved;

			breakpoints = DebuggingService.Breakpoints;
			DebuggingService.DebugSessionStarted += OnDebugSessionStarted;
			DebuggingService.StoppedEvent += HandleTargetExited;
			DebuggingService.ExecutionLocationChanged += OnExecutionLocationChanged;
			DebuggingService.CurrentFrameChanged += OnCurrentFrameChanged;
			DebuggingService.StoppedEvent += OnCurrentFrameChanged;
			DebuggingService.ResumedEvent += OnCurrentFrameChanged;
			breakpoints.BreakpointAdded += OnBreakpointAdded;
			breakpoints.BreakpointRemoved += OnBreakpointRemoved;
			breakpoints.BreakpointStatusChanged += OnBreakpointStatusChanged;
			breakpoints.BreakpointModified += OnBreakpointStatusChanged;
			DebuggingService.PinnedWatches.WatchAdded += OnWatchAdded;
			DebuggingService.PinnedWatches.WatchRemoved += OnWatchRemoved;
			DebuggingService.PinnedWatches.WatchChanged += OnWatchChanged;
			
			TaskService.Errors.TasksAdded += UpdateTasks;
			TaskService.Errors.TasksRemoved += UpdateTasks;
			TaskService.JumpedToTask += HandleTaskServiceJumpedToTask;
			IdeApp.Preferences.ShowMessageBubbles.Changed += HandleIdeAppPreferencesShowMessageBubblesChanged;
			TaskService.TaskToggled += HandleErrorListPadTaskToggled;
			widget.TextEditor.Options.Changed += HandleWidgetTextEditorOptionsChanged;
			IdeApp.Preferences.DefaultHideMessageBubbles.Changed += HandleIdeAppPreferencesDefaultHideMessageBubblesChanged;
			Document.AddAnnotation (this);
			if (document != null) {
				Document.MimeType = document.MimeType;
				Document.FileName = document.FileName;
			}
			FileRegistry.Add (this);
		}
Exemplo n.º 44
0
        public async Task CreateTextDocumentAsync(string text)
        {
            var textSource = new StringTextSource(text);

            document = await SimpleReadonlyDocument.CreateReadonlyDocumentAsync(textSource);
        }