Esempio n. 1
0
 public static DefinitionItem Create(
     ImmutableArray<string> tags,
     ImmutableArray<TaggedText> displayParts,
     DocumentLocation sourceLocation,
     bool displayIfNoReferences = true)
 {
     return Create(tags, displayParts, ImmutableArray.Create(sourceLocation), displayIfNoReferences);
 }
 public DocumentLocationDefinitionItem(
     ImmutableArray<string> tags,
     ImmutableArray<TaggedText> displayParts,
     ImmutableArray<DocumentLocation> additionalLocations,
     bool displayIfNoReferences,
     DocumentLocation location)
     : base(tags, displayParts, 
           ImmutableArray.Create(new TaggedText(TextTags.Text, location.Document.Project.Name)),
           additionalLocations, displayIfNoReferences)
 {
     _location = location;
 }
		public bool FindFirstBracket (DocumentLocation currentLocation)
		{
			if (Document == null || Document.LineCount < Region.BeginLine)
				return false;

			int firstBracketPosition = Document.GetTextBetween (Region.Begin, currentLocation).IndexOf ('{');
			if (firstBracketPosition == -1)
				return false;

			int beginOffset = Document.LocationToOffset (Region.Begin);
			FirstBracket = Document.OffsetToLocation (beginOffset + firstBracketPosition);
			return true;
		}
		public bool IsEndingBracket (DocumentLocation bracketLocation)
		{
			// If document isn't entirely loaded
			if (Document == null || Document.LineCount < Region.BeginLine)
				return false;

			if (!FirstBracket.HasValue && !FindFirstBracket (bracketLocation))
				return false;

			int firstBracketOffset = Document.LocationToOffset (FirstBracket.Value);
			int currentBracketOffset = Document.LocationToOffset (bracketLocation);

			return SimpleBracketMatcher.GetMatchingBracketOffset (Document, firstBracketOffset) == currentBracketOffset;
		}
		string GetIndentationString (DocumentLocation loc)
		{
			var line = data.GetLine (loc.Line);
			if (line == null)
				return "";
			// Get context to the end of the line w/o changing the main engine's state
			var offset = line.Offset;
			string curIndent = line.GetIndentation (data);
			try {
				stateTracker.Update (data, Math.Min (data.Length, offset + Math.Min (line.Length, loc.Column - 1)));
				int nlwsp = curIndent.Length;
				if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < line.LengthIncludingDelimiter && data.GetCharAt (offset + nlwsp) == '*'))
					return stateTracker.ThisLineIndent;
			} catch (Exception e) {
				LoggingService.LogError ("Error while indenting at "+ loc, e); 
			}
			return curIndent;
		}
            public DocumentLocationEntry(
                TableDataSourceFindReferencesContext context,
                VisualStudioWorkspaceImpl workspace,
                RoslynDefinitionBucket definitionBucket,
                DocumentLocation documentLocation,
                bool isDefinitionLocation,
                Guid projectGuid,
                SourceText sourceText,
                TaggedTextAndHighlightSpan taggedLineParts)
                : base(definitionBucket)
            {
                _context = context;

                _workspace = workspace;
                _documentLocation = documentLocation;
                _isDefinitionLocation = isDefinitionLocation;
                _boxedProjectGuid = projectGuid;
                _sourceText = sourceText;
                _taggedLineParts = taggedLineParts;
            }
Esempio n. 7
0
 public DebuggerRunningEventArgs(DocumentLocation location, bool running)
 {
     Location = location;
     Running  = running;
 }
Esempio n. 8
0
 public DocumentLocation GetDocumentLocation()
 {
     DocumentLocation documentLocation = null;
     Program.MainWindow.Invoke(new Action(() =>
     {
         if (!_skylineWindow.SelectedPath.Equals(new IdentityPath(SequenceTree.NODE_INSERT_ID)))
         {
             documentLocation = new DocumentLocation(_skylineWindow.SequenceTree.SelectedPath.ToGlobalIndexList());
             if (_skylineWindow.Document.Settings.HasResults)
             {
                 var chromatogramSet =
                     _skylineWindow.Document.Settings.MeasuredResults.Chromatograms[
                         _skylineWindow.SelectedResultsIndex];
                 documentLocation = documentLocation.SetChromFileId(
                     chromatogramSet.MSDataFileInfos.First().FileId.GlobalIndex);
             }
         }
     }));
     return documentLocation;
 }
		public InsertionPoint (DocumentLocation location, NewLineInsertion lineBefore, NewLineInsertion lineAfter)
		{
			this.Location = location;
			this.LineBefore = lineBefore;
			this.LineAfter = lineAfter;
		}
Esempio n. 10
0
        public int GetVirtualIndentationColumn (DocumentLocation loc)
		{
			return IndentationTracker.GetVirtualIndentationColumn (loc.Line, loc.Column);
		}
Esempio n. 11
0
		public XAttribute (DocumentLocation start, XName name, string value) : base (start)
		{
			this.Name = name;
			this.Value = value;
		}
 public TaskInfo(string name, DisplayText description, string typeName, string assemblyName, string assemblyFile, string declaredInFile, DocumentLocation declaredAtLocation)
     : base(name, description)
 {
     TypeName           = typeName;
     AssemblyName       = assemblyName;
     AssemblyFile       = assemblyFile;
     DeclaredInFile     = declaredInFile;
     DeclaredAtLocation = declaredAtLocation;
 }
Esempio n. 13
0
        static IEnumerable <PossibleNamespace> GetPossibleNamespaces(Document doc, AstNode node, ResolveResult resolveResult, DocumentLocation location)
        {
            var unit = doc.ParsedDocument.GetAst <SyntaxTree> ();

            if (unit == null)
            {
                yield break;
            }

            int  tc                    = GetTypeParameterCount(node);
            var  attribute             = unit.GetNodeAt <ICSharpCode.NRefactory.CSharp.Attribute> (location);
            bool isInsideAttributeType = attribute != null && attribute.Type.Contains(location);

            var compilations = new List <Tuple <ICompilation, MonoDevelop.Projects.ProjectReference> > ();

            compilations.Add(Tuple.Create(doc.Compilation, (MonoDevelop.Projects.ProjectReference)null));
            var referencedItems = IdeApp.Workspace != null?doc.Project.GetReferencedItems(IdeApp.Workspace.ActiveConfiguration).ToList() : (IEnumerable <SolutionItem>) new SolutionItem[0];

            var solution = doc.Project != null ? doc.Project.ParentSolution : null;

            if (solution != null)
            {
                foreach (var project in solution.GetAllProjects())
                {
                    if (project == doc.Project || referencedItems.Contains(project))
                    {
                        continue;
                    }
                    var comp = TypeSystemService.GetCompilation(project);
                    if (comp == null)
                    {
                        continue;
                    }
                    compilations.Add(Tuple.Create(comp, new MonoDevelop.Projects.ProjectReference(project)));
                }
            }

            var netProject = doc.Project as DotNetProject;

            if (netProject == null)
            {
                yield break;
            }
            var frameworkLookup = TypeSystemService.GetFrameworkLookup(netProject);

            if (resolveResult is UnknownMemberResolveResult)
            {
                var umResult = (UnknownMemberResolveResult)resolveResult;
                foreach (var r in frameworkLookup.LookupExtensionMethod(umResult.MemberName))
                {
                    var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName(r.FullName, r.Package, netProject.TargetFramework);
                    if (systemAssembly == null)
                    {
                        continue;
                    }
                    compilations.Add(Tuple.Create(TypeSystemService.GetCompilation(systemAssembly, doc.Compilation), new MonoDevelop.Projects.ProjectReference(systemAssembly)));
                }
            }
            bool foundIdentifier = false;
            var  lookup          = new MemberLookup(null, doc.Compilation.MainAssembly);

            foreach (var comp in compilations)
            {
                var compilation       = comp.Item1;
                var requiredReference = comp.Item2;
                if (resolveResult is AmbiguousTypeResolveResult)
                {
                    if (compilation != doc.Compilation)
                    {
                        continue;
                    }
                    var aResult = resolveResult as AmbiguousTypeResolveResult;
                    var file    = doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile;
                    var scope   = file.GetUsingScope(location).Resolve(compilation);
                    while (scope != null)
                    {
                        foreach (var u in scope.Usings)
                        {
                            foreach (var typeDefinition in u.Types)
                            {
                                if (typeDefinition.Name == aResult.Type.Name &&
                                    typeDefinition.TypeParameterCount == tc &&
                                    lookup.IsAccessible(typeDefinition, false))
                                {
                                    yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));
                                }
                            }
                        }
                        scope = scope.Parent;
                    }
                }

                var allTypes = compilation == doc.Compilation ? compilation.GetAllTypeDefinitions() : compilation.MainAssembly.GetAllTypeDefinitions();
                if (resolveResult is UnknownIdentifierResolveResult)
                {
                    var    uiResult = resolveResult as UnknownIdentifierResolveResult;
                    string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
                    foreach (var typeDefinition in allTypes)
                    {
                        if (typeDefinition.Name == possibleAttributeName && typeDefinition.TypeParameterCount == tc &&
                            lookup.IsAccessible(typeDefinition, false))
                        {
                            if (typeDefinition.DeclaringTypeDefinition != null)
                            {
                                var builder = new TypeSystemAstBuilder(new CSharpResolver(doc.Compilation));
                                foundIdentifier = true;
                                yield return(new PossibleNamespace(builder.ConvertType(typeDefinition.DeclaringTypeDefinition).ToString(), false, requiredReference));
                            }
                            else
                            {
                                foundIdentifier = true;
                                yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));
                            }
                        }
                    }
                }

                if (resolveResult is UnknownMemberResolveResult)
                {
                    var    umResult = (UnknownMemberResolveResult)resolveResult;
                    string possibleAttributeName = isInsideAttributeType ? umResult.MemberName + "Attribute" : umResult.MemberName;
                    foreach (var typeDefinition in allTypes.Where(t => t.HasExtensionMethods))
                    {
                        foreach (var method in typeDefinition.Methods.Where(m => m.IsExtensionMethod && m.Name == possibleAttributeName))
                        {
                            IType[] inferredTypes;
                            if (CSharpResolver.IsEligibleExtensionMethod(
                                    compilation.Import(umResult.TargetType),
                                    method,
                                    true,
                                    out inferredTypes
                                    ))
                            {
                                yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));

                                goto skipType;
                            }
                        }
skipType:
                        ;
                    }
                }

                if (resolveResult is ErrorResolveResult)
                {
                    var identifier = unit != null?unit.GetNodeAt <Identifier> (location) : null;

                    if (identifier != null)
                    {
                        var uiResult = resolveResult as UnknownIdentifierResolveResult;
                        if (uiResult != null)
                        {
                            string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
                            foreach (var typeDefinition in allTypes)
                            {
                                if ((identifier.Name == possibleAttributeName) &&
                                    typeDefinition.TypeParameterCount == tc &&
                                    lookup.IsAccessible(typeDefinition, false))
                                {
                                    yield return(new PossibleNamespace(typeDefinition.Namespace, true, requiredReference));
                                }
                            }
                        }
                    }
                }
            }
            // Try to search framework types
            if (!foundIdentifier && resolveResult is UnknownIdentifierResolveResult)
            {
                var    uiResult = resolveResult as UnknownIdentifierResolveResult;
                string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : uiResult.Identifier;
                foreach (var r in frameworkLookup.LookupIdentifier(possibleAttributeName, tc))
                {
                    var systemAssembly = netProject.AssemblyContext.GetAssemblyFromFullName(r.FullName, r.Package, netProject.TargetFramework);
                    if (systemAssembly == null)
                    {
                        continue;
                    }
                    yield return(new PossibleNamespace(r.Namespace, true, new MonoDevelop.Projects.ProjectReference(systemAssembly)));
                }
            }
        }
Esempio n. 14
0
        public override TooltipItem GetItem(TextEditor editor, int offset)
        {
            if (offset >= editor.Document.TextLength)
            {
                return(null);
            }

            if (!DebuggingService.IsDebugging || DebuggingService.IsRunning)
            {
                return(null);
            }

            StackFrame frame = DebuggingService.CurrentFrame;

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

            var ed = (ExtensibleTextEditor)editor;

            string expression = null;
            int    startOffset = 0, length = 0;

            if (ed.IsSomethingSelected && offset >= ed.SelectionRange.Offset && offset <= ed.SelectionRange.EndOffset)
            {
                expression  = ed.SelectedText;
                startOffset = ed.SelectionRange.Offset;
                length      = ed.SelectionRange.Length;
            }
            else
            {
                DomRegion     expressionRegion;
                ResolveResult res = ed.GetLanguageItem(offset, out expressionRegion);

                if (res == null || res.IsError || res.GetType() == typeof(ResolveResult))
                {
                    return(null);
                }

                //Console.WriteLine ("res is a {0}", res.GetType ().Name);

                if (expressionRegion.IsEmpty)
                {
                    return(null);
                }

                if (res is NamespaceResolveResult ||
                    res is ConversionResolveResult ||
                    res is ForEachResolveResult ||
                    res is TypeIsResolveResult ||
                    res is TypeOfResolveResult ||
                    res is ErrorResolveResult)
                {
                    return(null);
                }

                var start = new DocumentLocation(expressionRegion.BeginLine, expressionRegion.BeginColumn);
                var end   = new DocumentLocation(expressionRegion.EndLine, expressionRegion.EndColumn);

                startOffset = editor.Document.LocationToOffset(start);
                int endOffset = editor.Document.LocationToOffset(end);
                length = endOffset - startOffset;

                if (res is LocalResolveResult)
                {
                    var lr = (LocalResolveResult)res;

                    // Use the start and end offsets of the variable region so that we get the "@" in variable names like "@class"
                    start       = new DocumentLocation(lr.Variable.Region.BeginLine, lr.Variable.Region.BeginColumn);
                    end         = new DocumentLocation(lr.Variable.Region.EndLine, lr.Variable.Region.EndColumn);
                    startOffset = editor.Document.LocationToOffset(start);
                    endOffset   = editor.Document.LocationToOffset(end);

                    expression = ed.GetTextBetween(startOffset, endOffset).Trim();

                    // Note: When the LocalResolveResult is a parameter, the Variable.Region includes the type
                    if (lr.IsParameter)
                    {
                        int index = IndexOfLastWhiteSpace(expression);
                        if (index != -1)
                        {
                            expression = expression.Substring(index + 1);
                        }
                    }

                    length = expression.Length;
                }
                else if (res is InvocationResolveResult)
                {
                    var ir = (InvocationResolveResult)res;

                    if (ir.Member.Name != ".ctor")
                    {
                        return(null);
                    }

                    expression = ir.Member.DeclaringType.FullName;
                }
                else if (res is MemberResolveResult)
                {
                    var mr = (MemberResolveResult)res;

                    if (mr.TargetResult == null)
                    {
                        // User is hovering over a member definition...

                        if (mr.Member is IProperty)
                        {
                            // Visual Studio will evaluate Properties if you hover over their definitions...
                            var prop = (IProperty)mr.Member;

                            if (prop.CanGet)
                            {
                                if (prop.IsStatic)
                                {
                                    expression = prop.FullName;
                                }
                                else
                                {
                                    expression = prop.Name;
                                }
                            }
                            else
                            {
                                return(null);
                            }
                        }
                        else if (mr.Member is IField)
                        {
                            var field = (IField)mr.Member;

                            if (field.IsStatic)
                            {
                                expression = field.FullName;
                            }
                            else
                            {
                                expression = field.Name;
                            }
                        }
                        else
                        {
                            return(null);
                        }
                    }

                    // If the TargetResult is not null, then treat it like any other ResolveResult.
                }
                else if (res is ConstantResolveResult)
                {
                    // Fall through...
                }
                else if (res is ThisResolveResult)
                {
                    // Fall through...
                }
                else if (res is TypeResolveResult)
                {
                    // Fall through...
                }
                else
                {
                    return(null);
                }

                if (expression == null)
                {
                    expression = ed.GetTextBetween(start, end);
                }
            }

            if (string.IsNullOrEmpty(expression))
            {
                return(null);
            }

            ObjectValue val;

            if (!cachedValues.TryGetValue(expression, out val))
            {
                val = frame.GetExpressionValue(expression, true);
                cachedValues [expression] = val;
            }

            if (val == null || val.IsUnknown || val.IsNotSupported)
            {
                return(null);
            }

            val.Name = expression;

            return(new TooltipItem(val, startOffset, length));
        }
Esempio n. 15
0
        void ScrollToRequestedCaretLocation(Document doc, FileOpenInformation info)
        {
            if (info.Line < 1 && info.Offset < 0)
            {
                return;
            }

            if (editorOperationsFactoryService == null)
            {
                editorOperationsFactoryService = CompositionManager.Instance.GetExportedValue <IEditorOperationsFactoryService> ();
            }

            FileSettingsStore.Remove(doc.FileName);
            doc.DisableAutoScroll();

            doc.RunWhenContentAdded <ITextView> (textView => {
                var ipos = doc.Editor;
                if (ipos != null)
                {
                    var loc = new DocumentLocation(info.Line, info.Column >= 1 ? info.Column : 1);
                    if (info.Offset >= 0)
                    {
                        loc = ipos.OffsetToLocation(info.Offset);
                    }
                    if (loc.IsEmpty)
                    {
                        return;
                    }
                    ipos.SetCaretLocation(loc, info.Options.HasFlag(OpenDocumentOptions.HighlightCaretLine), info.Options.HasFlag(OpenDocumentOptions.CenterCaretLine));
                }
                else
                {
                    var offset = info.Offset;
                    if (offset < 0)
                    {
                        try {
                            if (info.Line - 1 > (textView?.TextSnapshot?.LineCount ?? 0))
                            {
                                LoggingService.LogInfo($"ScrollToRequestedCaretLocation line was over the snapshot's line count. "
                                                       + $"Called with {info.Line - 1} but line count was {textView?.TextSnapshot?.LineCount}");
                                return;
                            }

                            var line = textView.TextSnapshot.GetLineFromLineNumber(info.Line - 1);
                            if (info.Column >= 1)
                            {
                                offset = line.Start + Math.Min(info.Column - 1, line.Length);
                            }
                            else
                            {
                                offset = line.Start;
                            }
                        } catch (ArgumentException ae) {
                            LoggingService.LogError($"Calling GetLineFromLineNumber resulted in an argument exception."
                                                    + $"We tried calling with line number: {info.Line - 1}", ae);
                            // we should just abort in this case, since we can't really do anything
                            return;
                        }
                    }
                    if (editorOperationsFactoryService != null)
                    {
                        var editorOperations = editorOperationsFactoryService.GetEditorOperations(textView);
                        var point            = new VirtualSnapshotPoint(textView.TextSnapshot, offset);
                        editorOperations.SelectAndMoveCaret(point, point, TextSelectionMode.Stream, EnsureSpanVisibleOptions.AlwaysCenter);
                    }
                    else
                    {
                        LoggingService.LogError("Missing editor operations");
                    }
                }
            });

/*			var navigator = (ISourceFileNavigator)newContent.GetContent (typeof (ISourceFileNavigator));
 *                      if (fileInfo.Offset >= 0)
 *                              navigator.JumpToOffset (fileInfo.Offset);
 *                      else
 *                              navigator.JumpToLine (fileInfo.Line, fileInfo.Column);*/
        }
        void CreateSmartTag(List <CodeAction> fixes, DocumentLocation loc)
        {
            Fixes = fixes;
            if (!QuickTaskStrip.EnableFancyFeatures)
            {
                RemoveWidget();
                return;
            }
            var editor = document.Editor;

            if (editor == null || editor.Parent == null || !editor.Parent.IsRealized)
            {
                RemoveWidget();
                return;
            }
            if (document.ParsedDocument == null || document.ParsedDocument.IsInvalid)
            {
                RemoveWidget();
                return;
            }

            var container = editor.Parent;

            if (container == null)
            {
                RemoveWidget();
                return;
            }
            bool             first            = true;
            DocumentLocation smartTagLocBegin = loc;

            foreach (var fix in fixes)
            {
                if (fix.DocumentRegion.IsEmpty)
                {
                    continue;
                }
                if (first || loc < fix.DocumentRegion.Begin)
                {
                    smartTagLocBegin = fix.DocumentRegion.Begin;
                }
                first = false;
            }
            if (smartTagLocBegin.Line != loc.Line)
            {
                smartTagLocBegin = new DocumentLocation(loc.Line, 1);
            }
            // got no fix location -> try to search word start
            if (first)
            {
                int offset = document.Editor.LocationToOffset(smartTagLocBegin);
                while (offset > 0)
                {
                    char ch = document.Editor.GetCharAt(offset - 1);
                    if (!char.IsLetterOrDigit(ch) && ch != '_')
                    {
                        break;
                    }
                    offset--;
                }
                smartTagLocBegin = document.Editor.OffsetToLocation(offset);
            }

            if (currentSmartTag != null && currentSmartTagBegin == smartTagLocBegin)
            {
                currentSmartTag.fixes = fixes;
                return;
            }
            currentSmartTagBegin = smartTagLocBegin;

            RemoveWidget();
            var line = document.Editor.GetLine(smartTagLocBegin.Line);

            currentSmartTag = new SmartTagMarker((line.NextLine ?? line).Offset, this, fixes, smartTagLocBegin);
            document.Editor.Document.AddMarker(currentSmartTag);
        }
 public SmartTagMarker(int offset, CodeActionEditorExtension codeActionEditorExtension, List <CodeAction> fixes, DocumentLocation loc) : base(offset, 0)
 {
     this.codeActionEditorExtension = codeActionEditorExtension;
     this.fixes = fixes;
     this.loc   = loc;
 }
        internal static async Task UpdateFoldings(TextEditor Editor, ParsedDocument parsedDocument, DocumentLocation caretLocation, bool firstTime = false, CancellationToken token = default(CancellationToken))
        {
            if (parsedDocument == null || !Editor.Options.ShowFoldMargin)
            {
                return;
            }
            // don't update parsed documents that contain errors - the foldings from there may be invalid.
            if (await parsedDocument.HasErrorsAsync(token))
            {
                return;
            }

            try {
                var foldSegments = new List <IFoldSegment> ();

                foreach (FoldingRegion region in await parsedDocument.GetFoldingsAsync(token))
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    var  type      = FoldingType.Unknown;
                    bool setFolded = false;
                    bool folded    = false;
                    //decide whether the regions should be folded by default
                    switch (region.Type)
                    {
                    case FoldType.Member:
                        type = FoldingType.TypeMember;
                        break;

                    case FoldType.Type:
                        type = FoldingType.TypeDefinition;
                        break;

                    case FoldType.UserRegion:
                        type      = FoldingType.Region;
                        setFolded = DefaultSourceEditorOptions.Instance.DefaultRegionsFolding;
                        folded    = true;
                        break;

                    case FoldType.Comment:
                        type      = FoldingType.Comment;
                        setFolded = DefaultSourceEditorOptions.Instance.DefaultCommentFolding;
                        folded    = true;
                        break;

                    case FoldType.CommentInsideMember:
                        type      = FoldingType.Comment;
                        setFolded = DefaultSourceEditorOptions.Instance.DefaultCommentFolding;
                        folded    = false;
                        break;

                    case FoldType.Undefined:
                        setFolded = true;
                        folded    = region.IsFoldedByDefault;
                        break;
                    }
                    var start  = Editor.LocationToOffset(region.Region.Begin);
                    var end    = Editor.LocationToOffset(region.Region.End);
                    var marker = Editor.CreateFoldSegment(start, end - start);
                    foldSegments.Add(marker);
                    marker.CollapsedText = region.Name;
                    marker.FoldingType   = type;
                    //and, if necessary, set its fold state
                    if (marker != null && setFolded && firstTime)
                    {
                        // only fold on document open, later added folds are NOT folded by default.
                        marker.IsCollapsed = folded;
                        continue;
                    }
                    if (marker != null && region.Region.Contains(caretLocation.Line, caretLocation.Column))
                    {
                        marker.IsCollapsed = false;
                    }
                }
                if (firstTime)
                {
                    Editor.SetFoldings(foldSegments);
                }
                else
                {
                    Application.Invoke(delegate {
                        if (!token.IsCancellationRequested)
                        {
                            Editor.SetFoldings(foldSegments);
                        }
                    });
                }
            } catch (OperationCanceledException) {
            } catch (Exception ex) {
                LoggingService.LogError("Unhandled exception in ParseInformationUpdaterWorkerThread", ex);
            }
        }
Esempio n. 19
0
 protected int ConvertLocation(DocumentLocation location) => TextDocument.LocationToOffset(location);
 public static TextLocation Convert(this DocumentLocation location)
 {
     return(new TextLocation(location.Line, location.Column));
 }
Esempio n. 21
0
		async Task UpdateFoldings (ParsedDocument parsedDocument, DocumentLocation caretLocation, bool firstTime = false, CancellationToken token = default (CancellationToken))
		{
			if (parsedDocument == null || !textEditor.Options.ShowFoldMargin || isDisposed)
				return;
			// don't update parsed documents that contain errors - the foldings from there may be invalid.
			if (parsedDocument.HasErrors)
				return;
			
			try {
				var foldSegments = new List<IFoldSegment> ();

				foreach (FoldingRegion region in await parsedDocument.GetFoldingsAsync(token)) {
					if (token.IsCancellationRequested)
						return;
					var type = FoldingType.Unknown;
					bool setFolded = false;
					bool folded = false;
					//decide whether the regions should be folded by default
					switch (region.Type) {
					case FoldType.Member:
						type = FoldingType.TypeMember;
						break;
					case FoldType.Type:
						type = FoldingType.TypeDefinition;
						break;
					case FoldType.UserRegion:
						type = FoldingType.Region;
						setFolded = DefaultSourceEditorOptions.Instance.DefaultRegionsFolding;
						folded = true;
						break;
					case FoldType.Comment:
						type = FoldingType.Comment;
						setFolded = DefaultSourceEditorOptions.Instance.DefaultCommentFolding;
						folded = true;
						break;
					case FoldType.CommentInsideMember:
						type = FoldingType.Comment;
						setFolded = DefaultSourceEditorOptions.Instance.DefaultCommentFolding;
						folded = false;
						break;
					case FoldType.Undefined:
						setFolded = true;
						folded = region.IsFoldedByDefault;
						break;
					}
					var start = textEditor.LocationToOffset (region.Region.Begin);
					var end = textEditor.LocationToOffset (region.Region.End);
					var marker = textEditor.CreateFoldSegment (start, end - start);
					foldSegments.Add (marker);
					marker.CollapsedText = region.Name;
					marker.FoldingType = type;
					//and, if necessary, set its fold state
					if (marker != null && setFolded && firstTime) {
						// only fold on document open, later added folds are NOT folded by default.
						marker.IsCollapsed = folded;
						continue;
					}
					if (marker != null && region.Region.Contains (caretLocation.Line, caretLocation.Column))
						marker.IsCollapsed = false;
				}
				if (firstTime) {
					textEditor.SetFoldings (foldSegments);
				} else {
					Application.Invoke (delegate {
						if (!token.IsCancellationRequested)
							textEditor.SetFoldings (foldSegments);
					});
				}
			} catch (Exception ex) {
				LoggingService.LogError ("Unhandled exception in ParseInformationUpdaterWorkerThread", ex);
			}
		}
        public override TooltipItem GetItem(Mono.TextEditor.TextEditor editor, int offset)
        {
            if (offset >= editor.Document.TextLength)
            {
                return(null);
            }

            if (!DebuggingService.IsDebugging || DebuggingService.IsRunning)
            {
                return(null);
            }

            StackFrame frame = DebuggingService.CurrentFrame;

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

            var ed = (ExtensibleTextEditor)editor;

            string expression = null;
            int    startOffset = 0, length = 0;

            if (ed.IsSomethingSelected && offset >= ed.SelectionRange.Offset && offset <= ed.SelectionRange.EndOffset)
            {
                expression  = ed.SelectedText;
                startOffset = ed.SelectionRange.Offset;
                length      = ed.SelectionRange.Length;
            }
            else
            {
                ICSharpCode.NRefactory.TypeSystem.DomRegion expressionRegion;
                ResolveResult res = ed.GetLanguageItem(offset, out expressionRegion);

                if (res == null || res.IsError || res.GetType() == typeof(ResolveResult))
                {
                    return(null);
                }

                //Console.WriteLine ("res is a {0}", res.GetType ().Name);

                if (expressionRegion.IsEmpty)
                {
                    return(null);
                }

                if (res is NamespaceResolveResult ||
                    res is ConversionResolveResult ||
                    res is ForEachResolveResult ||
                    res is TypeIsResolveResult ||
                    res is TypeOfResolveResult ||
                    res is ErrorResolveResult)
                {
                    return(null);
                }

                var start = new DocumentLocation(expressionRegion.BeginLine, expressionRegion.BeginColumn);
                var end   = new DocumentLocation(expressionRegion.EndLine, expressionRegion.EndColumn);

                startOffset = editor.Document.LocationToOffset(start);
                int endOffset = editor.Document.LocationToOffset(end);
                length = endOffset - startOffset;

                if (res is LocalResolveResult)
                {
                    var lr = (LocalResolveResult)res;

                    // Capture only the local variable portion of the expression...
                    expression = lr.Variable.Name;
                    length     = expression.Length;

                    // Calculate start offset based on the variable region because we don't want to include the type information.
                    // Note: We might not actually need to do this anymore?
                    if (lr.Variable.Region.BeginLine != start.Line || lr.Variable.Region.BeginColumn != start.Column)
                    {
                        start       = new DocumentLocation(lr.Variable.Region.BeginLine, lr.Variable.Region.BeginColumn);
                        startOffset = editor.Document.LocationToOffset(start);
                    }
                }
                else if (res is InvocationResolveResult)
                {
                    var ir = (InvocationResolveResult)res;

                    if (ir.Member.Name != ".ctor")
                    {
                        return(null);
                    }

                    expression = ir.Member.DeclaringType.FullName;
                }
                else if (res is MemberResolveResult)
                {
                    var mr = (MemberResolveResult)res;

                    if (mr.TargetResult == null)
                    {
                        // User is hovering over a member definition...

                        if (mr.Member is IProperty)
                        {
                            // Visual Studio will evaluate Properties if you hover over their definitions...
                            var prop = (IProperty)mr.Member;

                            if (prop.CanGet)
                            {
                                if (prop.IsStatic)
                                {
                                    expression = prop.FullName;
                                }
                                else
                                {
                                    expression = prop.Name;
                                }
                            }
                            else
                            {
                                return(null);
                            }
                        }
                        else if (mr.Member is IField)
                        {
                            var field = (IField)mr.Member;

                            if (field.IsStatic)
                            {
                                expression = field.FullName;
                            }
                            else
                            {
                                expression = field.Name;
                            }
                        }
                        else
                        {
                            return(null);
                        }
                    }

                    // If the TargetResult is not null, then treat it like any other ResolveResult.
                }
                else if (res is ConstantResolveResult)
                {
                    // Fall through...
                }
                else if (res is ThisResolveResult)
                {
                    // Fall through...
                }
                else if (res is TypeResolveResult)
                {
                    // Fall through...
                }
                else
                {
                    return(null);
                }

                if (expression == null)
                {
                    expression = ed.GetTextBetween(start, end);
                }
            }

            if (string.IsNullOrEmpty(expression))
            {
                return(null);
            }

            ObjectValue val;

            if (!cachedValues.TryGetValue(expression, out val))
            {
                val = frame.GetExpressionValue(expression, true);
                cachedValues [expression] = val;
            }

            if (val == null || val.IsUnknown || val.IsNotSupported)
            {
                return(null);
            }

            val.Name = expression;

            return(new TooltipItem(val, startOffset, length));
        }
		public ErrorInFileException (DocumentLocation region, string fileName)
		{
			this.line = region.Line;
			this.column = region.Column;
			this.fileName = fileName;
		}
        public MonoDevelop.Projects.Dom.ResolveResult GetLanguageItem(ProjectDom dom, Mono.TextEditor.TextEditorData data, int offset, string expression)
        {
            string fileName = data.Document.FileName;

            MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
            if (doc == null)
            {
                return(null);
            }

            IParser parser = ProjectDomService.GetParser(fileName);

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

            IResolver         resolver         = parser.CreateResolver(dom, doc, fileName);
            IExpressionFinder expressionFinder = parser.CreateExpressionFinder(dom);

            if (resolver == null || expressionFinder == null)
            {
                return(null);
            }
            int wordEnd = offset;

            while (wordEnd < data.Length && (Char.IsLetterOrDigit(data.GetCharAt(wordEnd)) || data.GetCharAt(wordEnd) == '_'))
            {
                wordEnd++;
            }
            ExpressionResult expressionResult = new ExpressionResult(expression);

            expressionResult.ExpressionContext = ExpressionContext.MethodBody;

            DocumentLocation loc             = data.Document.OffsetToLocation(offset);
            string           savedExpression = null;
            ResolveResult    resolveResult;

            if (expressionResult.ExpressionContext == ExpressionContext.Attribute)
            {
                savedExpression                    = expressionResult.Expression;
                expressionResult.Expression       += "Attribute";
                expressionResult.ExpressionContext = ExpressionContext.ObjectCreation;
            }
            resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column));
            if (savedExpression != null && resolveResult == null)
            {
                expressionResult.Expression = savedExpression;
                resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column));
            }
            if (expressionResult.Region.End.IsEmpty)
            {
                return(resolveResult);
            }
            // Search for possible generic parameters.
//			if (this.resolveResult == null || this.resolveResult.ResolvedType == null || String.IsNullOrEmpty (this.resolveResult.ResolvedType.Name)) {
            int j       = data.Document.LocationToOffset(expressionResult.Region.End.Line, expressionResult.Region.End.Column);
            int bracket = 0;

            for (int i = j; i >= 0 && i < data.Document.Length; i++)
            {
                char ch = data.Document.GetCharAt(i);
                if (Char.IsWhiteSpace(ch))
                {
                    continue;
                }
                if (ch == '<')
                {
                    bracket++;
                }
                else if (ch == '>')
                {
                    bracket--;
                    if (bracket == 0)
                    {
                        expressionResult.Expression       += data.Document.GetTextBetween(j, i + 1);
                        expressionResult.ExpressionContext = ExpressionContext.ObjectCreation;
                        resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column)) ?? resolveResult;
                        break;
                    }
                }
                else
                {
                    if (bracket == 0)
                    {
                        break;
                    }
                }
            }
//			}

            // To resolve method overloads the full expression must be parsed.
            // ex.: Overload (1)/ Overload("one") - parsing "Overload" gives just a MethodResolveResult
            if (resolveResult is MethodResolveResult)
            {
                resolveResult = resolver.Resolve(expressionFinder.FindFullExpression(data, wordEnd), new DomLocation(loc.Line, loc.Column)) ?? resolveResult;
            }
            return(resolveResult);
        }
Esempio n. 25
0
		static DocumentLocation LimitColumn (TextEditor data, DocumentLocation loc)
		{
			return new DocumentLocation (loc.Line, System.Math.Min (loc.Column, data.GetLine (loc.Line).Length + 1));
		}
        public MonoDevelop.Projects.Dom.ResolveResult GetLanguageItem(ProjectDom dom, Mono.TextEditor.TextEditorData data, int offset)
        {
            if (offset < 0)
            {
                return(null);
            }
            string  fileName = data.Document.FileName;
            IParser parser   = ProjectDomService.GetParser(fileName);

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

            MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
            if (doc == null)
            {
                return(null);
            }

            IResolver resolver = parser.CreateResolver(dom, doc, fileName);

            if (resolver == null)
            {
                return(null);
            }
            var expressionFinder = new NewCSharpExpressionFinder(dom);

            int wordEnd = Math.Min(offset, data.Length - 1);

            if (wordEnd < 0)
            {
                return(null);
            }
            if (data.GetCharAt(wordEnd) == '@')
            {
                wordEnd++;
            }
            while (wordEnd < data.Length && (Char.IsLetterOrDigit(data.GetCharAt(wordEnd)) || data.GetCharAt(wordEnd) == '_'))
            {
                wordEnd++;
            }

            while (wordEnd < data.Length - 1 && Char.IsWhiteSpace(data.GetCharAt(wordEnd)))
            {
                wordEnd++;
            }

            /* is checked at the end.
             * int saveEnd = wordEnd;
             * if (wordEnd < data.Length && data.GetCharAt (wordEnd) == '<') {
             *      int matchingBracket = data.Document.GetMatchingBracketOffset (wordEnd);
             *      if (matchingBracket > 0)
             *              wordEnd = matchingBracket;
             *      while (wordEnd < data.Length - 1 && Char.IsWhiteSpace (data.GetCharAt (wordEnd)))
             *              wordEnd++;
             * }
             *
             * bool wasMethodCall = false;
             * if (data.GetCharAt (wordEnd) == '(') {
             *      int matchingBracket = data.Document.GetMatchingBracketOffset (wordEnd);
             *      if (matchingBracket > 0) {
             *              wordEnd = matchingBracket;
             *              wasMethodCall = true;
             *      }
             * }
             * if (!wasMethodCall)
             *      wordEnd = saveEnd;*/

            ExpressionResult expressionResult = expressionFinder.FindExpression(data, wordEnd);

            if (expressionResult == null)
            {
                return(null);
            }
            ResolveResult    resolveResult;
            DocumentLocation loc             = data.Document.OffsetToLocation(offset);
            string           savedExpression = null;

            // special handling for 'var' "keyword"
            if (expressionResult.ExpressionContext == ExpressionContext.IdentifierExpected && expressionResult.Expression != null && expressionResult.Expression.Trim() == "var")
            {
                int           endOffset = data.Document.LocationToOffset(expressionResult.Region.End.Line, expressionResult.Region.End.Column);
                StringBuilder identifer = new StringBuilder();
                for (int i = endOffset; i >= 0 && i < data.Document.Length; i++)
                {
                    char ch = data.Document.GetCharAt(i);
                    if (Char.IsWhiteSpace(ch))
                    {
                        continue;
                    }
                    if (ch == '=')
                    {
                        break;
                    }
                    if (Char.IsLetterOrDigit(ch) || ch == '_')
                    {
                        identifer.Append(ch);
                        continue;
                    }
                    identifer.Length = 0;
                    break;
                }
                if (identifer.Length > 0)
                {
                    expressionResult.Expression = identifer.ToString();
                    resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column));
                    if (resolveResult != null)
                    {
                        resolveResult = new MemberResolveResult(dom.GetType(resolveResult.ResolvedType));
                        resolveResult.ResolvedExpression = expressionResult;
                        return(resolveResult);
                    }
                }
            }

            if (expressionResult.ExpressionContext == ExpressionContext.Attribute && !string.IsNullOrEmpty(expressionResult.Expression))
            {
                savedExpression                    = expressionResult.Expression;
                expressionResult.Expression        = expressionResult.Expression.Trim() + "Attribute";
                expressionResult.ExpressionContext = ExpressionContext.ObjectCreation;
            }

            resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column));
            if (savedExpression != null && resolveResult == null)
            {
                expressionResult.Expression = savedExpression;
                resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column));
            }
            // Search for possible generic parameters.
//			if (this.resolveResult == null || this.resolveResult.ResolvedType == null || String.IsNullOrEmpty (this.resolveResult.ResolvedType.Name)) {
            if (!expressionResult.Region.IsEmpty)
            {
                int j       = data.Document.LocationToOffset(expressionResult.Region.End.Line, expressionResult.Region.End.Column);
                int bracket = 0;
                for (int i = j; i >= 0 && i < data.Document.Length; i++)
                {
                    char ch = data.Document.GetCharAt(i);
                    if (Char.IsWhiteSpace(ch))
                    {
                        continue;
                    }
                    if (ch == '<')
                    {
                        bracket++;
                    }
                    else if (ch == '>')
                    {
                        bracket--;
                        if (bracket == 0)
                        {
                            expressionResult.Expression       += data.Document.GetTextBetween(j, i + 1);
                            expressionResult.ExpressionContext = ExpressionContext.ObjectCreation;
                            resolveResult = resolver.Resolve(expressionResult, new DomLocation(loc.Line, loc.Column));
                            break;
                        }
                    }
                    else
                    {
                        if (bracket == 0)
                        {
                            break;
                        }
                    }
                }
            }

            // To resolve method overloads the full expression must be parsed.
            // ex.: Overload (1)/ Overload("one") - parsing "Overload" gives just a MethodResolveResult
            // and for constructor initializers it's tried too to to resolve constructor overloads.
            if (resolveResult is ThisResolveResult ||
                resolveResult is BaseResolveResult ||
                resolveResult is MethodResolveResult && ((MethodResolveResult)resolveResult).Methods.Count > 1)
            {
                // put the search offset at the end of the invocation to be able to find the full expression
                // the resolver finds it itself if spaces are between the method name and the argument opening parentheses.
                while (wordEnd < data.Length - 1 && Char.IsWhiteSpace(data.GetCharAt(wordEnd)))
                {
                    wordEnd++;
                }
                if (data.GetCharAt(wordEnd) == '(')
                {
                    int matchingBracket = data.Document.GetMatchingBracketOffset(wordEnd);
                    if (matchingBracket > 0)
                    {
                        wordEnd = matchingBracket;
                    }
                }
                //Console.WriteLine (expressionFinder.FindFullExpression (txt, wordEnd));
                ResolveResult possibleResult = resolver.Resolve(expressionFinder.FindFullExpression(data, wordEnd), new DomLocation(loc.Line, loc.Column)) ?? resolveResult;
                //Console.WriteLine ("possi:" + resolver.Resolve (expressionFinder.FindFullExpression (txt, wordEnd), new DomLocation (loc.Line, loc.Column)));
                if (possibleResult is MethodResolveResult)
                {
                    resolveResult = possibleResult;
                }
            }
            return(resolveResult);
        }
		public unsafe ParsedDocument Parse (string fileName, string content)
		{
			var regionStack = new Stack<Tuple<string, DocumentLocation>> ();
			var result = new DefaultParsedDocument (fileName);
			bool inSingleComment = false, inMultiLineComment = false;
			bool inString = false, inVerbatimString = false;
			bool inChar = false;
			bool inLineStart = true, hasStartedAtLine = false;
			int line = 1, column = 1;
			var startLoc = DocumentLocation.Empty;
			
			fixed (char* startPtr = content) {
				char* endPtr = startPtr + content.Length;
				char* ptr = startPtr;
				char* beginPtr = ptr;
				while (ptr < endPtr) {
					switch (*ptr) {
					case '#':
						if (!inLineStart)
							break;
						inLineStart = false;
						ptr++;

						if (StartsIdentifier (ptr, endPtr, "region")) {
							var regionLocation = new DocumentLocation (line, column);
							column++;
							ptr += "region".Length;
							column += "region".Length;
							SkipWhitespaces (ref ptr, endPtr, ref column);
							regionStack.Push (Tuple.Create (ReadToEol (content, ref ptr, endPtr, ref line, ref column), regionLocation));
							continue;
						} else if (StartsIdentifier (ptr, endPtr, "endregion")) {
							column++;
							ptr += "endregion".Length;
							column += "endregion".Length;
							if (regionStack.Count > 0) {
								var beginRegion = regionStack.Pop ();
								result.Add (new FoldingRegion (
									beginRegion.Item1, 
									new DocumentRegion (beginRegion.Item2.Line, beginRegion.Item2.Column, line, column),
									FoldType.UserRegion,
									true));
							}
							continue;
						} else {
							column++;
						}
						break;
					case '/':
						if (inString || inChar || inVerbatimString || inMultiLineComment || inSingleComment) {
							inLineStart = false;
							break;
						}
						if (ptr + 1 < endPtr) {
							char nextCh = *(ptr + 1);
							if (nextCh == '/') {
								hasStartedAtLine = inLineStart;
								beginPtr = ptr + 2;
								startLoc = new DocumentLocation (line, column);
								ptr++;
								column++;
								inSingleComment = true;
							} else if (nextCh == '*') {
								hasStartedAtLine = inLineStart;
								beginPtr = ptr + 2;
								startLoc = new DocumentLocation (line, column);
								ptr++;
								column++;
								inMultiLineComment = true;
							}
						}
						inLineStart = false;
						break;
					case '*':
						inLineStart = false;
						if (inString || inChar || inVerbatimString || inSingleComment)
							break;
						if (inMultiLineComment && ptr + 1 < endPtr) {
							if (ptr + 1 < endPtr && *(ptr + 1) == '/') {
								ptr += 2;
								column += 2;
								inMultiLineComment = false;
								result.Add (new MonoDevelop.Ide.TypeSystem.Comment () {
									Region = new DocumentRegion (startLoc, new DocumentLocation (line, column)),
									OpenTag = "/*",
									CommentType = MonoDevelop.Ide.TypeSystem.CommentType.Block,
									Text = content.Substring ((int)(beginPtr - startPtr), (int)(ptr - beginPtr)),
									CommentStartsLine = hasStartedAtLine
								});
								continue;
							}
						}
						break;
					case '@':
						inLineStart = false;
						if (inString || inChar || inVerbatimString || inSingleComment || inMultiLineComment)
							break;
						if (ptr + 1 < endPtr && *(ptr + 1) == '"') {
							ptr++;
							column++;
							inVerbatimString = true;
						}
						break;
					case '\n':
						if (inSingleComment && hasStartedAtLine) {
							bool isDocumentation = *beginPtr == '/';
							if (isDocumentation)
								beginPtr++;
							
							result.Add (new MonoDevelop.Ide.TypeSystem.Comment () { 
								Region = new DocumentRegion (startLoc, new DocumentLocation (line, column)),
								CommentType = MonoDevelop.Ide.TypeSystem.CommentType.SingleLine, 
								OpenTag = "//",
								Text = content.Substring ((int)(beginPtr - startPtr), (int)(ptr - beginPtr)),
								CommentStartsLine = hasStartedAtLine,
								IsDocumentation = isDocumentation
							});
							inSingleComment = false;
						}
						inString = false;
						inChar = false;
						inLineStart = true;
						line++;
						column = 1;
						ptr++;
						continue;
					case '\r':
						if (ptr + 1 < endPtr && *(ptr + 1) == '\n')
							ptr++;
						goto case '\n';
					case '\\':
						if (inString || inChar)
							ptr++;
						break;
					case '"':
						if (inSingleComment || inMultiLineComment || inChar)
							break;
						if (inVerbatimString) {
							if (ptr + 1 < endPtr && *(ptr + 1) == '"') {
								ptr++;
								column++;
								break;
							}
							inVerbatimString = false;
							break;
						}
						inString = !inString;
						break;
					case '\'':
						if (inSingleComment || inMultiLineComment || inString || inVerbatimString)
							break;
						inChar = !inChar;
						break;
					default:
						inLineStart &= *ptr == ' ' || *ptr == '\t';
						break;
					}

					column++;
					ptr++;
				}
			}
			foreach (var fold in result.GetCommentsAsync().Result.ToFolds ()) {
				result.Add (fold);
			}
			return result;
		}
Esempio n. 28
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);
        }
Esempio n. 29
0
		protected virtual async Task<ICompletionDataList> HandleCodeCompletion (
			CodeCompletionContext completionContext, bool forced, CancellationToken token)
		{
			var buf = this.Editor;

			// completionChar may be a space even if the current char isn't, when ctrl-space is fired t
			var currentLocation = new DocumentLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
			char currentChar = completionContext.TriggerOffset < 1? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 1);
			char previousChar = completionContext.TriggerOffset < 2? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 2);

			LoggingService.LogDebug ("Attempting completion for state '{0}'x{1}, previousChar='{2}'," 
				+ " currentChar='{3}', forced='{4}'", tracker.Engine.CurrentState,
				tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);
			
			//closing tag completion
			if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
				return ClosingTagCompletion (buf, currentLocation);
			
			// Auto insert '>' when '/' is typed inside tag state (for quick tag closing)
			//FIXME: avoid doing this when the next non-whitespace char is ">" or ignore the next ">" typed
			if (XmlEditorOptions.AutoInsertFragments && tracker.Engine.CurrentState is XmlTagState && currentChar == '/') {
				buf.InsertAtCaret (">");
				return null;
			}
			
			//entity completion
			if (currentChar == '&' && (tracker.Engine.CurrentState is XmlRootState ||
			                           tracker.Engine.CurrentState is XmlAttributeValueState))
			{
				var list = new CompletionDataList ();
				
				//TODO: need to tweak semicolon insertion
				list.Add ("apos").Description = "'";
				list.Add ("quot").Description = "\"";
				list.Add ("lt").Description = "<";
				list.Add ("gt").Description = ">";
				list.Add ("amp").Description = "&";
				
				//not sure about these "completions". they're more like
				//shortcuts than completions but they're pretty useful
				list.Add ("'").CompletionText = "apos;";
				list.Add ("\"").CompletionText = "quot;";
				list.Add ("<").CompletionText = "lt;";
				list.Add (">").CompletionText = "gt;";
				list.Add ("&").CompletionText = "amp;";
				
				var ecList = await GetEntityCompletions (token);
				list.AddRange (ecList);
				return list;
			}
			
			//doctype completion
			if (tracker.Engine.CurrentState is XmlDocTypeState) {
				if (tracker.Engine.CurrentStateLength == 1) {
					CompletionDataList list = await GetDocTypeCompletions (token);
					if (list != null && list.Count > 0)
						return list;
				}
				return null;
			}

			//attribute value completion
			//determine whether to trigger completion within attribute values quotes
			if ((Tracker.Engine.CurrentState is XmlAttributeValueState)
			    //trigger on the opening quote
			    && ((Tracker.Engine.CurrentStateLength == 1 && (currentChar == '\'' || currentChar == '"'))
			    //or trigger on first letter of value, if unforced
			    || (forced || Tracker.Engine.CurrentStateLength == 2))) {
				var att = (XAttribute)Tracker.Engine.Nodes.Peek ();

				if (att.IsNamed) {
					var attributedOb = Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
					if (attributedOb == null)
						return null;

					//if triggered by first letter of value or forced, grab those letters

					var result = await GetAttributeValueCompletions (attributedOb, att, token);
					if (result != null) {
						result.TriggerWordLength = Tracker.Engine.CurrentStateLength - 1;
						return result;
					}
					return null;
				}
			}
			
			//attribute name completion
			if ((forced && Tracker.Engine.Nodes.Peek () is IAttributedXObject && !tracker.Engine.Nodes.Peek ().IsEnded)
			     || ((Tracker.Engine.CurrentState is XmlNameState
			    && Tracker.Engine.CurrentState.Parent is XmlAttributeState) ||
			    Tracker.Engine.CurrentState is XmlTagState)
			    && (Tracker.Engine.CurrentStateLength == 1 || forced)) {
				IAttributedXObject attributedOb = (Tracker.Engine.Nodes.Peek () as IAttributedXObject) ?? 
					Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
				if (attributedOb == null)
					return null;
				
				//attributes
				if (attributedOb.Name.IsValid && (forced ||
					(char.IsWhiteSpace (previousChar) && char.IsLetter (currentChar))))
				{
					var existingAtts = new Dictionary<string,string> (StringComparer.OrdinalIgnoreCase);
					
					foreach (XAttribute att in attributedOb.Attributes) {
						existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
					}
					var result = await GetAttributeCompletions (attributedOb, existingAtts, token);
					if (result != null) {
						if (!forced)
							result.TriggerWordLength = 1;
						return result;
					}
					return null;
				}
			}
			
//			if (Tracker.Engine.CurrentState is XmlRootState) {
//				if (line < 3) {
//				cp.Add ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
//			}

			//element completion
			if (currentChar == '<' && tracker.Engine.CurrentState is XmlRootState ||
				(tracker.Engine.CurrentState is XmlNameState && forced)) {
				var list = await GetElementCompletions (token);
				AddCloseTag (list, Tracker.Engine.Nodes);
				return list.Count > 0 ? list : null;
			}

			if (forced && Tracker.Engine.CurrentState is XmlRootState) {
				var list = new CompletionDataList ();
				MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName (DocumentContext.Name, list);
				return list.Count > 0? list : null;
			}
			
			return null;
		}
Esempio n. 30
0
 public RazorStatement(DocumentLocation start) : base(start)
 {
 }
Esempio n. 31
0
        public override Task InsertWithCursor(string operation, InsertPosition defaultPosition, IEnumerable <AstNode> nodes)
        {
            var tcs              = new TaskCompletionSource <object> ();
            var editor           = document.Editor;
            DocumentLocation loc = document.Editor.Caret.Location;
            var declaringType    = document.ParsedDocument.GetInnermostTypeDefinition(loc);
            var mode             = new InsertionCursorEditMode(
                editor.Parent,
                CodeGenerationService.GetInsertionPoints(document, declaringType));

            if (mode.InsertionPoints.Count == 0)
            {
                MessageService.ShowError(
                    GettextCatalog.GetString("No valid insertion point can be found in type '{0}'.", declaringType.Name)
                    );
                return(tcs.Task);
            }
            var helpWindow = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow();

            helpWindow.TransientFor = MonoDevelop.Ide.IdeApp.Workbench.RootWindow;
            helpWindow.TitleText    = operation;
            mode.HelpWindow         = helpWindow;

            switch (defaultPosition)
            {
            case InsertPosition.Start:
                mode.CurIndex = 0;
                break;

            case InsertPosition.End:
                mode.CurIndex = mode.InsertionPoints.Count - 1;
                break;

            case InsertPosition.Before:
                for (int i = 0; i < mode.InsertionPoints.Count; i++)
                {
                    if (mode.InsertionPoints [i].Location < loc)
                    {
                        mode.CurIndex = i;
                    }
                }
                break;

            case InsertPosition.After:
                for (int i = 0; i < mode.InsertionPoints.Count; i++)
                {
                    if (mode.InsertionPoints [i].Location > loc)
                    {
                        mode.CurIndex = i;
                        break;
                    }
                }
                break;
            }
            operationsRunning++;
            mode.StartMode();
            DesktopService.RemoveWindowShadow(helpWindow);
            mode.Exited += delegate(object s, InsertionCursorEventArgs iCArgs) {
                if (iCArgs.Success)
                {
                    if (iCArgs.InsertionPoint.LineAfter == NewLineInsertion.None &&
                        iCArgs.InsertionPoint.LineBefore == NewLineInsertion.None && nodes.Count() > 1)
                    {
                        iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine;
                    }
                    foreach (var node in nodes.Reverse())
                    {
                        var output = OutputNode(CodeGenerationService.CalculateBodyIndentLevel(declaringType), node);
                        var offset = document.Editor.LocationToOffset(iCArgs.InsertionPoint.Location);
                        var delta  = iCArgs.InsertionPoint.Insert(editor, output.Text);
                        output.RegisterTrackedSegments(this, delta + offset);
                    }
                    tcs.SetResult(null);
                }
                else
                {
                    Rollback();
                }
                DisposeOnClose();
            };
            return(tcs.Task);
        }
Esempio n. 32
0
		public XElement (DocumentLocation start) : base (start)
		{
			attributes = new XAttributeCollection (this);
		}
Esempio n. 33
0
 public static bool ContainsOuter(this DocumentRegion region, DocumentLocation location)
 {
     return(region.Begin <= location && location <= region.End);
 }
		public static int LocationToOffset (this IReadonlyTextDocument document, DocumentLocation location)
		{
			if (document == null)
				throw new ArgumentNullException ("document");
			return document.LocationToOffset (location.Line, location.Column);
		}
 private void InjectLineInfoMembersToBuffer(DocumentLocation startPosition, DocumentLocation endPosition)
 {
     this.InjectLineInfoMemberToBuffer(this.StartLineMember, startPosition.LineNumber.Value);
     this.InjectLineInfoMemberToBuffer(this.StartColumnMember, startPosition.LinePosition.Value);
     this.InjectLineInfoMemberToBuffer(this.EndLineMember, endPosition.LineNumber.Value);
     this.InjectLineInfoMemberToBuffer(this.EndColumnMember, endPosition.LinePosition.Value);
 }
Esempio n. 36
0
 public WebFormsRenderExpression(DocumentLocation start) : base(start)
 {
 }
Esempio n. 37
0
		public XElement (DocumentLocation start, XName name) : this (start)
		{
			this.Name = name;
		}
Esempio n. 38
0
        public static Action <TextEditorData> VisualSelectionFromMoveAction(Action <TextEditorData> moveAction)
        {
            return(delegate(TextEditorData data) {
                //get info about the old selection state
                DocumentLocation oldCaret = data.Caret.Location, oldAnchor = oldCaret, oldLead = oldCaret;
                if (data.MainSelection != null)
                {
                    oldLead = data.MainSelection.Lead;
                    oldAnchor = data.MainSelection.Anchor;
                }

                //do the action, preserving selection
                SelectionActions.StartSelection(data);
                moveAction(data);
                SelectionActions.EndSelection(data);

                DocumentLocation newCaret = data.Caret.Location, newAnchor = newCaret, newLead = newCaret;
                if (data.MainSelection != null)
                {
                    newLead = data.MainSelection.Lead;
                    newAnchor = data.MainSelection.Anchor;
                }

                //Console.WriteLine ("oc{0}:{1} oa{2}:{3} ol{4}:{5}", oldCaret.Line, oldCaret.Column, oldAnchor.Line, oldAnchor.Column, oldLead.Line, oldLead.Column);
                //Console.WriteLine ("nc{0}:{1} na{2}:{3} nl{4}:{5}", newCaret.Line, newCaret.Line, newAnchor.Line, newAnchor.Column, newLead.Line, newLead.Column);

                //pivot the anchor around the anchor character
                if (oldAnchor < oldLead && newAnchor >= newLead)
                {
                    data.SetSelection(new DocumentLocation(newAnchor.Line, newAnchor.Column + 1), newLead);
                }
                else if (oldAnchor > oldLead && newAnchor <= newLead)
                {
                    data.SetSelection(new DocumentLocation(newAnchor.Line, newAnchor.Column - 1), newLead);
                }

                //pivot the lead about the anchor character
                if (newAnchor == newLead)
                {
                    if (oldAnchor < oldLead)
                    {
                        SelectionActions.FromMoveAction(Left) (data);
                    }
                    else
                    {
                        SelectionActions.FromMoveAction(Right) (data);
                    }
                }
                //pivot around the anchor line
                else
                {
                    if (oldAnchor < oldLead && newAnchor > newLead && (
                            (newLead.Line == newAnchor.Line && oldLead.Line == oldAnchor.Line + 1) ||
                            (newLead.Line == newAnchor.Line - 1 && oldLead.Line == oldAnchor.Line)))
                    {
                        SelectionActions.FromMoveAction(Left) (data);
                    }
                    else if (oldAnchor > oldLead && newAnchor < newLead && (
                                 (newLead.Line == newAnchor.Line && oldLead.Line == oldAnchor.Line - 1) ||
                                 (newLead.Line == newAnchor.Line + 1 && oldLead.Line == oldAnchor.Line)))
                    {
                        SelectionActions.FromMoveAction(Right) (data);
                    }
                }
            });
        }
		public static string GetTextBetween (this IReadonlyTextDocument document, DocumentLocation start, DocumentLocation end)
		{
			if (document == null)
				throw new ArgumentNullException ("document");
			return document.GetTextBetween (document.LocationToOffset (start), document.LocationToOffset (end));
		}
Esempio n. 40
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered CreateDocumentLocation.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("CreateDocumentLocation.Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
            IOrganizationService        privService    = serviceFactory.CreateOrganizationService(null);

            try
            {
                var      url       = RecordUrl.Get <string>(executionContext);
                var      recordRef = new DynamicUrlParser(url).ToEntityReference(privService);
                string   config    = GetSecureConfigValue(privService, "PrivSharePointUser");;
                string[] user      = config.Split(';');

                // Create a new sharepoint service using the given priv sharepoint user credentials
                SPService spService   = new SPService(user[0], user[1]);
                var       docLocation = new DocumentLocationHelper(privService, spService);

                // Get the site passed into the workflow activity
                var siteId = Site.Get(executionContext);
                var site   = (SharePointSite)service.Retrieve(SharePointSite.EntityLogicalName, siteId.Id, new ColumnSet("sharepointsiteid", "absoluteurl"));

                if (site != null)
                {
                    // Set the name of the folder
                    recordRef.Name = RecordFolderName.Get <string>(executionContext);
                    var newLocation = docLocation.CreateDocumentLocation(site, DocumentLibraryName.Get(executionContext), recordRef);

                    DocumentLocation.Set(executionContext, newLocation.ToEntityReference());
                    DocumentFolder.Set(executionContext, newLocation.AbsoluteURL);
                }
                else
                {
                    DocumentLocation.Set(executionContext, null);
                }
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }

            tracingService.Trace("Exiting CreateDocumentLocation.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
Esempio n. 41
0
		public XAttribute (DocumentLocation start) : base (start)
		{
		}
 void StoreWidgetState()
 {
     this.vSave     = textEditor.VAdjustment.Value;
     this.hSave     = textEditor.HAdjustment.Value;
     this.caretSave = textEditor.Caret.Location;
 }
		async static Task<PathEntry> GetRegionEntry (ParsedDocument unit, DocumentLocation loc)
		{
			PathEntry entry;
			FoldingRegion reg;
			try {
				var regions = await unit.GetUserRegionsAsync ().ConfigureAwait (false);
				if (unit == null || !regions.Any ())
					return null;
				reg = regions.LastOrDefault (r => r.Region.Contains (loc));
			} catch (AggregateException) {
				return null;
			} catch (OperationCanceledException) {
				return null;
			}
			if (reg == null) {
				entry = new PathEntry (GettextCatalog.GetString ("No region"));
			} else {
				entry = new PathEntry (CompilationUnitDataProvider.Pixbuf, GLib.Markup.EscapeText (reg.Name));
			}
			entry.Position = EntryPosition.Right;
			return entry;
		}
Esempio n. 44
0
        protected override void Update(CommandArrayInfo ainfo)
        {
            var doc = IdeApp.Workbench.ActiveDocument;

            if (doc == null || doc.FileName == FilePath.Null)
            {
                return;
            }

            var parsedDocument = doc.ParsedDocument;

            if (parsedDocument == null || parsedDocument.IsInvalid)
            {
                return;
            }

            ResolveResult resolveResult;
            object        item  = GetItem(doc, out resolveResult);
            bool          added = false;

            var options = new RefactoringOptions(doc)
            {
                ResolveResult = resolveResult,
                SelectedItem  = item
            };

            var ciset = new CommandInfoSet();

            ciset.Text = GettextCatalog.GetString("Refactor");

            bool canRename;

            if (item is IVariable || item is IParameter)
            {
                canRename = true;
            }
            else if (item is ITypeDefinition)
            {
                canRename = !((ITypeDefinition)item).Region.IsEmpty;
            }
            else if (item is IType)
            {
                canRename = ((IType)item).Kind == TypeKind.TypeParameter;
            }
            else if (item is IMember)
            {
                canRename = !((IMember)item).Region.IsEmpty;
            }
            else if (item is INamespace)
            {
                canRename = true;
            }
            else
            {
                canRename = false;
            }
            if (canRename)
            {
                ciset.CommandInfos.Add(IdeApp.CommandService.GetCommandInfo(MonoDevelop.Ide.Commands.EditCommands.Rename), new Action(delegate {
                    new MonoDevelop.Refactoring.Rename.RenameHandler().Start(null);
                }));
                added = true;
            }

            foreach (var refactoring in RefactoringService.Refactorings)
            {
                if (refactoring.IsValid(options))
                {
                    CommandInfo info = new CommandInfo(refactoring.GetMenuDescription(options));
                    info.AccelKey = refactoring.AccelKey;
                    ciset.CommandInfos.Add(info, new Action(new RefactoringOperationWrapper(refactoring, options).Operation));
                }
            }
            var refactoringInfo = doc.Annotation <RefactoringDocumentInfo> ();

            if (refactoringInfo == null)
            {
                refactoringInfo = new RefactoringDocumentInfo();
                doc.AddAnnotation(refactoringInfo);
            }
            var  loc   = doc.Editor.Caret.Location;
            bool first = true;

            if (refactoringInfo.lastDocument != doc.ParsedDocument || loc != lastLocation)
            {
                if (QuickTaskStrip.EnableFancyFeatures)
                {
                    var ext = doc.GetContent <CodeActionEditorExtension> ();
                    refactoringInfo.validActions = ext != null?ext.GetCurrentFixes() : null;
                }
                else
                {
                    refactoringInfo.validActions = RefactoringService.GetValidActions(doc, loc).Result;
                }

                lastLocation = loc;
                refactoringInfo.lastDocument = doc.ParsedDocument;
            }
            if (refactoringInfo.validActions != null && refactoringInfo.lastDocument != null && refactoringInfo.lastDocument.CreateRefactoringContext != null)
            {
                var context = refactoringInfo.lastDocument.CreateRefactoringContext(doc, CancellationToken.None);

                foreach (var fix_ in refactoringInfo.validActions.OrderByDescending(i => Tuple.Create(CodeActionWidget.IsAnalysisOrErrorFix(i), (int)i.Severity, CodeActionWidget.GetUsage(i.IdString))))
                {
                    if (CodeActionWidget.IsAnalysisOrErrorFix(fix_))
                    {
                        continue;
                    }
                    var fix = fix_;
                    if (first)
                    {
                        first = false;
                        if (ciset.CommandInfos.Count > 0)
                        {
                            ciset.CommandInfos.AddSeparator();
                        }
                    }

                    ciset.CommandInfos.Add(fix.Title, new Action(() => RefactoringService.ApplyFix(fix, context)));
                }
            }

            if (ciset.CommandInfos.Count > 0)
            {
                ainfo.Add(ciset, null);
                added = true;
            }

            if (IdeApp.ProjectOperations.CanJumpToDeclaration(item))
            {
                var type = item as IType;
                if (type != null && type.GetDefinition().Parts.Count > 1)
                {
                    var declSet = new CommandInfoSet();
                    declSet.Text = GettextCatalog.GetString("_Go to Declaration");
                    var ct = type.GetDefinition();
                    foreach (var part in ct.Parts)
                    {
                        declSet.CommandInfos.Add(string.Format(GettextCatalog.GetString("{0}, Line {1}"), FormatFileName(part.Region.FileName), part.Region.BeginLine), new System.Action(new JumpTo(part).Run));
                    }
                    ainfo.Add(declSet);
                }
                else
                {
                    ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.GotoDeclaration), new System.Action(new JumpTo(item).Run));
                }
                added = true;
            }

            if (item is IMember)
            {
                var member = (IMember)item;
                if (member.IsOverride || member.ImplementedInterfaceMembers.Any())
                {
                    ainfo.Add(GettextCatalog.GetString("Go to _Base Symbol"), new System.Action(new GotoBase(member).Run));
                    added = true;
                }
            }

            if (!(item is IMethod && ((IMethod)item).SymbolKind == SymbolKind.Operator) && (item is IEntity || item is ITypeParameter || item is IVariable || item is INamespace))
            {
                ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindReferences), new System.Action(new FindRefs(item, false).Run));
                if (doc.HasProject && HasOverloads(doc.Project.ParentSolution, item))
                {
                    ainfo.Add(IdeApp.CommandService.GetCommandInfo(RefactoryCommands.FindAllReferences), new System.Action(new FindRefs(item, true).Run));
                }
                added = true;
            }

            if (item is IMember)
            {
                var member = (IMember)item;
                if (member.IsVirtual || member.IsAbstract || member.DeclaringType.Kind == TypeKind.Interface)
                {
                    var handler = new FindDerivedSymbolsHandler(doc, member);
                    if (handler.IsValid)
                    {
                        ainfo.Add(GettextCatalog.GetString("Find Derived Symbols"), new System.Action(handler.Run));
                        added = true;
                    }
                }
            }
            if (item is IMember)
            {
                var member = (IMember)item;
                if (member.SymbolKind == SymbolKind.Method || member.SymbolKind == SymbolKind.Indexer)
                {
                    var findMemberOverloadsHandler = new FindMemberOverloadsHandler(doc, member);
                    if (findMemberOverloadsHandler.IsValid)
                    {
                        ainfo.Add(GettextCatalog.GetString("Find Member Overloads"), new System.Action(findMemberOverloadsHandler.Run));
                        added = true;
                    }
                }
            }

            if (item is ITypeDefinition)
            {
                ITypeDefinition cls = (ITypeDefinition)item;
                foreach (var bc in cls.DirectBaseTypes)
                {
                    if (bc != null && bc.GetDefinition() != null && bc.GetDefinition().Kind != TypeKind.Interface /* TODO: && IdeApp.ProjectOperations.CanJumpToDeclaration (bc)*/)
                    {
                        ainfo.Add(GettextCatalog.GetString("Go to _Base"), new System.Action(new GotoBase((ITypeDefinition)item).Run));
                        break;
                    }
                }
                if ((cls.Kind == TypeKind.Class && !cls.IsSealed) || cls.Kind == TypeKind.Interface)
                {
                    ainfo.Add(cls.Kind != TypeKind.Interface ? GettextCatalog.GetString("Find _derived classes") : GettextCatalog.GetString("Find _implementor classes"), new System.Action(new FindDerivedClasses(cls).Run));
                }
                ainfo.Add(GettextCatalog.GetString("Find Extension Methods"), new System.Action(new FindExtensionMethodHandler(doc, cls).Run));
                added = true;
            }

            if (added)
            {
                ainfo.AddSeparator();
            }
        }
Esempio n. 45
0
		protected XNode (DocumentLocation start) : base (start) {}
        public static IEnumerable <T> GetAnnotationsAtLocation <T> (MSBuildRootDocument doc, DocumentLocation location)
        {
            var xobj = doc.XDocument.FindNodeAtLocation(location);

            if (xobj == null)
            {
                return(null);
            }
            return(doc.Annotations
                   .GetMany <T> (xobj)
                   .Where(a => !(a is IRegionAnnotation ra) || ra.Region.Contains(location)));
        }
Esempio n. 47
0
 public string GetIndentationString(DocumentLocation loc)
 {
     return IndentationTracker.GetIndentationString(loc.Line, loc.Column);
 }
        static IEnumerable <string> GetPossibleNamespaces(Document doc, AstNode node, ResolveResult resolveResult, DocumentLocation location)
        {
            var unit = doc.ParsedDocument.GetAst <SyntaxTree> ();

            if (unit == null)
            {
                yield break;
            }

            int  tc                    = GetTypeParameterCount(node);
            var  attribute             = unit.GetNodeAt <ICSharpCode.NRefactory.CSharp.Attribute> (location);
            bool isInsideAttributeType = attribute != null && attribute.Type.Contains(location);
            var  compilation           = doc.Compilation;
            var  lookup                = new MemberLookup(null, compilation.MainAssembly);

            if (resolveResult is AmbiguousTypeResolveResult)
            {
                var aResult = resolveResult as AmbiguousTypeResolveResult;
                var file    = doc.ParsedDocument.ParsedFile as CSharpUnresolvedFile;
                var scope   = file.GetUsingScope(location).Resolve(compilation);
                while (scope != null)
                {
                    foreach (var u in scope.Usings)
                    {
                        foreach (var typeDefinition in u.Types)
                        {
                            if (typeDefinition.Name == aResult.Type.Name &&
                                typeDefinition.TypeParameterCount == tc &&
                                lookup.IsAccessible(typeDefinition, false))
                            {
                                yield return(typeDefinition.Namespace);
                            }
                        }
                    }
                    scope = scope.Parent;
                }
                yield break;
            }

            if (resolveResult is UnknownIdentifierResolveResult)
            {
                var    uiResult = resolveResult as UnknownIdentifierResolveResult;
                string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : null;
                foreach (var typeDefinition in compilation.GetAllTypeDefinitions())
                {
                    if ((typeDefinition.Name == uiResult.Identifier || typeDefinition.Name == possibleAttributeName) && typeDefinition.TypeParameterCount == tc &&
                        lookup.IsAccessible(typeDefinition, false))
                    {
                        yield return(typeDefinition.Namespace);
                    }
                }
                yield break;
            }

            if (resolveResult is UnknownMemberResolveResult)
            {
                var    umResult = (UnknownMemberResolveResult)resolveResult;
                string possibleAttributeName = isInsideAttributeType ? umResult.MemberName + "Attribute" : null;
                foreach (var typeDefinition in compilation.GetAllTypeDefinitions().Where(t => t.HasExtensionMethods))
                {
                    foreach (var method in typeDefinition.Methods.Where(m => m.IsExtensionMethod && (m.Name == umResult.MemberName || m.Name == possibleAttributeName)))
                    {
                        IType[] inferredTypes;
                        if (CSharpResolver.IsEligibleExtensionMethod(
                                compilation.Import(umResult.TargetType),
                                method,
                                true,
                                out inferredTypes
                                ))
                        {
                            yield return(typeDefinition.Namespace);

                            goto skipType;
                        }
                    }
skipType:
                    ;
                }
                yield break;
            }

            if (resolveResult is ErrorResolveResult)
            {
                var identifier = unit != null?unit.GetNodeAt <Identifier> (location) : null;

                if (identifier != null)
                {
                    var uiResult = resolveResult as UnknownIdentifierResolveResult;
                    if (uiResult != null)
                    {
                        string possibleAttributeName = isInsideAttributeType ? uiResult.Identifier + "Attribute" : null;
                        foreach (var typeDefinition in compilation.GetAllTypeDefinitions())
                        {
                            if ((identifier.Name == uiResult.Identifier || identifier.Name == possibleAttributeName) &&
                                typeDefinition.TypeParameterCount == tc &&
                                lookup.IsAccessible(typeDefinition, false))
                            {
                                yield return(typeDefinition.Namespace);
                            }
                        }
                    }
                }
                yield break;
            }
        }
 public DocumentDefinitionLocation(DocumentLocation location)
 {
     Location = location;
 }
Esempio n. 50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MonoDevelop.CodeIssues.CodeIssue"/> class.
 /// </summary>
 public CodeIssue(string description, string fileName, DocumentLocation start, DocumentLocation end, string inspectorIdString, IEnumerable <MonoDevelop.CodeActions.CodeAction> actions = null) : this(description, new DomRegion(fileName, start, end), inspectorIdString, actions)
 {
 }
		public void TestSelectAllCaretMovement ()
		{
			TextEditorData data = new Mono.TextEditor.TextEditorData  ();
			data.Document.Text = 
				@"123456789
123456789
123456789
123456789
123456789
123456789";
			
			Assert.IsFalse (data.IsSomethingSelected);
			var loc = new DocumentLocation (3, 3);
			data.Caret.Location = loc;
			SelectionActions.SelectAll (data);
			Assert.IsTrue (data.IsSomethingSelected);
			
			Assert.AreEqual (data.SelectionRange.Offset, 0);
			Assert.AreEqual (data.SelectionRange.EndOffset, data.Document.TextLength);
			Assert.AreEqual (loc, data.Caret.Location);
		}
Esempio n. 52
0
        public void ParseListFile(string listFileContents)
        {
            var               calcToFile         = new Dictionary <CalcLocation, DocumentLocation>(700000);
            var               fileToCalc         = new Dictionary <DocumentLocation, CalcLocation>(700000);
            var               callerInfo         = new Dictionary <CalcLocation, CallerInformation>();
            FcreateFile       currentFcreateFile = null;
            FilePath          currentFile        = new FilePath(string.Empty);
            var               lines          = listFileContents.Split('\n');
            var               fcreateForFile = new Dictionary <FilePath, FcreateFile>();
            CallerInformation callInfoToAdd  = null;

            for (int i = 0; i < lines.Length; i++)
            {
                var line = lines[i];
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                Match fileMatch = FileRegex.Match(line);
                if (fileMatch.Success)
                {
                    string file = fileMatch.Groups["file"].Value.Trim();
                    if (file == "fcreate")
                    {
                        if (!fcreateForFile.TryGetValue(currentFile, out currentFcreateFile))
                        {
                            currentFcreateFile          = new FcreateFile();
                            fcreateForFile[currentFile] = currentFcreateFile;
                        }
                        currentFile = new FilePath(currentFile + ".fcreate");
                    }
                    else
                    {
                        currentFile        = new FilePath(file);
                        currentFcreateFile = null;
                    }
                }
                else
                {
                    Match listingMatch = ListingRegex.Match(line);
                    if (!listingMatch.Success)
                    {
                        continue;
                    }

                    string stringLineNumber = listingMatch.Groups["lineNum"].Value.Trim();
                    int    lineNumber       = int.Parse(stringLineNumber);
                    ushort address          = ushort.Parse(listingMatch.Groups["addr"].Value, NumberStyles.HexNumber);
                    byte   page             = byte.Parse(listingMatch.Groups["page"].Value, NumberStyles.HexNumber);
                    string codeLine         = listingMatch.Groups["line"].Value;

                    // correction for ram pages
                    if (page == 0 && address >= 0x8000 && address < 0xC000)
                    {
                        page = 1;
                    }

                    if (currentFcreateFile != null)
                    {
                        lineNumber += currentFcreateFile.Lines;
                        currentFcreateFile.Builder.AppendLine(listingMatch.Groups["line"].Value.TrimEnd());
                        currentFcreateFile.Lines++;
                    }

                    if (listingMatch.Groups["byte1"].Value.Contains("-") || string.IsNullOrWhiteSpace(listingMatch.Groups["byte1"].Value))
                    {
                        continue;
                    }

                    DocumentLocation key   = new DocumentLocation(currentFile, lineNumber);
                    CalcLocation     value = new CalcLocation(address, page, address >= 0x8000);

                    do
                    {
                        line         = lines[i + 1];
                        listingMatch = ListingContRegex.Match(line);
                        if (!listingMatch.Success)
                        {
                            continue;
                        }

                        i++;
                        codeLine = listingMatch.Groups["line"].Value;
                    } while (listingMatch.Success);

                    if (callInfoToAdd != null)
                    {
                        callerInfo.Add(value, callInfoToAdd);
                    }

                    callInfoToAdd = ParseCallLine(codeLine, key);

                    if (!calcToFile.ContainsKey(value))
                    {
                        calcToFile.Add(value, key);
                    }

                    if (!fileToCalc.ContainsKey(key))
                    {
                        fileToCalc.Add(key, value);
                    }
                }
            }

            foreach (var file in fcreateForFile)
            {
                var filePath = new FilePath(file.Key + ".fcreate");
                using (var writer = new StreamWriter(filePath))
                {
                    writer.Write(file.Value.Builder.ToString());
                }
            }

            _fileToCalc        = fileToCalc;
            _calcToFile        = calcToFile;
            _callerInformation = callerInfo;
        }
		public XProcessingInstruction (DocumentLocation start) : base (start) {}
Esempio n. 54
0
        protected virtual async Task <ICompletionDataList> HandleCodeCompletion(
            CodeCompletionContext completionContext, bool forced, CancellationToken token)
        {
            var buf = this.Editor;

            // completionChar may be a space even if the current char isn't, when ctrl-space is fired t
            var  currentLocation = new DocumentLocation(completionContext.TriggerLine, completionContext.TriggerLineOffset);
            char currentChar     = completionContext.TriggerOffset < 1? ' ' : buf.GetCharAt(completionContext.TriggerOffset - 1);
            char previousChar    = completionContext.TriggerOffset < 2? ' ' : buf.GetCharAt(completionContext.TriggerOffset - 2);

            LoggingService.LogDebug("Attempting completion for state '{0}'x{1}, previousChar='{2}',"
                                    + " currentChar='{3}', forced='{4}'", tracker.Engine.CurrentState,
                                    tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);

            //closing tag completion
            if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
            {
                return(ClosingTagCompletion(buf, currentLocation));
            }

            // Auto insert '>' when '/' is typed inside tag state (for quick tag closing)
            //FIXME: avoid doing this when the next non-whitespace char is ">" or ignore the next ">" typed
            if (XmlEditorOptions.AutoInsertFragments && tracker.Engine.CurrentState is XmlTagState && currentChar == '/')
            {
                buf.InsertAtCaret(">");
                return(null);
            }

            //entity completion
            if (currentChar == '&' && (tracker.Engine.CurrentState is XmlRootState ||
                                       tracker.Engine.CurrentState is XmlAttributeValueState))
            {
                var list = new CompletionDataList();

                //TODO: need to tweak semicolon insertion
                list.Add("apos").Description = "'";
                list.Add("quot").Description = "\"";
                list.Add("lt").Description   = "<";
                list.Add("gt").Description   = ">";
                list.Add("amp").Description  = "&";

                //not sure about these "completions". they're more like
                //shortcuts than completions but they're pretty useful
                list.Add("'").CompletionText  = "apos;";
                list.Add("\"").CompletionText = "quot;";
                list.Add("<").CompletionText  = "lt;";
                list.Add(">").CompletionText  = "gt;";
                list.Add("&").CompletionText  = "amp;";

                var ecList = await GetEntityCompletions(token);

                list.AddRange(ecList);
                return(list);
            }

            //doctype completion
            if (tracker.Engine.CurrentState is XmlDocTypeState)
            {
                if (tracker.Engine.CurrentStateLength == 1)
                {
                    CompletionDataList list = await GetDocTypeCompletions(token);

                    if (list != null && list.Count > 0)
                    {
                        return(list);
                    }
                }
                return(null);
            }

            //attribute value completion
            //determine whether to trigger completion within attribute values quotes
            if ((Tracker.Engine.CurrentState is XmlAttributeValueState)
                //trigger on the opening quote
                && ((Tracker.Engine.CurrentStateLength == 1 && (currentChar == '\'' || currentChar == '"'))
                    //or trigger on first letter of value, if unforced
                    || (forced || Tracker.Engine.CurrentStateLength == 2)))
            {
                var att = (XAttribute)Tracker.Engine.Nodes.Peek();

                if (att.IsNamed)
                {
                    var attributedOb = Tracker.Engine.Nodes.Peek(1) as IAttributedXObject;
                    if (attributedOb == null)
                    {
                        return(null);
                    }

                    //if triggered by first letter of value or forced, grab those letters

                    var result = await GetAttributeValueCompletions(attributedOb, att, token);

                    if (result != null)
                    {
                        result.TriggerWordLength = Tracker.Engine.CurrentStateLength - 1;
                        return(result);
                    }
                    return(null);
                }
            }

            //attribute name completion
            if ((forced && Tracker.Engine.Nodes.Peek() is IAttributedXObject && !tracker.Engine.Nodes.Peek().IsEnded) ||
                ((Tracker.Engine.CurrentState is XmlNameState &&
                  Tracker.Engine.CurrentState.Parent is XmlAttributeState) ||
                 Tracker.Engine.CurrentState is XmlTagState) &&
                (Tracker.Engine.CurrentStateLength == 1 || forced))
            {
                IAttributedXObject attributedOb = (Tracker.Engine.Nodes.Peek() as IAttributedXObject) ??
                                                  Tracker.Engine.Nodes.Peek(1) as IAttributedXObject;
                if (attributedOb == null)
                {
                    return(null);
                }

                //attributes
                if (attributedOb.Name.IsValid && (forced ||
                                                  (char.IsWhiteSpace(previousChar) && char.IsLetter(currentChar))))
                {
                    var existingAtts = new Dictionary <string, string> (StringComparer.OrdinalIgnoreCase);

                    foreach (XAttribute att in attributedOb.Attributes)
                    {
                        existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
                    }
                    var result = await GetAttributeCompletions(attributedOb, existingAtts, token);

                    if (result != null)
                    {
                        if (!forced)
                        {
                            result.TriggerWordLength = 1;
                        }
                        return(result);
                    }
                    return(null);
                }
            }

//			if (Tracker.Engine.CurrentState is XmlRootState) {
//				if (line < 3) {
//				cp.Add ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
//			}

            //element completion
            if (currentChar == '<' && tracker.Engine.CurrentState is XmlRootState ||
                (tracker.Engine.CurrentState is XmlNameState && forced))
            {
                var list = await GetElementCompletions(token);

                AddCloseTag(list, Tracker.Engine.Nodes);
                return(list.Count > 0 ? list : null);
            }

            if (forced && Tracker.Engine.CurrentState is XmlRootState)
            {
                var list = new CompletionDataList();
                MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName(DocumentContext.Name, list);
                return(list.Count > 0? list : null);
            }

            return(null);
        }
Esempio n. 55
0
        public Chromatogram[] GetChromatograms(DocumentLocation documentLocation)
        {
            if (documentLocation == null)
                return new Chromatogram[0];
            var result = new List<Chromatogram>();
            SrmDocument document = Program.MainWindow.Document;
            Bookmark bookmark = Bookmark.ToBookmark(documentLocation, document);
            IdentityPath identityPath = bookmark.IdentityPath;
            var nodeList = GetDocNodes(identityPath, document);
            TransitionDocNode transitionDocNode = null;
            if (nodeList.Count > 3)
            {
                transitionDocNode = (TransitionDocNode) nodeList[3];
            }
            var measuredResults = document.Settings.MeasuredResults;
            var nodePep = (PeptideDocNode)(nodeList.Count > 1 ? nodeList[1] : null);
            if (null == nodePep)
            {
                return result.ToArray();
            }

            int iColor = 0;

            foreach (var chromatogramSet in measuredResults.Chromatograms)
            {
                foreach (var msDataFileInfo in chromatogramSet.MSDataFileInfos)
                {
                    if (bookmark.ChromFileInfoId != null && !ReferenceEquals(msDataFileInfo.FileId, bookmark.ChromFileInfoId))
                    {
                        continue;
                    }

                    foreach (var nodeGroup in nodePep.TransitionGroups)
                    {
                        if (nodeList.Count > 2 && !Equals(nodeGroup, nodeList[2]))
                        {
                            continue;
                        }
                        ChromatogramGroupInfo[] arrayChromInfo;
                        measuredResults.TryLoadChromatogram(
                            chromatogramSet,
                            nodePep,
                            nodeGroup,
                            (float) document.Settings.TransitionSettings.Instrument.MzMatchTolerance,
                            true,
                            out arrayChromInfo);
                        foreach (var transition in nodeGroup.Transitions)
                        {
                            if (transitionDocNode != null && !Equals(transitionDocNode, transition))
                            {
                                continue;
                            }
                            foreach (var chromatogramGroup in arrayChromInfo)
                            {
                                for (int iTransition = 0; iTransition < chromatogramGroup.NumTransitions; iTransition++)
                                {
                                    ChromatogramInfo transitionInfo = chromatogramGroup.GetTransitionInfo(iTransition);
                                    if (Math.Abs(transitionInfo.ProductMz - transition.Mz) >
                                        document.Settings.TransitionSettings.Instrument.MzMatchTolerance)
                                    {
                                        continue;
                                    }
                                    Color color = GraphChromatogram.COLORS_LIBRARY[iColor % GraphChromatogram.COLORS_LIBRARY.Length];
                                    iColor++;
                                    result.Add(new Chromatogram
                                    {
                                        Intensities = transitionInfo.Intensities,
                                        ProductMz = transitionInfo.ProductMz,
                                        PrecursorMz = chromatogramGroup.PrecursorMz,
                                        Times = transitionInfo.Times,
                                        Color = color
                                    });
                                }
                            }
                        }
                    }
                }
            }

            if (result.Count == 1)
                result[0].Color = ChromGraphItem.ColorSelected;

            return result.ToArray();
        }
Esempio n. 56
0
 public static string GetIndentationString(this IIndentationTracker thisObject, DocumentLocation loc)
 {
     return(thisObject.GetIndentationString(loc.Line, loc.Column));
 }
Esempio n. 57
0
 /// <summary>
 /// Select a document location in Skyline's tree view.
 /// </summary>
 /// <param name="documentLocation">Which location to select (null for insert node).</param>
 public void SetDocumentLocation(DocumentLocation documentLocation)
 {
     Program.MainWindow.Invoke(new Action(() =>
     {
         if (documentLocation == null)
             Program.MainWindow.SelectPath(new IdentityPath(SequenceTree.NODE_INSERT_ID));
         else
         {
             Bookmark bookmark = Bookmark.ToBookmark(documentLocation, Program.MainWindow.DocumentUI);
             Program.MainWindow.NavigateToBookmark(bookmark);
         }
     }));
 }
Esempio n. 58
0
 public static int GetVirtualIndentationColumn(this IIndentationTracker thisObject, DocumentLocation loc)
 {
     return(thisObject.GetVirtualIndentationColumn(loc.Line, loc.Column));
 }
Esempio n. 59
0
		protected virtual ICompletionDataList ClosingTagCompletion (TextEditor buf, DocumentLocation currentLocation)

		{

			//get name of current node in document that's being ended

			var el = tracker.Engine.Nodes.Peek () as XElement;

			if (el != null && el.Region.End >= currentLocation && !el.IsClosed && el.IsNamed) {

				string tag = String.Concat ("</", el.Name.FullName, ">");

				if (XmlEditorOptions.AutoCompleteElements) {



					//						//make sure we have a clean atomic undo so the user can undo the tag insertion

					//						//independently of the >

					//						bool wasInAtomicUndo = this.Editor.Document.IsInAtomicUndo;

					//						if (wasInAtomicUndo)

					//							this.Editor.Document.EndAtomicUndo ();



					using (var undo = buf.OpenUndoGroup ()) {

						buf.InsertText (buf.CaretOffset, tag);

						buf.CaretOffset -= tag.Length;

					}



					//						if (wasInAtomicUndo)

					//							this.Editor.Document.BeginAtomicUndo ();



					return null;

				} else {

					var cp = new CompletionDataList ();

					cp.Add (new XmlTagCompletionData (tag, 0, true));

					return cp;

				}

			}

			return null;
		}
Esempio n. 60
0
 void StoreWidgetState()
 {
     // vSave  = textEditor.VAdjustment.Value;
     // hSave  = textEditor.HAdjustment.Value;
     caretSave = textEditor.Caret.Location;
 }