Esempio n. 1
0
        void TextAreaTextEntered(object sender, TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && !e.Handled)
            {
                ILanguageBinding languageBinding = GetAdapterFromSender(sender).Language;
                if (languageBinding != null && languageBinding.FormattingStrategy != null)
                {
                    char c = e.Text[0];
                    // When entering a newline, AvalonEdit might use either "\r\n" or "\n", depending on
                    // what was passed to TextArea.PerformTextInput. We'll normalize this to '\n'
                    // so that formatting strategies don't have to handle both cases.
                    if (c == '\r')
                    {
                        c = '\n';
                    }
                    languageBinding.FormattingStrategy.FormatLine(GetAdapterFromSender(sender), c);

                    if (c == '\n')
                    {
                        // Immediately parse on enter.
                        // This ensures we have up-to-date CC info about the method boundary when a user
                        // types near the end of a method.
                        ParserService.BeginParse(this.FileName, this.DocumentAdapter.CreateSnapshot());
                    }
                }
            }
        }
Esempio n. 2
0
        protected override void OnFileNameChanged(OpenedFile file)
        {
            base.OnFileNameChanged(file);
            if (file == PrimaryFile)
            {
                FileName oldFileName = codeEditor.FileName;
                FileName newFileName = FileName.Create(file.FileName);

                if (!string.IsNullOrEmpty(oldFileName))
                {
                    ParserService.ClearParseInformation(oldFileName);
                }


                BookmarksNotifyNameChange(oldFileName, newFileName);
                // changing the filename on the codeEditor raises several events; ensure
                // we got our state updated first (bookmarks, persistent anchors) before other code
                // processes the file name change

                codeEditor.FileName = newFileName;
                UpdateSyntaxHighlighting(newFileName);

                ParserService.BeginParse(file.FileName, codeEditor.DocumentAdapter);
            }
        }
Esempio n. 3
0
        public override void CloseIfAllViewsClosed()
        {
            if (registeredViews.Count == 0)
            {
                bool wasDirty = this.IsDirty;
                FileService.OpenedFileClosed(this);

                FileClosed.RaiseEvent(this, EventArgs.Empty);

                if (fileChangeWatcher != null)
                {
                    fileChangeWatcher.Dispose();
                    fileChangeWatcher = null;
                }

                if (wasDirty)
                {
                    // We discarded some information when closing the file,
                    // so we need to re-parse it.
                    if (System.IO.File.Exists(this.FileName))
                    {
                        ParserService.BeginParse(this.FileName);
                    }
                    else
                    {
                        ParserService.ClearParseInformation(this.FileName);
                    }
                }
            }
        }
Esempio n. 4
0
        public virtual void Complete(CompletionContext context)
        {
            MarkAsUsed();

            string insertedText  = this.Text;
            IClass selectedClass = GetClassOrExtensionMethodClass(this.Entity);

            if (selectedClass != null)
            {
                // Class or Extension method is being inserted
                var editor   = context.Editor;
                var document = context.Editor.Document;
                //  Resolve should return AmbiguousResolveResult or something like that when we resolve a name that exists in more imported namespaces
                //   - so that we would know that we always want to insert fully qualified name
                var nameResult = ResolveAtCurrentOffset(selectedClass.Name, context);

                bool addUsing = false;

                if (this.Entity is IClass)
                {
                    if (!IsUserTypingFullyQualifiedName(context))
                    {
                        nameResult = ResolveAtCurrentOffset(insertedText, context);
                        addUsing   = (!IsKnownName(nameResult));
                    }
                    // Special case for Attributes
                    if (insertedText.EndsWith("Attribute") && IsInAttributeContext(editor, context.StartOffset))
                    {
                        insertedText = insertedText.RemoveFromEnd("Attribute");
                    }
                }
                else if (this.Entity is IMethod)
                {
                    addUsing = !IsKnownName(nameResult);
                }

                context.Editor.Document.Replace(context.StartOffset, context.Length, insertedText);
                context.EndOffset = context.StartOffset + insertedText.Length;

                if (addUsing && nameResult != null && nameResult.CallingClass != null)
                {
                    //TODO: Uncomment
                    //var cu = nameResult.CallingClass.CompilationUnit;
                    //NamespaceRefactoringService.AddUsingDeclaration(cu, document, selectedClass.Namespace, false);
                    ParserService.BeginParse(editor.FileName, document);
                }
            }
            else
            {
                // Something else than a class or Extension method is being inserted - just insert text
                context.Editor.Document.Replace(context.StartOffset, context.Length, insertedText);
                context.EndOffset = context.StartOffset + insertedText.Length;
            }
        }
Esempio n. 5
0
        void FetchParseInformation()
        {
            ParseInformation parseInfo = ParserService.GetExistingParseInformation(this.FileName);

            if (parseInfo == null)
            {
                // if parse info is not yet available, start parsing on background
                ParserService.BeginParse(this.FileName, primaryTextEditorAdapter.Document);
                // we'll receive the result using the ParseInformationUpdated event
            }
            ParseInformationUpdated(parseInfo);
        }
Esempio n. 6
0
        public MenuItem Create(RefactoringMenuContext context)
        {
            if (context.ExpressionResult.Context == ExpressionContext.Attribute)
            {
                return(null);
            }
            if (!(context.ResolveResult is UnknownMethodResolveResult))
            {
                return(null);
            }
            if (context.ProjectContent == null)
            {
                return(null);
            }

            UnknownMethodResolveResult rr = context.ResolveResult as UnknownMethodResolveResult;

            MenuItem item = new MenuItem()
            {
                Header = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.ResolveExtensionMethod}"), rr.CallName),
                Icon   = ClassBrowserIconService.GotoArrow.CreateImage()
            };

            List <IClass> results = new List <IClass>();

            SearchAllExtensionMethodsWithName(results, context.ProjectContent, rr.CallName);

            foreach (IProjectContent content in context.ProjectContent.ThreadSafeGetReferencedContents())
            {
                SearchAllExtensionMethodsWithName(results, content, rr.CallName);
            }

            if (!results.Any())
            {
                return(null);
            }

            foreach (IClass c in results)
            {
                string   newNamespace = c.Namespace;
                MenuItem subItem      = new MenuItem();
                subItem.Header = "using " + newNamespace;
                subItem.Icon   = ClassBrowserIconService.Namespace.CreateImage();
                item.Items.Add(subItem);
                subItem.Click += delegate {
                    NamespaceRefactoringService.AddUsingDeclaration(context.CompilationUnit, context.Editor.Document, newNamespace, true);
                    ParserService.BeginParse(context.Editor.FileName, context.Editor.Document);
                };
            }

            return(item);
        }
Esempio n. 7
0
        public void WriteCodeDomToFile(FileProjectItem baseItem, string outputFileName, CodeCompileUnit ccu)
        {
            WorkbenchSingleton.AssertMainThread();
            CodeDomProvider      provider = project.LanguageProperties.CodeDomProvider;
            CodeGeneratorOptions options  = new CodeDOMGeneratorUtility().CreateCodeGeneratorOptions;

            if (project.LanguageProperties == LanguageProperties.VBNet)
            {
                // the root namespace is implicit in VB
                foreach (CodeNamespace ns in ccu.Namespaces)
                {
                    if (string.Equals(ns.Name, project.RootNamespace, StringComparison.OrdinalIgnoreCase))
                    {
                        ns.Name = string.Empty;
                    }
                    else if (ns.Name.StartsWith(project.RootNamespace + ".", StringComparison.OrdinalIgnoreCase))
                    {
                        ns.Name = ns.Name.Substring(project.RootNamespace.Length + 1);
                    }
                }
            }

            string codeOutput;

            using (StringWriter writer = new StringWriter()) {
                if (provider == null)
                {
                    writer.WriteLine("No CodeDom provider was found for this language.");
                }
                else
                {
                    provider.GenerateCodeFromCompileUnit(ccu, writer, options);
                }
                codeOutput = writer.ToString();
            }

            FileUtility.ObservedSave(delegate(string fileName) {
                File.WriteAllText(fileName, codeOutput, Encoding.UTF8);
            },
                                     outputFileName, FileErrorPolicy.Inform);
            EnsureOutputFileIsInProject(baseItem, outputFileName);
            ParserService.BeginParse(outputFileName, new StringTextBuffer(codeOutput));
        }
Esempio n. 8
0
        public MenuItem Create(RefactoringMenuContext context)
        {
            // TODO : [Test] above method is in Default context?
//			if (context.ExpressionResult.Context != ExpressionContext.Attribute)
//				return null;
            if (!(context.ResolveResult is UnknownIdentifierResolveResult || context.ResolveResult is UnknownMethodResolveResult))
            {
                return(null);
            }

            List <IClass> results = new List <IClass>();

            ParseInformation info = ParserService.GetParseInformation(context.Editor.FileName);

            if (info == null || info.CompilationUnit == null || info.CompilationUnit.ProjectContent == null)
            {
                return(null);
            }

            ICompilationUnit unit = info.CompilationUnit;
            IProjectContent  pc   = info.CompilationUnit.ProjectContent;

            string name = null;

            if (context.ResolveResult is UnknownMethodResolveResult)
            {
                var rr = context.ResolveResult as UnknownMethodResolveResult;
                SearchAttributesWithName(results, pc, rr.CallName);

                foreach (IProjectContent content in pc.ReferencedContents)
                {
                    SearchAttributesWithName(results, content, rr.CallName);
                }

                name = rr.CallName;
            }

            if (context.ResolveResult is UnknownIdentifierResolveResult)
            {
                var rr = context.ResolveResult as UnknownIdentifierResolveResult;
                SearchAttributesWithName(results, pc, rr.Identifier);

                foreach (IProjectContent content in pc.ReferencedContents)
                {
                    SearchAttributesWithName(results, content, rr.Identifier);
                }

                name = rr.Identifier;
            }

            if (!results.Any())
            {
                return(null);
            }

            MenuItem item = new MenuItem()
            {
                Header = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.ResolveAttribute}"), name),
                Icon   = ClassBrowserIconService.GotoArrow.CreateImage()
            };

            foreach (IClass c in results)
            {
                string   newNamespace = c.Namespace;
                MenuItem subItem      = new MenuItem();
                subItem.Header = "using " + newNamespace;
                subItem.Icon   = ClassBrowserIconService.Namespace.CreateImage();
                item.Items.Add(subItem);
                subItem.Click += delegate {
                    NamespaceRefactoringService.AddUsingDeclaration(unit, context.Editor.Document, newNamespace, true);
                    ParserService.BeginParse(context.Editor.FileName, context.Editor.Document);
                };
            }

            return(item);
        }
        public virtual void MergeFormChanges(CodeCompileUnit unit)
        {
            Reparse();

            // find InitializeComponent method and the class it is declared in
            CodeTypeDeclaration formClass           = null;
            CodeMemberMethod    initializeComponent = null;

            foreach (CodeNamespace n in unit.Namespaces)
            {
                foreach (CodeTypeDeclaration typeDecl in n.Types)
                {
                    foreach (CodeTypeMember m in typeDecl.Members)
                    {
                        if (m is CodeMemberMethod && m.Name == "InitializeComponent")
                        {
                            formClass           = typeDecl;
                            initializeComponent = (CodeMemberMethod)m;
                            break;
                        }
                    }
                }
            }

            if (formClass == null || initializeComponent == null)
            {
                throw new InvalidOperationException("InitializeComponent method not found in framework-generated CodeDom.");
            }
            if (this.formClass == null)
            {
                MessageService.ShowMessage("Cannot save form: InitializeComponent method does not exist anymore. You should not modify the Designer.cs file while editing a form.");
                return;
            }

            FixGeneratedCode(this.formClass, initializeComponent);

            // generate file and get initialize components string
            StringWriter     writer       = new StringWriter();
            CodeDOMGenerator domGenerator = new CodeDOMGenerator(this.CodeDomProvider, tabs + '\t');

            domGenerator.ConvertContentDefinition(initializeComponent, writer);

            string statements = writer.ToString();

            // initializeComponents.BodyRegion.BeginLine + 1
            DomRegion bodyRegion = GetReplaceRegion(this.ViewContent.DesignerCodeFileDocument, initializeComponents);

            if (bodyRegion.BeginColumn <= 0 || bodyRegion.EndColumn <= 0)
            {
                throw new InvalidOperationException("Column must be > 0");
            }
            int startOffset = this.ViewContent.DesignerCodeFileDocument.PositionToOffset(bodyRegion.BeginLine, bodyRegion.BeginColumn);
            int endOffset   = this.ViewContent.DesignerCodeFileDocument.PositionToOffset(bodyRegion.EndLine, bodyRegion.EndColumn);

            this.ViewContent.DesignerCodeFileDocument.Replace(startOffset, endOffset - startOffset, statements);

            // apply changes the designer made to field declarations
            // first loop looks for added and changed fields
            foreach (CodeTypeMember m in formClass.Members)
            {
                if (m is CodeMemberField)
                {
                    CodeMemberField newField = (CodeMemberField)m;
                    IField          oldField = GetField(completeClass, newField.Name);
                    if (oldField == null || FieldChanged(oldField, newField))
                    {
                        AddOrReplaceField(domGenerator, newField);
                    }
                }
            }

            // second loop looks for removed fields
            List <string> removedFields = new List <string>();

            foreach (IField field in completeClass.Fields)
            {
                bool found = false;
                foreach (CodeTypeMember m in formClass.Members)
                {
                    if (m is CodeMemberField && m.Name == field.Name)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    removedFields.Add(field.Name);
                }
            }
            // removing fields is done in two steps because
            // we must not modify the c.Fields collection while it is enumerated
            removedFields.ForEach(RemoveField);

            ParserService.BeginParse(this.ViewContent.DesignerCodeFile.FileName, this.ViewContent.DesignerCodeFileDocument);
        }
Esempio n. 10
0
 public void Execute()
 {
     NamespaceRefactoringService.AddUsingDeclaration(CompilationUnit, Editor.Document, NewNamespace, true);
     ParserService.BeginParse(Editor.FileName, Editor.Document);
 }