public async Task TestBug60365()
        {
            var             tww     = new TestWorkbenchWindow();
            TestViewContent content = new TestViewContent();

            tww.ViewContent       = content;
            content.ContentName   = "/a.cs";
            content.Data.MimeType = "text/x-csharp";

            var doc = new MonoDevelop.Ide.Gui.Document(tww);

            var text   = "@c$";
            int endPos = text.IndexOf('$');

            if (endPos >= 0)
            {
                text = text.Substring(0, endPos) + text.Substring(endPos + 1);
            }

            content.Text           = text;
            content.CursorPosition = System.Math.Max(0, endPos);

            var project = MonoDevelop.Projects.Services.ProjectService.CreateProject("C#");

            project.Name     = "test";
            project.FileName = "test.csproj";
            project.Files.Add(new ProjectFile(content.ContentName, BuildAction.Compile));

            var solution = new MonoDevelop.Projects.Solution();

            solution.AddConfiguration("", true);
            solution.DefaultSolutionFolder.AddItem(project);
            using (var monitor = new ProgressMonitor())
                await TypeSystemService.Load(solution, monitor);
            content.Project = project;
            doc.SetProject(project);

            var ext = new CSharpCompletionTextEditorExtension();

            ext.Initialize(doc.Editor, doc);
            var listWindow = new CompletionListWindow();
            var widget     = new TestCompletionWidget(ext.Editor, ext.DocumentContext);

            listWindow.CompletionWidget      = widget;
            listWindow.CodeCompletionContext = widget.CurrentCodeCompletionContext;

            var list = await ext.HandleCodeCompletionAsync(widget.CurrentCodeCompletionContext, new CompletionTriggerInfo (CompletionTriggerReason.CharTyped, 'c'));

            var ka = KeyActions.Complete;

            list.First(d => d.CompletionText == "class").InsertCompletionText(listWindow, ref ka, KeyDescriptor.Tab);

            Assert.AreEqual("@class", content.Text);

            content.Contents.Add(ext);

            await doc.UpdateParseDocument();

            TypeSystemService.Unload(solution);
        }
예제 #2
0
 void UpdateFileOpenInfo(MonoDevelop.Ide.Gui.Document document, int line, int column)
 {
     try {
         var existingFileInfo = _recentDocuments.FirstOrDefault((arg) => arg.Project.ItemId == document.Project.ItemId && arg.FileName.FullPath == document.FileName.FullPath);
         if (existingFileInfo != null)
         {
             _recentDocuments.Remove(existingFileInfo);
         }
         if (GetProjectWithId(document.Project.ItemId) != null && File.Exists(document.FileName.FullPath))
         {
             var fileInfo = new FileOpenInformation(document.FileName.FullPath, document.Project, line, column, OpenDocumentOptions.BringToFront | OpenDocumentOptions.TryToReuseViewer);
             _recentDocuments.Insert(0, fileInfo);
         }
         if (_recentDocuments.Count >= MaxDocuments)
         {
             var numberOfDocumentsToPurge = _recentDocuments.Count - MaxDocuments;
             for (int i = 0; i < numberOfDocumentsToPurge; i++)
             {
                 _recentDocuments.RemoveAt(_recentDocuments.Count - 1);
             }
         }
     } catch (Exception ex) {
         Console.WriteLine("error updating file info " + ex.Message);
     }
 }
예제 #3
0
        public static void QueueQuickFixAnalysis(MonoDevelop.Ide.Gui.Document doc, DomLocation loc, Action <List <ContextAction> > callback)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                try {
                    string disabledNodes = PropertyService.Get("ContextActions." + doc.Editor.Document.MimeType, "") ?? "";

                    var availableFixes = new List <ContextAction> (contextActions.Where(fix => disabledNodes.IndexOf(fix.Type.FullName) < 0 && fix.Action.IsValid(doc, loc)).Select(fix => fix.Action));
                    var ext            = doc.GetContent <MonoDevelop.AnalysisCore.Gui.ResultsEditorExtension> ();
                    if (ext != null)
                    {
                        foreach (var result in ext.GetResultsAtOffset(doc.Editor.LocationToOffset(loc.Line, loc.Column)))
                        {
                            var fresult = result as FixableResult;
                            if (fresult == null)
                            {
                                continue;
                            }
                            foreach (var action in FixOperationsHandler.GetActions(doc, fresult))
                            {
                                availableFixes.Add(new AnalysisContextAction(result, action));
                            }
                        }
                    }

                    callback(availableFixes);
                } catch (Exception ex) {
                    LoggingService.LogError("Error in analysis service", ex);
                }
            });
        }
예제 #4
0
        public async Task TestBug58473()
        {
            var text   = @"$";
            int endPos = text.IndexOf('$');

            if (endPos >= 0)
            {
                text = text.Substring(0, endPos) + text.Substring(endPos + 1);
            }

            var project = Ide.Services.ProjectService.CreateDotNetProject("C#");

            project.Name = "test";
            project.References.Add(MonoDevelop.Projects.ProjectReference.CreateAssemblyReference("mscorlib"));
            project.References.Add(MonoDevelop.Projects.ProjectReference.CreateAssemblyReference("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
            project.References.Add(MonoDevelop.Projects.ProjectReference.CreateAssemblyReference("System.Core"));

            project.FileName = "test.csproj";
            project.Files.Add(new ProjectFile("/a.cs", BuildAction.Compile));

            var solution = new MonoDevelop.Projects.Solution();

            solution.AddConfiguration("", true);
            solution.DefaultSolutionFolder.AddItem(project);
            using (var monitor = new ProgressMonitor())
                await TypeSystemService.Load(solution, monitor);

            var tww     = new TestWorkbenchWindow();
            var content = new TestViewContent();

            tww.ViewContent       = content;
            content.ContentName   = "/a.cs";
            content.Data.MimeType = "text/x-csharp";
            content.Project       = project;


            content.Text           = text;
            content.CursorPosition = Math.Max(0, endPos);
            var doc = new MonoDevelop.Ide.Gui.Document(tww);

            doc.SetProject(project);

            var compExt = new CSharpCompletionTextEditorExtension();

            compExt.Initialize(doc.Editor, doc);
            content.Contents.Add(compExt);

            await doc.UpdateParseDocument();

            var ctx = new CodeCompletionContext();

            var tmp = IdeApp.Preferences.EnableAutoCodeCompletion;

            IdeApp.Preferences.EnableAutoCodeCompletion.Set(false);
            var list = await compExt.HandleCodeCompletionAsync(ctx, CompletionTriggerInfo.CodeCompletionCommand);

            Assert.IsNotNull(list);
            IdeApp.Preferences.EnableAutoCodeCompletion.Set(tmp);
            project.Dispose();
        }
        public static MethodDeclarationAtCaret Create(MonoDevelop.Ide.Gui.Document doc)
        {
            var parsedDocument = doc.DocumentContext.AnalysisDocument;

            if (parsedDocument == null)
            {
                return(NullMethodDeclaration);
            }

            SyntaxNode root = null;

            if (!parsedDocument.TryGetSyntaxRoot(out root))
            {
                return(NullMethodDeclaration);
            }

            SyntaxNode currentNode;

            try {
                int caretOffset = doc.Editor.CaretOffset;
                currentNode = root.FindNode(TextSpan.FromBounds(caretOffset, caretOffset));
            } catch (Exception) {
                return(NullMethodDeclaration);
            }

            var currentType   = currentNode.AncestorsAndSelf().OfType <TypeDeclarationSyntax> ().FirstOrDefault();
            var currentMethod = currentNode.AncestorsAndSelf().OfType <MethodDeclarationSyntax> ().FirstOrDefault();

            return(new MethodDeclarationAtCaret {
                TypeDeclaration = currentType,
                MethodDeclaration = currentMethod
            });
        }
예제 #6
0
            public CSharpChunkParser(SpanParser spanParser, Mono.TextEditor.Document doc, ColorSheme style, SyntaxMode mode, LineSegment line) : base(spanParser, doc, style, mode, line)
            {
                document = IdeApp.Workbench.GetDocument(doc.FileName);

                foreach (var tag in ProjectDomService.SpecialCommentTags)
                {
                    tags.Add(tag.Tag);
                }
//				ICSharpCode.OldNRefactory.Ast.CompilationUnit unit = null;
//				if (document != null && document.ParsedDocument != null && MonoDevelop.Core.PropertyService.Get ("EnableSemanticHighlighting", false)) {
//					resolver = document.GetResolver ();
//					if (!document.ParsedDocument.TryGetTag (out unit)) {
//						try {
//							using (ICSharpCode.OldNRefactory.IParser parser = ICSharpCode.OldNRefactory.ParserFactory.CreateParser (ICSharpCode.OldNRefactory.SupportedLanguage.CSharp, document.Editor.Document.OpenTextReader ())) {
//								parser.Parse ();
//								unit = parser.CompilationUnit;
//								document.ParsedDocument.SetTag (unit);
//							}
//						} catch (Exception) {
//							resolver = null;
//							return;
//						}
//					}
//					resolver.SetupParsedCompilationUnit (unit);
//				}
            }
 public override void DisableOnce(MonoDevelop.Ide.Gui.Document document, DocumentRegion loc)
 {
     document.Editor.Insert(
         document.Editor.LocationToOffset(loc.BeginLine, 1),
         document.Editor.IndentationTracker.GetIndentationString(loc.Begin) + "// ReSharper disable once " + attr.ResharperDisableKeyword + document.Editor.EolMarker
         );
 }
예제 #8
0
 public override void DisableWithPragma(MonoDevelop.Ide.Gui.Document document, DocumentLocation loc)
 {
     using (document.Editor.OpenUndoGroup()) {
         document.Editor.Insert(document.Editor.LocationToOffset(loc.Line + 1, 1), "#pragma warning restore " + attr.PragmaWarning + document.Editor.EolMarker);
         document.Editor.Insert(document.Editor.LocationToOffset(loc.Line, 1), "#pragma warning disable " + attr.PragmaWarning + document.Editor.EolMarker);
     }
 }
예제 #9
0
        public static void QueueQuickFixAnalysis(MonoDevelop.Ide.Gui.Document doc, TextLocation loc, Action <List <MonoDevelop.CodeActions.CodeAction> > callback)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(delegate {
                try {
                    var result = new List <MonoDevelop.CodeActions.CodeAction> ();

                    var ext = doc.GetContent <MonoDevelop.AnalysisCore.Gui.ResultsEditorExtension> ();
                    if (ext != null)
                    {
                        foreach (var r in ext.GetResultsAtOffset(doc.Editor.LocationToOffset(loc)).OrderBy(r => r.Level))
                        {
                            var fresult = r as FixableResult;
                            if (fresult == null)
                            {
                                continue;
                            }
                            foreach (var action in FixOperationsHandler.GetActions(doc, fresult))
                            {
                                result.Add(new AnalysisContextActionProvider.AnalysisCodeAction(action, r));
                            }
                        }
                    }
                    result.AddRange(GetValidActions(doc, loc).Result);
                    callback(result);
                } catch (Exception ex) {
                    LoggingService.LogError("Error in analysis service", ex);
                }
            });
        }
예제 #10
0
 protected override void Update(CommandArrayInfo ainfo)
 {
     MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
     if (doc != null)
     {
         SourceEditorView view = IdeApp.Workbench.ActiveDocument.GetContent <SourceEditorView>();
         if (view != null)
         {
             DocumentLocation location = view.TextEditor.Caret.Location;
             if (location.IsEmpty)
             {
                 return;
             }
             DocumentLine line = view.Document.GetLine(location.Line);
             if (line == null || line.Markers == null)
             {
                 return;
             }
             foreach (TextLineMarker marker in line.Markers)
             {
                 UrlMarker urlMarker = marker as UrlMarker;
                 if (urlMarker != null)
                 {
                     if (urlMarker.StartColumn <= location.Column && location.Column < urlMarker.EndColumn)
                     {
                         ainfo.Add(urlMarker.UrlType == UrlType.Email ? GettextCatalog.GetString("_Write an e-mail to...") : GettextCatalog.GetString("_Open URL..."), urlMarker);
                         ainfo.AddSeparator();
                     }
                 }
             }
         }
     }
 }
예제 #11
0
 public override void DisableAndRestore(MonoDevelop.Ide.Gui.Document document, DocumentLocation loc)
 {
     using (document.Editor.OpenUndoGroup()) {
         document.Editor.Insert(document.Editor.LocationToOffset(loc.Line + 1, 1), "// ReSharper restore " + attr.ResharperDisableKeyword + document.Editor.EolMarker);
         document.Editor.Insert(document.Editor.LocationToOffset(loc.Line, 1), "// ReSharper disable " + attr.ResharperDisableKeyword + document.Editor.EolMarker);
     }
 }
예제 #12
0
        public override IEnumerable <MonoDevelop.CodeActions.CodeAction> GetActions(MonoDevelop.Ide.Gui.Document document, TextLocation loc, CancellationToken cancellationToken)
        {
            var context = new MDRefactoringContext(document, loc);

            if (context.IsInvalid || context.RootNode == null)
            {
                yield break;
            }
            var actions = provider.GetActions(context);

            if (actions == null)
            {
                LoggingService.LogWarning(provider + " returned null actions.");
                yield break;
            }
            int num = 0;

            foreach (var action_ in actions)
            {
                var action = action_;
                if (actionId.Count <= num)
                {
                    actionId.Add(provider.GetType().FullName + "'" + num);
                }
                yield return(new NRefactoryCodeAction(actionId[num], GettextCatalog.GetString(action.Description ?? ""), action));

                num++;
            }
        }
예제 #13
0
		public IParameterDataProvider HandleParameterCompletion (MonoDevelop.Ide.Gui.Document realDocument, CodeCompletionContext completionContext, DocumentInfo info, LocalDocumentInfo localInfo, char completionChar)
		{
			CodeCompletionContext ccc;
			using (var completion = CreateCompletion (realDocument, info, localInfo, out ccc)) {
				return completion.HandleParameterCompletion (completionContext, completionChar);
			}
		}
예제 #14
0
		public ICompletionDataList HandleCompletion (MonoDevelop.Ide.Gui.Document realDocument, CodeCompletionContext completionContext, DocumentInfo info, LocalDocumentInfo localInfo, char currentChar, ref int triggerWordLength)
		{
			CodeCompletionContext ccc;
			using (var completion = CreateCompletion (realDocument, info, localInfo, out ccc)) {
				return completion.HandleCodeCompletion (completionContext, currentChar, ref triggerWordLength);
			}
		}
        public static void QueueQuickFixAnalysis(MonoDevelop.Ide.Gui.Document doc, TextLocation loc, CancellationToken token, Action <List <MonoDevelop.CodeActions.CodeAction> > callback)
        {
            var ext    = doc.GetContent <MonoDevelop.AnalysisCore.Gui.ResultsEditorExtension> ();
            var issues = ext != null?ext.GetResultsAtOffset(doc.Editor.LocationToOffset(loc), token).OrderBy(r => r.Level).ToList() : new List <Result> ();

            ThreadPool.QueueUserWorkItem(delegate {
                try {
                    var result = new List <MonoDevelop.CodeActions.CodeAction> ();
                    foreach (var r in issues)
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        var fresult = r as FixableResult;
                        if (fresult == null)
                        {
                            continue;
                        }
                        foreach (var action in FixOperationsHandler.GetActions(doc, fresult))
                        {
                            result.Add(new AnalysisContextActionProvider.AnalysisCodeAction(action, r)
                            {
                                DocumentRegion = action.DocumentRegion
                            });
                        }
                    }
                    result.AddRange(GetValidActions(doc, loc).Result);
                    callback(result);
                } catch (Exception ex) {
                    LoggingService.LogError("Error in analysis service", ex);
                }
            });
        }
        void AttachViewContents(MonoDevelop.Ide.Gui.Document document)
        {
            if (document == null || document.Project == null)
            {
                return;
            }
            var repo = VersionControlService.GetRepository(document.Project);

            if (repo == null)
            {
                return;
            }
            if (!document.IsFile || !repo.GetVersionInfo(document.FileName).IsVersioned)
            {
                return;
            }
            if (document.Editor == null)
            {
                return;
            }

            var item = new VersionControlItem(repo, document.Project, document.FileName, false, null);

            TryAttachView <IDiffView> (document, item, DiffCommand.DiffViewHandlers);
            TryAttachView <IBlameView> (document, item, BlameCommand.BlameViewHandlers);
            TryAttachView <ILogView> (document, item, LogCommand.LogViewHandlers);
            TryAttachView <IMergeView> (document, item, MergeCommand.MergeViewHandlers);
        }
예제 #17
0
		public ICompletionDataList HandlePopupCompletion (MonoDevelop.Ide.Gui.Document realDocument, DocumentInfo info, LocalDocumentInfo localInfo)
		{
			CodeCompletionContext codeCompletionContext;
			using (var completion = CreateCompletion (realDocument, info, localInfo, out codeCompletionContext)) {
				return completion.CodeCompletionCommand (codeCompletionContext);
			}
		}
예제 #18
0
        CSharpTextEditorCompletion CreateCompletion(MonoDevelop.Ide.Gui.Document realDocument, DocumentInfo info, LocalDocumentInfo localInfo, out CodeCompletionContext codeCompletionContext)
        {
            var doc = new Mono.TextEditor.Document()
            {
                Text = localInfo.LocalDocument,
            };
            var documentLocation = doc.OffsetToLocation(localInfo.CaretPosition);

            codeCompletionContext = new CodeCompletionContext()
            {
                TriggerOffset     = localInfo.CaretPosition,
                TriggerLine       = documentLocation.Line,
                TriggerLineOffset = documentLocation.Column - 1
            };

            var r = new System.IO.StringReader(localInfo.LocalDocument);

            using (var parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, r)) {
                parser.Parse();
                return(new CSharpTextEditorCompletion(localInfo.HiddenDocument)
                {
                    ParsedUnit = parser.CompilationUnit,
                    CompletionWidget = CreateCompletionWidget(realDocument, localInfo),
                    Dom = localInfo.HiddenDocument.Dom
                });
            }
        }
예제 #19
0
 public static object GetItem(MonoDevelop.Ide.Gui.Document doc, out ResolveResult resolveResult)
 {
     resolveResult = GetResolveResult(doc);
     if (resolveResult is LocalResolveResult)
     {
         return(((LocalResolveResult)resolveResult).Variable);
     }
     if (resolveResult is MemberResolveResult)
     {
         return(((MemberResolveResult)resolveResult).Member);
     }
     if (resolveResult is MethodGroupResolveResult)
     {
         var mg     = ((MethodGroupResolveResult)resolveResult);
         var method = mg.Methods.FirstOrDefault();
         if (method == null && mg.GetExtensionMethods().Any())
         {
             method = mg.GetExtensionMethods().First().FirstOrDefault();
         }
         return(method);
     }
     if (resolveResult is TypeResolveResult)
     {
         return(resolveResult.Type);
     }
     if (resolveResult is NamespaceResolveResult)
     {
         return(((NamespaceResolveResult)resolveResult).Namespace);
     }
     if (resolveResult is OperatorResolveResult)
     {
         return(((OperatorResolveResult)resolveResult).UserDefinedOperatorMethod);
     }
     return(null);
 }
예제 #20
0
		Document GetOpenDocument ()
		{
			MonoDevelop.Ide.Gui.Document document = containingProject.GetOpenFile (FileName);
			if (document != null) {
				return new Document (FileName, document);
			}
			return null;
		}
        protected override void Run()
        {
            MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument;
            var    textEditorData            = doc.GetContent <ITextEditorDataProvider>().GetTextEditorData();
            string date = DateTime.Now.ToString();

            textEditorData.InsertAtCaret(date);
        }
예제 #22
0
        public bool GetParameterCompletionCommandOffset(MonoDevelop.Ide.Gui.Document realDocument, DocumentInfo info, LocalDocumentInfo localInfo, out int cpos)
        {
            CodeCompletionContext codeCompletionContext;

            using (var completion = CreateCompletion(realDocument, info, localInfo, out codeCompletionContext)) {
                return(completion.GetParameterCompletionCommandOffset(out cpos));
            }
        }
예제 #23
0
		public void Save (string fileName = null)
		{
			DispatchService.GuiSyncDispatch (() => {
				MonoDevelop.Ide.Gui.Document document = containingProject.GetOpenFile (FileName);
				if (document != null) {
					document.Save ();
				}
			});
		}
예제 #24
0
        public CodeActionWidget(CodeActionEditorExtension ext, MonoDevelop.Ide.Gui.Document document)
        {
//			this.ext = ext;
            this.document = document;
            Events        = Gdk.EventMask.AllEventsMask;
            icon          = ImageService.GetPixbuf("md-text-quickfix", Gtk.IconSize.Menu);
            SetSizeRequest(Math.Max((int)document.Editor.LineHeight, icon.Width) + 4, (int)document.Editor.LineHeight + 4);
            document.Editor.Parent.EditorOptionsChanged += HandleDocumentEditorParentEditorOptionsChanged;
        }
예제 #25
0
        public ICompletionDataList HandleCompletion(MonoDevelop.Ide.Gui.Document document, DocumentInfo info,
                                                    LocalDocumentInfo localInfo, ProjectDom dom, char currentChar, ref int triggerWordLength)
        {
            CodeCompletionContext codeCompletionContext;

            using (var completion = CreateCompletion(document, info, localInfo, dom, out codeCompletionContext)) {
                return(completion.HandleCodeCompletion(codeCompletionContext, currentChar, ref triggerWordLength));
            }
        }
예제 #26
0
        public ImportSymbolCompletionData(MonoDevelop.Ide.Gui.Document doc, ImportSymbolCache cache, IType type)
        {
            this.doc   = doc;
            this.cache = cache;
//			this.data = doc.Editor;
            this.ambience = AmbienceService.GetAmbience(doc.Editor.MimeType);
            this.type     = type;
            this.unit     = doc.ParsedDocument;
        }
예제 #27
0
		public CodeActionWidget (CodeActionEditorExtension ext, MonoDevelop.Ide.Gui.Document document)
		{
//			this.ext = ext;
			this.document = document;
			Events = Gdk.EventMask.AllEventsMask;
			icon = ImageService.GetPixbuf ("md-text-quickfix", Gtk.IconSize.Menu);
			SetSizeRequest (Math.Max ((int)document.Editor.LineHeight , icon.Width) + 4, (int)document.Editor.LineHeight + 4);
			document.Editor.Parent.EditorOptionsChanged += HandleDocumentEditorParentEditorOptionsChanged;
		}
예제 #28
0
 public CodeCoverageView(MonoDevelop.Ide.Gui.Document doc)
 {
     this.origDoc = doc;
     file         = doc.FileName;
     if (doc.HasProject)
     {
         Project = doc.Project;
     }
 }
        public override void SuppressWithAttribute(MonoDevelop.Ide.Gui.Document document, DocumentRegion loc)
        {
            var member = document.ParsedDocument.GetMember(loc.End);

            document.Editor.Insert(
                document.Editor.LocationToOffset(member.Region.BeginLine, 1),
                document.Editor.IndentationTracker.GetIndentationString(loc.Begin) + string.Format("[SuppressMessage(\"{0}\", \"{1}\")]" + document.Editor.EolMarker, attr.SuppressMessageCategory, attr.SuppressMessageCheckId)
                );
        }
예제 #30
0
        public IParameterDataProvider HandleParameterCompletion(MonoDevelop.Ide.Gui.Document document,
                                                                DocumentInfo info, LocalDocumentInfo localInfo, ProjectDom dom, char completionChar)
        {
            CodeCompletionContext codeCompletionContext;

            using (var completion = CreateCompletion(document, info, localInfo, dom, out codeCompletionContext)) {
                return(completion.HandleParameterCompletion(codeCompletionContext, completionChar));
            }
        }
예제 #31
0
        public static ResolveResult GetResolveResult(MonoDevelop.Ide.Gui.Document doc)
        {
            ITextEditorResolver textEditorResolver = doc.GetContent <ITextEditorResolver> ();

            if (textEditorResolver != null)
            {
                return(textEditorResolver.GetLanguageItem(doc.Editor.Caret.Offset));
            }
            return(null);
        }
예제 #32
0
		public ImportSymbolCompletionData (MonoDevelop.Ide.Gui.Document doc, ImportSymbolCache cache, ProjectDom dom, IType type)
		{
			this.doc = doc;
			this.cache = cache;
			this.dom = dom;
			this.data = doc.Editor;
			this.ambience = doc.Project != null ? doc.Project.Ambience : AmbienceService.GetAmbienceForFile (doc.FileName);
			this.type = type;
			this.unit = doc.CompilationUnit;
		}
		static async Task<Tuple<CSharpCompletionTextEditorExtension,TestViewContent>> Setup (string input)
		{
			TestWorkbenchWindow tww = new TestWorkbenchWindow ();
			TestViewContent content = new TestViewContent ();
			tww.ViewContent = content;
			content.ContentName = "/a.cs";
			content.Data.MimeType = "text/x-csharp";

			var doc = new MonoDevelop.Ide.Gui.Document (tww);

			var text = input;
			int endPos = text.IndexOf ('$');
			if (endPos >= 0)
				text = text.Substring (0, endPos) + text.Substring (endPos + 1);

			content.Text = text;
			content.CursorPosition = System.Math.Max (0, endPos);

			var project = Services.ProjectService.CreateProject ("C#");
			project.Name = "test";
			project.FileName = "test.csproj";
			project.Files.Add (new ProjectFile (content.ContentName, BuildAction.Compile)); 
			project.Policies.Set (PolicyService.InvariantPolicies.Get<CSharpFormattingPolicy> (), CSharpFormatter.MimeType);
			var solution = new MonoDevelop.Projects.Solution ();
			solution.AddConfiguration ("", true); 
			solution.DefaultSolutionFolder.AddItem (project);
			using (var monitor = new ProgressMonitor ())
				await TypeSystemService.Load (solution, monitor);
			content.Project = project;
			doc.SetProject (project);


			var compExt = new CSharpCompletionTextEditorExtension ();
			compExt.Initialize (doc.Editor, doc);
			content.Contents.Add (compExt);

			await doc.UpdateParseDocument ();
			TypeSystemService.Unload (solution);
			return Tuple.Create (compExt, content);
		}
		static void TestInsertionPoints (string text)
		{
			
			TestWorkbenchWindow tww = new TestWorkbenchWindow ();
			TestViewContent sev = new TestViewContent ();
			DotNetProject project = new DotNetAssemblyProject ("C#");
			project.FileName = GetTempFile (".csproj");
			
			string file = GetTempFile (".cs");
			project.AddFile (file);
			sev.Project = project;
			sev.ContentName = file;
			tww.ViewContent = sev;
			var doc = new MonoDevelop.Ide.Gui.Document (tww);
			var data = doc.Editor;
			List<InsertionPoint> loc = new List<InsertionPoint> ();
			for (int i = 0; i < text.Length; i++) {
				char ch = text[i];
				if (ch == '@') {
					i++;
					ch = text[i];
					NewLineInsertion insertBefore = NewLineInsertion.None;
					NewLineInsertion insertAfter  = NewLineInsertion.None;
					
					switch (ch) {
					case 'n':
						break;
					case 'd':
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'D':
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'u':
						insertBefore = NewLineInsertion.Eol;
						break;
					case 'U':
						insertBefore = NewLineInsertion.BlankLine;
						break;
					case 's':
						insertBefore = insertAfter = NewLineInsertion.Eol;
						break;
					case 'S':
						insertBefore = insertAfter = NewLineInsertion.BlankLine;
						break;
						
					case 't':
						insertBefore = NewLineInsertion.Eol;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'T':
						insertBefore = NewLineInsertion.None;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'v':
						insertBefore = NewLineInsertion.BlankLine;
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'V':
						insertBefore = NewLineInsertion.None;
						insertAfter = NewLineInsertion.Eol;
						break;
					default:
						Assert.Fail ("unknown insertion point:" + ch);
						break;
					}
					loc.Add (new InsertionPoint (data.Document.OffsetToLocation (data.Document.Length), insertBefore, insertAfter));
				} else {
					data.Insert (data.Document.Length, ch.ToString ());
				}
			}
			
			
			doc.ParsedDocument =  new NRefactoryParser ().Parse (null, "a.cs", data.Document.Text);
			
			var foundPoints = HelperMethods.GetInsertionPoints (doc, doc.ParsedDocument.CompilationUnit.Types[0]);
			Assert.AreEqual (loc.Count, foundPoints.Count, "point count doesn't match");
			for (int i = 0; i < loc.Count; i++) {
				Assert.AreEqual (loc[i].Location, foundPoints[i].Location, "point " + i + " doesn't match");
				Assert.AreEqual (loc[i].LineAfter, foundPoints[i].LineAfter, "point " + i + " ShouldInsertNewLineAfter doesn't match");
				Assert.AreEqual (loc[i].LineBefore, foundPoints[i].LineBefore, "point " + i + " ShouldInsertNewLineBefore doesn't match");
			}
		}
예제 #35
0
		public override void Dispose ()
		{
			ClearExtensions ();
			FileRegistry.Remove (this);
			RemoveAutoSaveTimer ();
			
			StoreSettings ();
			
			this.isDisposed = true;
			Counters.LoadedEditors--;
			
		/*	if (messageBubbleHighlightPopupWindow != null)
				messageBubbleHighlightPopupWindow.Destroy ();*/

			IdeApp.Preferences.DefaultHideMessageBubblesChanged -= HandleIdeAppPreferencesDefaultHideMessageBubblesChanged;
			IdeApp.Preferences.ShowMessageBubblesChanged -= HandleIdeAppPreferencesShowMessageBubblesChanged;
			TaskService.TaskToggled -= HandleErrorListPadTaskToggled;
			
			DisposeErrorMarkers ();
			
			ClipbardRingUpdated -= UpdateClipboardRing;

			widget.TextEditor.Document.SyntaxModeChanged -= HandleSyntaxModeChanged;
			widget.TextEditor.Document.TextReplaced -= HandleTextReplaced;
			widget.TextEditor.Document.LineChanged -= HandleLineChanged;
			widget.TextEditor.Document.BeginUndo -= HandleBeginUndo; 
			widget.TextEditor.Document.EndUndo -= HandleEndUndo;
			widget.TextEditor.Document.Undone -= HandleUndone;
			widget.TextEditor.Document.Redone -= HandleUndone;
			widget.TextEditor.Caret.PositionChanged -= HandlePositionChanged; 
			widget.TextEditor.IconMargin.ButtonPressed -= OnIconButtonPress;
			widget.TextEditor.Document.TextReplacing -= OnTextReplacing;
			widget.TextEditor.Document.TextReplaced -= OnTextReplaced;
			widget.TextEditor.Document.ReadOnlyCheckDelegate = null;
			widget.TextEditor.Options.Changed -= HandleWidgetTextEditorOptionsChanged;

			TextEditorService.FileExtensionAdded -= HandleFileExtensionAdded;
			TextEditorService.FileExtensionRemoved -= HandleFileExtensionRemoved;

			DebuggingService.DebugSessionStarted -= OnDebugSessionStarted;
			DebuggingService.CurrentFrameChanged -= currentFrameChanged;
			DebuggingService.StoppedEvent -= currentFrameChanged;
			DebuggingService.ResumedEvent -= currentFrameChanged;
			breakpoints.BreakpointAdded -= breakpointAdded;
			breakpoints.BreakpointRemoved -= breakpointRemoved;
			breakpoints.BreakpointStatusChanged -= breakpointStatusChanged;
			breakpoints.BreakpointModified -= breakpointStatusChanged;
			DebuggingService.PinnedWatches.WatchAdded -= OnWatchAdded;
			DebuggingService.PinnedWatches.WatchRemoved -= OnWatchRemoved;
			DebuggingService.PinnedWatches.WatchChanged -= OnWatchChanged;
			
			TaskService.Errors.TasksAdded -= UpdateTasks;
			TaskService.Errors.TasksRemoved -= UpdateTasks;
			TaskService.Errors.TasksChanged -= UpdateTasks;
			TaskService.JumpedToTask -= HandleTaskServiceJumpedToTask;
			
			// This is not necessary but helps when tracking down memory leaks
			
			debugStackLineMarker = null;
			currentDebugLineMarker = null;
			
			currentFrameChanged = null;
			breakpointAdded = null;
			breakpointRemoved = null;
			breakpointStatusChanged = null;

			if (ownerDocument != null) {
				ownerDocument.DocumentParsed -= HandleDocumentParsed;
				ownerDocument = null;
			}

			RemoveMarkerQueue ();
		}
예제 #36
0
			public AspCompletionWidget (MonoDevelop.Ide.Gui.Document realDocument, LocalDocumentInfo localInfo)
			{
				this.realDocument = realDocument;
				this.localInfo = localInfo;
			}
예제 #37
0
		public ImportSymbolCompletionData (MonoDevelop.Ide.Gui.Document doc, ImportSymbolCache cache, IType type)
		{
			this.doc = doc;
			this.cache = cache;
//			this.data = doc.Editor;
			this.ambience = AmbienceService.GetAmbience (doc.Editor.MimeType);
			this.type = type;
			this.unit = doc.ParsedDocument;
			this.DisplayFlags |= ICSharpCode.NRefactory.Completion.DisplayFlags.IsImportCompletion;
		}
예제 #38
0
		void BindActiveDoc (object sender, EventArgs e)
		{
			var doc = IdeApp.Workbench.ActiveDocument;
			if (boundDoc == doc) {
				return;
			}
			if (boundDoc != null) {				
				boundDoc.DocumentParsed -= ActiveDoc_DocumentParsed;
			}
			boundDoc = doc;
			if (boundDoc != null) {
				boundDoc.DocumentParsed += ActiveDoc_DocumentParsed;
			}
		}
예제 #39
0
		internal static RefactoringOptions CreateRefactoringOptions (string text)
		{
			int cursorPosition = -1;
			int endPos = text.IndexOf ('$');
			if (endPos >= 0) {
				cursorPosition = endPos;
				text = text.Substring (0, cursorPosition) + text.Substring (cursorPosition + 1);
			}
			
			int selectionStart = -1;
			int selectionEnd   = -1;
			int idx = text.IndexOf ("<-");
			if (idx >= 0) {
				selectionStart = idx;
				text = text.Substring (0, idx) + text.Substring (idx + 2);
				selectionEnd = idx = text.IndexOf ("->");
				
				text = text.Substring (0, idx) + text.Substring (idx + 2);
				if (cursorPosition < 0)
					cursorPosition = selectionEnd - 1;
			}
			
			TestWorkbenchWindow tww = new TestWorkbenchWindow ();
			TestViewContent sev = new TestViewContent ();
	//		return new RefactoringOptions ();
			
			DotNetProject project = new DotNetAssemblyProject ("C#");
			Solution solution = new Solution ();
			solution.RootFolder.Items.Add (project);
			project.FileName = GetTempFile (".csproj");
			string file = GetTempFile (".cs");
			project.AddFile (file);
			string parsedText = text;
			string editorText = text;
			ProjectDomService.Load (project);
			ProjectDom dom = ProjectDomService.GetProjectDom (project);
			dom.ForceUpdate (true);
			ProjectDomService.Parse (project, file, delegate { return parsedText; });
			ProjectDomService.Parse (project, file, delegate { return parsedText; });
			
			sev.Project = project;
			sev.ContentName = file;
			sev.Text = editorText;
			sev.CursorPosition = cursorPosition;
			
			tww.ViewContent = sev;
			var doc = new MonoDevelop.Ide.Gui.Document (tww);
			doc.Editor.Document.MimeType = "text/x-csharp";
			doc.Editor.Document.FileName = file;
			doc.ParsedDocument = new McsParser ().Parse (null, sev.ContentName, parsedText);
			foreach (var e in doc.ParsedDocument.Errors)
				Console.WriteLine (e);
			if (cursorPosition >= 0)
				doc.Editor.Caret.Offset = cursorPosition;
			if (selectionStart >= 0) 
				doc.Editor.SetSelection (selectionStart, selectionEnd);
			
			NRefactoryResolver resolver = new NRefactoryResolver (dom, 
			                                                      doc.ParsedDocument.CompilationUnit, 
			                                                      sev.Data, 
			                                                      file);
			
			ExpressionResult expressionResult;
			if (selectionStart >= 0) {
				expressionResult = new ExpressionResult (editorText.Substring (selectionStart, selectionEnd - selectionStart).Trim ());
				endPos = selectionEnd;
			} else {
				expressionResult = new NewCSharpExpressionFinder (dom).FindFullExpression (doc.Editor, cursorPosition + 1);
			}
			ResolveResult resolveResult = endPos >= 0 ? resolver.Resolve (expressionResult, new DomLocation (doc.Editor.Caret.Line, doc.Editor.Caret.Column)) : null;
			
			RefactoringOptions result = new RefactoringOptions {
				Document = doc,
				Dom = dom,
				ResolveResult = resolveResult,
				SelectedItem = null
			};
			if (resolveResult is MemberResolveResult)
				result.SelectedItem = ((MemberResolveResult)resolveResult).ResolvedMember;
			if (resolveResult is LocalVariableResolveResult)
				result.SelectedItem = ((LocalVariableResolveResult)resolveResult).LocalVariable;
			if (resolveResult is ParameterResolveResult)
				result.SelectedItem = ((ParameterResolveResult)resolveResult).Parameter;
			result.TestFileProvider = new FileProvider (result);
			return result;
		}
예제 #40
0
		static void TestInsertionPoints (string text)
		{
			
			TestWorkbenchWindow tww = new TestWorkbenchWindow ();
			TestViewContent sev = new TestViewContent ();
			var project = new UnknownProject ();
			project.FileName = "test.csproj";
			
			TypeSystemService.LoadProject (project);

			sev.Project = project;
			tww.ViewContent = sev;
			var doc = new MonoDevelop.Ide.Gui.Document (tww);
			var data = doc.Editor;
			List<InsertionPoint> loc = new List<InsertionPoint> ();
			for (int i = 0; i < text.Length; i++) {
				char ch = text [i];
				if (ch == '@') {
					i++;
					ch = text [i];
					NewLineInsertion insertBefore = NewLineInsertion.None;
					NewLineInsertion insertAfter = NewLineInsertion.None;
					
					switch (ch) {
					case 'n':
						break;
					case 'd':
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'D':
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'u':
						insertBefore = NewLineInsertion.Eol;
						break;
					case 'U':
						insertBefore = NewLineInsertion.BlankLine;
						break;
					case 's':
						insertBefore = insertAfter = NewLineInsertion.Eol;
						break;
					case 'S':
						insertBefore = insertAfter = NewLineInsertion.BlankLine;
						break;
						
					case 't':
						insertBefore = NewLineInsertion.Eol;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'T':
						insertBefore = NewLineInsertion.None;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'v':
						insertBefore = NewLineInsertion.BlankLine;
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'V':
						insertBefore = NewLineInsertion.None;
						insertAfter = NewLineInsertion.Eol;
						break;
					default:
						Assert.Fail ("unknown insertion point:" + ch);
						break;
					}
					loc.Add (new InsertionPoint (data.Document.OffsetToLocation (data.Document.TextLength), insertBefore, insertAfter));
				} else {
					data.Insert (data.Document.TextLength, ch.ToString ());
				}
			}
			
			var parsedFile = TypeSystemService.ParseFile (project, "program.cs", "text/x-csharp", data.Document.Text);

			var foundPoints = CodeGenerationService.GetInsertionPoints (doc.Editor, parsedFile, parsedFile.TopLevelTypeDefinitions.First ());
			Assert.AreEqual (loc.Count, foundPoints.Count, "point count doesn't match");
			for (int i = 0; i < loc.Count; i++) {
				Assert.AreEqual (loc[i].Location, foundPoints[i].Location, "point " + i + " doesn't match");
				Assert.AreEqual (loc[i].LineAfter, foundPoints[i].LineAfter, "point " + i + " ShouldInsertNewLineAfter doesn't match");
				Assert.AreEqual (loc[i].LineBefore, foundPoints[i].LineBefore, "point " + i + " ShouldInsertNewLineBefore doesn't match");
			}
		}
		public Document (string fileName, MD.Document document)
		{
			this.FullName = fileName;
			this.document = document;
		}
예제 #42
0
			public CSharpChunkParser (SpanParser spanParser, Mono.TextEditor.Document doc, ColorSheme style, SyntaxMode mode, LineSegment line) : base (spanParser, doc, style, mode, line)
			{
				document = IdeApp.Workbench.GetDocument (doc.FileName);
				
				foreach (var tag in ProjectDomService.SpecialCommentTags) {
					tags.Add (tag.Tag);
				}
				
				ICSharpCode.OldNRefactory.Ast.CompilationUnit unit = null;
				if (document != null && document.ParsedDocument != null && MonoDevelop.Core.PropertyService.Get ("EnableSemanticHighlighting", false)) {
					resolver = document.GetResolver ();
					if (!document.ParsedDocument.TryGetTag (out unit)) {
						try {
							using (ICSharpCode.OldNRefactory.IParser parser = ICSharpCode.OldNRefactory.ParserFactory.CreateParser (ICSharpCode.OldNRefactory.SupportedLanguage.CSharp, document.Editor.Document.OpenTextReader ())) {
								parser.Parse ();
								unit = parser.CompilationUnit;
								document.ParsedDocument.SetTag (unit);
							}
						} catch (Exception) {
							resolver = null;
							return;
						}
					}
					resolver.SetupParsedCompilationUnit (unit);
				}
			}
		static async Task TestInsertionPoints (string text)
		{
			var tww = new TestWorkbenchWindow ();
			var content = new TestViewContent ();
			tww.ViewContent = content;
			content.ContentName = "/a.cs";
			content.Data.MimeType = "text/x-csharp";
			MonoDevelop.AnalysisCore.AnalysisOptions.EnableUnitTestEditorIntegration.Set (true);
			var doc = new MonoDevelop.Ide.Gui.Document (tww);

			var data = doc.Editor;
			List<InsertionPoint> loc = new List<InsertionPoint> ();
			for (int i = 0; i < text.Length; i++) {
				char ch = text [i];
				if (ch == '@') {
					i++;
					ch = text [i];
					NewLineInsertion insertBefore = NewLineInsertion.None;
					NewLineInsertion insertAfter = NewLineInsertion.None;

					switch (ch) {
					case 'n':
						break;
					case 'd':
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'D':
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'u':
						insertBefore = NewLineInsertion.Eol;
						break;
					case 'U':
						insertBefore = NewLineInsertion.BlankLine;
						break;
					case 's':
						insertBefore = insertAfter = NewLineInsertion.Eol;
						break;
					case 'S':
						insertBefore = insertAfter = NewLineInsertion.BlankLine;
						break;

					case 't':
						insertBefore = NewLineInsertion.Eol;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'T':
						insertBefore = NewLineInsertion.None;
						insertAfter = NewLineInsertion.BlankLine;
						break;
					case 'v':
						insertBefore = NewLineInsertion.BlankLine;
						insertAfter = NewLineInsertion.Eol;
						break;
					case 'V':
						insertBefore = NewLineInsertion.None;
						insertAfter = NewLineInsertion.Eol;
						break;
					default:
						Assert.Fail ("unknown insertion point:" + ch);
						break;
					}
					var vv = data.OffsetToLocation (data.Length);
					loc.Add (new InsertionPoint (new DocumentLocation (vv.Line, vv.Column), insertBefore, insertAfter));
				} else {
					data.InsertText (data.Length, ch.ToString ());
				}
			}


			var project = Services.ProjectService.CreateProject ("C#");
			project.Name = "test";
			project.FileName = "test.csproj";
			project.Files.Add (new ProjectFile ("/a.cs", BuildAction.Compile)); 

			var solution = new MonoDevelop.Projects.Solution ();
			solution.AddConfiguration ("", true); 
			solution.DefaultSolutionFolder.AddItem (project);
			using (var monitor = new ProgressMonitor ())
				await TypeSystemService.Load (solution, monitor);
			content.Project = project;
			doc.SetProject (project);
			var parsedFile = await doc.UpdateParseDocument ();
			var model = parsedFile.GetAst<SemanticModel> ();
			var sym = model?.GetEnclosingSymbol (data.Text.IndexOf ('{'));
			var type = sym as INamedTypeSymbol ?? sym?.ContainingType;
			if (type != null) {
				var foundPoints = InsertionPointService.GetInsertionPoints (doc.Editor, parsedFile, type, type.Locations.First ());
				Assert.AreEqual (loc.Count, foundPoints.Count, "point count doesn't match");
				for (int i = 0; i < loc.Count; i++) {
					Assert.AreEqual (loc [i].Location, foundPoints [i].Location, "point " + i + " doesn't match");
					Assert.AreEqual (loc [i].LineAfter, foundPoints [i].LineAfter, "point " + i + " ShouldInsertNewLineAfter doesn't match");
					Assert.AreEqual (loc [i].LineBefore, foundPoints [i].LineBefore, "point " + i + " ShouldInsertNewLineBefore doesn't match");
				}
			}

			TypeSystemService.Unload (solution);

		}
		public ImportSymbolCompletionData (MonoDevelop.Ide.Gui.Document doc, ImportSymbolCache cache, IType type)
		{
			this.doc = doc;
			this.cache = cache;
//			this.data = doc.Editor;
			this.ambience = AmbienceService.GetAmbience (doc.Editor.MimeType);
			this.type = type;
			this.unit = doc.ParsedDocument;
		}
        void IdeApp_Workbench_ActiveDocumentChanged(object sender, EventArgs e)
        {
            if (_previousDocument != null && _previousDocument.Editor != null && _previousDocument.Editor.Caret != null) {
                UpdateFileOpenInfo (_previousDocument, _previousDocument.Editor.Caret.Line, _previousDocument.Editor.Caret.Column);
            }

            if (IdeApp.Workbench != null && IdeApp.Workbench.ActiveDocument != null) {
                var document = IdeApp.Workbench.ActiveDocument;
                if (document != null && document.FileName != null) {

                    var existingFileInfo = _recentDocuments.FirstOrDefault ((arg) => arg.Project == document.Project && arg.FileName.FullPath == document.FileName.FullPath);
                    var lineNumber = existingFileInfo?.Line ?? 1;
                    var column = existingFileInfo?.Column ?? 1;
                    UpdateFileOpenInfo (document, lineNumber, column);
                }
            }
            _previousDocument = IdeApp.Workbench.ActiveDocument;

            //TODO experimental - probably want to move this to ide save, or every 30 seconds or so..
            SaveHistory ();
        }