/// <summary>
        /// Process clean-up on file.
        /// </summary>
        /// <param name="projectFile">
        /// The project file to process.
        /// </param>
        /// <param name="rangeMarker">
        /// The range marker to process.
        /// </param>
        /// <param name="profile">
        /// The code cleanup settings to use.
        /// </param>
        /// <param name="progressIndicator">
        /// The progress indicator.
        /// </param>
        public void Process(
            IPsiSourceFile projectFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, JetBrains.Application.Progress.IProgressIndicator progressIndicator)
        {
            if (!this.IsAvailable(projectFile))
            {
                return;
            }

            ISolution solution = projectFile.GetSolution();

            ICSharpFile file = projectFile.GetDominantPsiFile <CSharpLanguage>() as ICSharpFile;

            if (file == null)
            {
                return;
            }


            if (!profile.GetSetting(FIX_VIOLATIONS))
            {
                return;
            }

            var services = solution.GetPsiServices();

            services.Transactions.Execute("Code cleanup", () => this.InternalProcess(projectFile.ToProjectFile(), file, profile.GetSetting(CREATE_XML_DOC_STUB)));

            StyleCopTrace.Out();
        }
        /// <summary>
        /// Process clean-up on file.
        /// </summary>
        /// <param name="projectFile">
        /// The project file to process.
        /// </param>
        /// <param name="rangeMarker">
        /// The range marker to process.
        /// </param>
        /// <param name="profile">
        /// The code cleanup settings to use.
        /// </param>
        /// <param name="progressIndicator">
        /// The progress indicator.
        /// </param>
        public void Process(
            IPsiSourceFile projectFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, JB::JetBrains.Application.Progress.IProgressIndicator progressIndicator)
        {
            if (projectFile == null)
            {
                return;
            }

            if (!this.IsAvailable(projectFile))
            {
                return;
            }

            ISolution solution = projectFile.GetSolution();

            ICSharpFile file = projectFile.GetPsiFile <CSharpLanguage>() as ICSharpFile;

            if (file == null)
            {
                return;
            }

            PsiManager.GetInstance(solution).DoTransaction(() => this.InternalProcess(profile, file), "Code cleanup");

            StyleCopTrace.Out();
        }
        /// <summary>
        /// Process clean-up on file.
        /// </summary>
        /// <param name="projectFile">
        /// The project file to process.
        /// </param>
        /// <param name="rangeMarker">
        /// The range marker to process.
        /// </param>
        /// <param name="profile">
        /// The code cleanup settings to use.
        /// </param>
        /// <param name="progressIndicator">
        /// The progress indicator.
        /// </param>
        public void Process(
            IPsiSourceFile projectFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, JetBrains.Application.Progress.IProgressIndicator progressIndicator)
        {
            if (!this.IsAvailable(projectFile))
            {
                return;
            }

            ISolution solution = projectFile.GetSolution();

            ICSharpFile file = projectFile.GetDominantPsiFile <CSharpLanguage>() as ICSharpFile;

            if (file == null)
            {
                return;
            }

            StyleCopCodeCleanupOptions options = profile.GetSetting(Descriptor);

            if (!options.FixViolations)
            {
                return;
            }

            var services = solution.GetPsiServices();

            services.Transactions.Execute("Code cleanup", () => this.InternalProcess(projectFile.ToProjectFile(), file, options.CreateXmlDocStubs));

            StyleCopTrace.Out();
        }
        public void Execute(ISolution solution, ITextControl textControl)
        {
            if (!_literalExpression.IsValid())
            {
                return;
            }

            IFile containingFile = _literalExpression.GetContainingFile();

            CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(_literalExpression.GetPsiModule());

            IExpression newExpression = null;

            _literalExpression.GetPsiServices().PsiManager.DoTransaction(
                () =>
            {
                using (solution.GetComponent <IShellLocks>().UsingWriteLock())
                    newExpression = ModificationUtil.ReplaceChild(
                        _literalExpression, elementFactory.CreateExpression("System.Int16.MaxValue"));
            }, GetType().Name);

            if (newExpression != null)
            {
                IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>());
                containingFile.OptimizeImportsAndRefs(
                    marker, false, true, NullProgressIndicator.Instance);
            }
        }
        public void Execute(ISolution solution, ITextControl textControl)
        {
            if (!_literalExpression.IsValid())
            {
                return;
            }

            var containingFile = _literalExpression.GetContainingFile();
            var psiModule      = _literalExpression.GetPsiModule();
            var elementFactory = CSharpElementFactory.GetInstance(psiModule);

            IExpression newExpression = null;

            _literalExpression.GetPsiServices().Transactions.Execute(GetType().Name, () =>
            {
                using (solution.GetComponent <IShellLocks>().UsingWriteLock())
                    newExpression = ModificationUtil.ReplaceChild(
                        _literalExpression.Task, elementFactory.CreateExpression("$0.ConfigureAwait($1)", _literalExpression.Task,
                                                                                 elementFactory.CreateExpressionByConstantValue(CSharpConstantValueFactory.CreateBoolValue(_value, psiModule))));
            });

            if (newExpression != null)
            {
                IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>());
                containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance);
            }
        }
        public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator)
        {
            var file = sourceFile.GetNonInjectedPsiFile <CSharpLanguage>();

            if (file == null)
            {
                return;
            }

            if (!profile.GetSetting(DescriptorInstance))
            {
                return;
            }

            CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(sourceFile.PsiModule);

            file.GetPsiServices().PsiManager.DoTransaction(
                () =>
            {
                using (_shellLocks.UsingWriteLock())
                    file.ProcessChildren <IExpression>(
                        expression =>
                    {
                        ConstantValue value = expression.ConstantValue;
                        if (value.IsInteger() && Convert.ToInt32(value.Value) == int.MaxValue)
                        {
                            ModificationUtil.ReplaceChild(expression, elementFactory.CreateExpression("int.MaxValue"));
                        }
                    }
                        );
            },
                "Code cleanup");
        }
    public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator)
    {
      var file = sourceFile.GetNonInjectedPsiFile<CSharpLanguage>();
      if (file == null)
        return;

      if (!profile.GetSetting(DescriptorInstance))
        return;

      CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(sourceFile.PsiModule);
      
      file.GetPsiServices().PsiManager.DoTransaction(
        () =>
          {
            using (_shellLocks.UsingWriteLock())
              file.ProcessChildren<IExpression>(
                expression =>
                  {
                    ConstantValue value = expression.ConstantValue;
                    if (value.IsInteger() && Convert.ToInt32(value.Value) == int.MaxValue)
                      ModificationUtil.ReplaceChild(expression, elementFactory.CreateExpression("int.MaxValue"));
                  }
                );
          },
        "Code cleanup");
    }
        private static void reformatSourceCode(T propertyDeclaration, ISolution solution)
        {
            IFile        containingFile = propertyDeclaration.GetContainingFile();
            IRangeMarker marker         = propertyDeclaration.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>());

            containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance);
        }
Example #9
0
        public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator)
        {
            IFile file = sourceFile.GetTheOnlyPsiFile(CSharpLanguage.Instance);

            if (file == null)
            {
                return;
            }

            if (!profile.GetSetting(DescriptorInstance))
            {
                return;
            }

            file.GetPsiServices().Transactions.Execute("Reflow & Retag XML Documentation Comments",
                                                       () =>
            {
                using (_shellLocks.UsingWriteLock()) {
                    foreach (var documentBlockOwner in file.Descendants <IDocCommentBlockOwner>())
                    {
                        CommentReflowAndRetagAction.ReflowAndRetagCommentBlockNode(
                            documentBlockOwner.GetSolution(),
                            null,
                            documentBlockOwner.DocCommentBlock);
                    }
                };
            });
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            IRangeMarker marker = PsiManager.GetInstance(solution).CreatePsiRangeMarker(this.DocumentRange);

            file.ArrangeThisQualifier(marker);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            IRangeMarker marker = this.DocumentRange.CreateRangeMarker();

            file.ArrangeThisQualifier(marker);
        }
Example #12
0
        public void Process(
            IPsiSourceFile sourceFile,
            IRangeMarker rangeMarkerMarker,
            CodeCleanupProfile profile,
            IProgressIndicator progressIndicator)
        {
            ISolution solution = sourceFile.GetSolution();

            if (!profile.GetSetting(OurDescriptor))
            {
                return;
            }

            INTriplesFile[] files = sourceFile.GetPsiFiles <NTriplesLanguage>().Cast <INTriplesFile>().ToArray();
            using (progressIndicator.SafeTotal("Reformat Psi", files.Length))
            {
                foreach (INTriplesFile file in files)
                {
                    using (IProgressIndicator pi = progressIndicator.CreateSubProgress(1))
                    {
                        using (WriteLockCookie.Create())
                        {
                            var languageService = file.Language.LanguageService();
                            Assertion.Assert(languageService != null, "languageService != null");
                            var formatter = languageService.CodeFormatter;
                            Assertion.Assert(formatter != null, "formatter != null");

                            PsiManager.GetInstance(sourceFile.GetSolution()).DoTransaction(
                                delegate
                            {
                                if (rangeMarkerMarker != null && rangeMarkerMarker.IsValid)
                                {
                                    formatter.Format(
                                        solution,
                                        rangeMarkerMarker.DocumentRange,
                                        CodeFormatProfile.DEFAULT,
                                        true,
                                        false,
                                        pi);
                                }
                                else
                                {
                                    formatter.FormatFile(
                                        file,
                                        CodeFormatProfile.DEFAULT,
                                        pi);
                                }
                            },
                                "Code cleanup");
                        }
                    }
                }
            }
        }
        public IOccurrence MakeOccurrence(FindResult findResult)
        {
            if (!(findResult is FindResultText findResultText) ||
                findResultText.DocumentRange.Document.GetOutsideSolutionPath().IsEmpty)
            {
                return(null);
            }

            IRangeMarker rangeMarker = findResultText.Solution.GetComponent <DocumentManager>().CreateRangeMarker(findResultText.DocumentRange);

            return(new T4OutsideSolutionOccurrence(rangeMarker));
        }
Example #14
0
        public void Process(
            IPsiSourceFile sourceFile,
            IRangeMarker rangeMarkerMarker,
            CodeCleanupProfile profile,
            IProgressIndicator progressIndicator)
        {
            ISolution solution = sourceFile.GetSolution();
            if (!profile.GetSetting(OurDescriptor))
            {
                return;
            }

            INTriplesFile[] files = sourceFile.GetPsiFiles<NTriplesLanguage>().Cast<INTriplesFile>().ToArray();
            using (progressIndicator.SafeTotal("Reformat Psi", files.Length))
            {
                foreach (INTriplesFile file in files)
                {
                    using (IProgressIndicator pi = progressIndicator.CreateSubProgress(1))
                    {
                        using (WriteLockCookie.Create())
                        {
                            var languageService = file.Language.LanguageService();
                            Assertion.Assert(languageService != null, "languageService != null");
                            var formatter = languageService.CodeFormatter;
                            Assertion.Assert(formatter != null, "formatter != null");

                            PsiManager.GetInstance(sourceFile.GetSolution()).DoTransaction(
                                delegate
                                {
                                    if (rangeMarkerMarker != null && rangeMarkerMarker.IsValid)
                                    {
                                        formatter.Format(
                                            solution,
                                            rangeMarkerMarker.DocumentRange,
                                            CodeFormatProfile.DEFAULT,
                                            true,
                                            false,
                                            pi);
                                    }
                                    else
                                    {
                                        formatter.FormatFile(
                                            file,
                                            CodeFormatProfile.DEFAULT,
                                            pi);
                                    }
                                },
                                "Code cleanup");
                        }
                    }
                }
            }
        }
        protected PostfixLookupItem(
      [NotNull] string shortcut, [NotNull] PrefixExpressionContext context)
        {
            myIdentifier = shortcut;
              myShortcut = shortcut.ToLowerInvariant();
              myWasReparsed = !context.Expression.IsPhysical();

              var shift = myWasReparsed ? +2 : 0;
              myExpressionRange = context.ExpressionRange.CreateRangeMarker();
              myReferenceRange = context.Parent.PostfixReferenceRange.CreateRangeMarker();
              myReferenceType = context.Parent.PostfixReferenceNode.GetType();
              myReplaceRange = context.ReplaceRange.ExtendRight(shift);
        }
Example #16
0
        public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile,
                            IProgressIndicator progressIndicator, IUserDataHolder cache)
        {
            var solution = sourceFile.GetSolution();

            if (!profile.GetSetting(ourDescriptor))
            {
                return;
            }

            var psiServices = sourceFile.GetPsiServices();

            IShaderLabFile[] files;
            using (new ReleaseLockCookie(psiServices.Locks, LockKind.FullWrite))
            {
                psiServices.Locks.AssertReadAccessAllowed();
                files = sourceFile.GetPsiFiles <ShaderLabLanguage>().Cast <IShaderLabFile>().ToArray();
            }
            using (progressIndicator.SafeTotal(Name, files.Length))
            {
                foreach (var file in files)
                {
                    using (var indicator = progressIndicator.CreateSubProgress(1))
                    {
                        var service = file.Language.LanguageService();
                        if (service == null)
                        {
                            return;
                        }

                        var formatter = service.CodeFormatter;

                        sourceFile.GetPsiServices().Transactions.Execute("Code cleanup", delegate
                        {
                            if (rangeMarker != null && rangeMarker.IsValid)
                            {
                                CodeFormatterHelper.Format(file.Language,
                                                           solution, rangeMarker.DocumentRange, CodeFormatProfile.DEFAULT, true, false, indicator);
                            }
                            else
                            {
                                formatter.FormatFile(
                                    file,
                                    CodeFormatProfile.DEFAULT,
                                    indicator);
                            }
                        });
                    }
                }
            }
        }
Example #17
0
        protected override void OnAfterComplete(ITextControl textControl, ref TextRange nameRange,
                                                ref TextRange decorationRange, TailType tailType, ref Suffix suffix,
                                                ref IRangeMarker caretPositionRangeMarker)
        {
            // TODO: completion with a space can break this
            base.OnAfterComplete(textControl, ref nameRange, ref decorationRange,
                                 tailType, ref suffix, ref caretPositionRangeMarker);

            if (context != null)
            {
                context.CompletionManager.Locks.QueueReadLock("Code completion inside markup extension",
                                                              () => ExecuteManualCompletion(textControl));
            }
        }
Example #18
0
        protected override void OnAfterComplete(ITextControl textControl, ref TextRange nameRange, ref TextRange decorationRange, TailType tailType,
                                                ref Suffix suffix, ref IRangeMarker caretPositionRangeMarker)
        {
            Solution.GetPsiServices().Files.CommitAllDocuments();
            var psiServices = Solution.GetPsiServices();

            using (var transactionCookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "Lookup item"))
            {
                ImportHelper.AddMissingNamespaceImport(
                    (ICSharpTypeAndNamespaceHolderDeclaration)Context.BasicContext.File,
                    CSharpElementFactory.GetInstance(Context.PsiModule), "System.Reflection");
                psiServices.Caches.Update();
                transactionCookie.Commit();
            }
        }
        public void Process(
                IPsiSourceFile sourceFile, IRangeMarker rangeMarker,
                CodeCleanupProfile profile, IProgressIndicator progressIndicator) {
            var settingsStore = sourceFile.GetSettingsStore();
            var settings = settingsStore.GetKey<XamlAttributeOrderingSettings>(SettingsOptimization.OptimizeDefault);
            if (!profile.GetSetting(DescriptorInstance) || !settings.Enable) {
                return;
            }

            foreach (var xamlFile in sourceFile.GetPsiFiles<XamlLanguage>().OfType<IXamlFile>()) {
                sourceFile.GetPsiServices().Transactions.Execute("Code cleanup",
                        () => {
                            var comparer = new AttributesComparer(settings);
                            xamlFile.ProcessDescendants(new ReorderAttributesProcessor(comparer));
                        });
            }
        }
        protected override void OnAfterComplete(ITextControl textControl, ref TextRange nameRange,
            ref TextRange decorationRange, TailType tailType, ref Suffix suffix,
            ref IRangeMarker caretPositionRangeMarker)
        {
            // TODO: completion with a space can break this
            base.OnAfterComplete(textControl, ref nameRange, ref decorationRange,
                tailType, ref suffix, ref caretPositionRangeMarker);

            if (context != null)
            {
                context.CompletionManager.Locks.QueueReadLock("Code completion inside markup extension",
                    () => context.CompletionManager.ExecuteManualCompletion(
                        CodeCompletionType.AutomaticCompletion, textControl, context.Solution, EmptyAction.Instance,
                        context.CompletionManager.GetPrimaryEvaluationMode(CodeCompletionType.AutomaticCompletion),
                        AutocompletionBehaviour.DoNotAutocomplete));
            }
        }
Example #21
0
        protected override void OnAfterComplete(ITextControl textControl, ref TextRange nameRange,
                                                ref TextRange decorationRange, TailType tailType, ref Suffix suffix,
                                                ref IRangeMarker caretPositionRangeMarker)
        {
            // TODO: completion with a space can break this
            base.OnAfterComplete(textControl, ref nameRange, ref decorationRange,
                                 tailType, ref suffix, ref caretPositionRangeMarker);

            if (context != null)
            {
                context.CompletionManager.Locks.QueueReadLock("Code completion inside markup extension",
                                                              () => context.CompletionManager.ExecuteManualCompletion(
                                                                  CodeCompletionType.AutomaticCompletion, textControl, context.Solution, EmptyAction.Instance,
                                                                  context.CompletionManager.GetPrimaryEvaluationMode(CodeCompletionType.AutomaticCompletion),
                                                                  AutocompletionBehaviour.DoNotAutocomplete));
            }
        }
Example #22
0
        /// <inheritdoc/>
        public void Process(
            IPsiSourceFile sourceFile,
            IRangeMarker rangeMarker,
            CodeCleanupProfile profile,
            IProgressIndicator progressIndicator)
        {
            IPsiServices psiServices            = sourceFile.GetPsiServices();
            IPsiFiles    psiFiles               = psiServices.Files;
            IContextBoundSettingsStore settings = sourceFile.GetSettingsStore();
            var orderUsingSettings              =
                settings.GetKey <OrderUsingsSettings>(SettingsOptimization.DoMeSlowly);
            OrderUsingsConfiguration config = null;

            if (!string.IsNullOrWhiteSpace(orderUsingSettings.OrderSpecificationXml))
            {
                config = ConfigurationSerializer.FromXml(new StringReader(orderUsingSettings.OrderSpecificationXml));
            }

            if (config == null)
            {
                return;
            }

            var file = psiFiles.GetDominantPsiFile <CSharpLanguage>(sourceFile) as ICSharpFile;

            if (file == null)
            {
                return;
            }

            if (!profile.GetSetting(DescriptorInstance))
            {
                return;
            }

            file.GetPsiServices().Transactions.Execute(
                "Code cleanup",
                () =>
            {
                using (_shellLocks.UsingWriteLock())
                {
                    CleanUsings(file, config);
                    WalkNamespaceDeclarations(file.NamespaceDeclarations, config);
                }
            });
        }
Example #23
0
        private LinkedList <KeyValueSettingLookupItem> CreateLookupItems(
            ISpecificCodeCompletionContext context,
            IEnumerable <KeyValueSetting> settings,
            IProjectModelElement project,
            IRangeMarker rangeMarker,
            LinkedList <KeyValueSettingLookupItem> lookupItems)
        {
            foreach (var setting in settings)
            {
                var iconId     = _presentationService.GetIcon(project);
                var lookupItem = new KeyValueSettingLookupItem(setting, iconId, rangeMarker);
                lookupItem.InitializeRanges(context.EvaluateRanges(), context.BasicContext);

                lookupItems.AddLast(lookupItem);
            }

            return(lookupItems);
        }
            public EnumMemberLookupItem([NotNull] IRangeMarker dotRangeMarker,
                                        [NotNull] DeclaredElementInstance <IField> enumMember,
                                        [NotNull] string normalizedValue,
                                        [NotNull] string value, bool isFlags)
            {
                myDotRangeMarker = dotRangeMarker;
                myPointer        = enumMember.CreateElementInstancePointer();
                myShortName      = enumMember.Element.ShortName;
                myIsFlags        = isFlags && normalizedValue.Any(x => x != '0'); // ugh :(
                myIdentity       = "   ENUM_MEMBER_" + normalizedValue;

                DisplayName = new RichText(myShortName, new TextStyle(FontStyle.Bold));

                if (value.Length <= 32) // protect from too heavy values
                {
                    DisplayTypeName = new RichText("= " + value, new TextStyle(FontStyle.Regular, SystemColors.GrayText));
                }
            }
        /// <inheritdoc/>
        public void Process(
            IPsiSourceFile sourceFile,
            IRangeMarker rangeMarker,
            CodeCleanupProfile profile,
            IProgressIndicator progressIndicator)
        {
            IPsiServices psiServices = sourceFile.GetPsiServices();
            IPsiFiles psiFiles = psiServices.Files;
            IContextBoundSettingsStore settings = sourceFile.GetSettingsStore();
            var orderUsingSettings =
                settings.GetKey<OrderUsingsSettings>(SettingsOptimization.DoMeSlowly);
            OrderUsingsConfiguration config = null;
            if (!string.IsNullOrWhiteSpace(orderUsingSettings.OrderSpecificationXml))
            {
                config = ConfigurationSerializer.FromXml(new StringReader(orderUsingSettings.OrderSpecificationXml));
            }

            if (config == null)
            {
                return;
            }

            var file = psiFiles.GetDominantPsiFile<CSharpLanguage>(sourceFile) as ICSharpFile;
            if (file == null)
            {
                return;
            }

            if (!profile.GetSetting(DescriptorInstance))
            {
                return;
            }

            file.GetPsiServices().Transactions.Execute(
                "Code cleanup",
                () =>
                {
                    using (_shellLocks.UsingWriteLock())
                    {
                        CleanUsings(file, config);
                        WalkNamespaceDeclarations(file.NamespaceDeclarations, config);
                    }
                });
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            IExpression expression = CreateExpression();

            if (expression != null)
            {
                using (WriteLockCookie.Create())
                    expression = ReplaceElement(_selectedExpression, expression);
                if (expression != null)
                {
                    IFile        file      = expression.GetContainingFile();
                    ISolution    solution1 = expression.GetPsiServices().Solution;
                    IRangeMarker marker    = expression.GetDocumentRange().CreateRangeMarker(solution1.GetComponent <DocumentManager>());
                    OptimizeRefs(marker, file);
                }
            }

            return(null);
        }
        public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator)
        {
            var file = sourceFile.GetTheOnlyPsiFile(CSharpLanguage.Instance);

            if (file == null)
            {
                return;
            }

            if (!profile.GetSetting(DescriptorInstance))
            {
                return;
            }

            file.GetPsiServices().Transactions.Execute("Reflow XML Documentation Comments",
                                                       () =>
            {
                using (_shellLocks.UsingWriteLock())
                    file.ProcessChildren <IDocCommentBlockNode>(node => CommentReflowAction.ReFlowCommentBlockNode(file.GetSolution(), progressIndicator, node));
            });
        }
        public void Process(
            IPsiSourceFile sourceFile, IRangeMarker rangeMarker,
            CodeCleanupProfile profile, IProgressIndicator progressIndicator)
        {
            var settingsStore = sourceFile.GetSettingsStore();
            var settings      = settingsStore.GetKey <XamlAttributeOrderingSettings>(SettingsOptimization.OptimizeDefault);

            if (!profile.GetSetting(DescriptorInstance) || !settings.Enable)
            {
                return;
            }

            foreach (var xamlFile in sourceFile.GetPsiFiles <XamlLanguage>().OfType <IXamlFile>())
            {
                sourceFile.GetPsiServices().Transactions.Execute("Code cleanup",
                                                                 () => {
                    var comparer = new AttributesComparer(settings);
                    xamlFile.ProcessDescendants(new ReorderAttributesProcessor(comparer));
                });
            }
        }
 public ProjectReferenceLookupItem(IProject project, IconId image, IRangeMarker rangeMarker)
     : base(GetCompleteText(project), image)
 {
     this.project = project;
     VisualReplaceRangeMarker = rangeMarker;
 }
 protected override void OnAfterComplete(ITextControl textControl, ref TextRange nameRange, ref TextRange decorationRange, TailType tailType,
                                         ref Suffix suffix, ref IRangeMarker caretPositionRangeMarker)
 {
 }
 protected override void OptimizeRefs(IRangeMarker marker, IFile file)
 {
   file.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance);
 }
 protected override void OptimizeRefs(IRangeMarker marker, IFile file)
 {
     file.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance);
 }
 protected abstract void OptimizeRefs(IRangeMarker marker, IFile file);
        /// <summary>
        /// Process clean-up on file.
        /// </summary>
        /// <param name="projectFile">
        /// The project file to process.
        /// </param>
        /// <param name="rangeMarker">
        /// The range marker to process.
        /// </param>
        /// <param name="profile">
        /// The code cleanup settings to use.
        /// </param>
        /// <param name="progressIndicator">
        /// The progress indicator.
        /// </param>
        public void Process(
            IPsiSourceFile projectFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, JB::JetBrains.Application.Progress.IProgressIndicator progressIndicator)
        {
            if (projectFile == null)
            {
                return;
            }

            if (!this.IsAvailable(projectFile))
            {
                return;
            }

            ISolution solution = projectFile.GetSolution();

            ICSharpFile file = projectFile.GetPsiFile<CSharpLanguage>() as ICSharpFile;

            if (file == null)
            {
                return;
            }

            PsiManager.GetInstance(solution).DoTransaction(() => this.InternalProcess(profile, file), "Code cleanup");

            StyleCopTrace.Out();
        }
        private void Accept(ITextControl textControl, IRangeMarker rangeMarker, ISolution solution)
        {
            var identifierNode = TextControlToPsi.GetElement <ITreeNode>(solution, textControl);
            var psiServices    = solution.GetPsiServices();

            if (identifierNode != null)
            {
                IErrorElement errorElement;

                ITreeNode usage = identifierNode.GetContainingNode <IUserTypeUsage>();
                if (usage != null)
                {
                    errorElement = usage.NextSibling as IErrorElement;
                }
                else
                {
                    usage = identifierNode.PrevSibling;
                    while (usage != null && !(usage is ITypeUsage))
                    {
                        usage = usage.PrevSibling;
                    }
                    errorElement = identifierNode.NextSibling as IErrorElement;
                }

                using (var cookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "RemoveIdentifier"))
                    using (new DisableCodeFormatter())
                    {
                        using (WriteLockCookie.Create())
                        {
                            ModificationUtil.DeleteChild(identifierNode);
                            if (usage != null)
                            {
                                ModificationUtil.DeleteChild(usage);
                            }
                            if (errorElement != null)
                            {
                                ModificationUtil.DeleteChild(errorElement);
                            }
                        }

                        cookie.Commit();
                    }
            }

            using (WriteLockCookie.Create())
            {
                textControl.Document.InsertText(rangeMarker.DocumentRange.StartOffset, "void Foo(){}");
            }

            psiServices.Files.CommitAllDocuments();

            var methodDeclaration = TextControlToPsi.GetElement <IMethodDeclaration>(solution, textControl);

            if (methodDeclaration == null)
            {
                return;
            }

            var insertionIndex = methodDeclaration.GetTreeStartOffset().Offset;

            string attributeText = null;

            var attributeList = methodDeclaration.FirstChild as IAttributeSectionList;

            if (attributeList != null)
            {
                attributeText = attributeList.GetText();
                var treeNode = attributeList.NextSibling;
                while (treeNode is IWhitespaceNode)
                {
                    attributeText += treeNode.GetText();
                    treeNode       = treeNode.NextSibling;
                }
            }

            using (var cookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "RemoveInsertedDeclaration"))
                using (new DisableCodeFormatter())
                {
                    using (WriteLockCookie.Create())
                        ModificationUtil.DeleteChild(methodDeclaration);

                    cookie.Commit();
                }

            // Get the UnityEventFunction generator to actually insert the methods
            GenerateCodeWorkflowBase.ExecuteNonInteractive(
                GeneratorUnityKinds.UnityEventFunctions, solution, textControl, methodDeclaration.Language,
                configureContext: context =>
            {
                var inputElements = from e in context.ProvidedElements.Cast <GeneratorDeclaredElement <IMethod> >()
                                    where myEventFunction.Match(e.DeclaredElement) != EventFunctionMatch.NoMatch
                                    select e;

                context.InputElements.Clear();
                context.InputElements.AddRange(inputElements);
            });

            if (!string.IsNullOrEmpty(attributeText))
            {
                using (WriteLockCookie.Create())
                    textControl.Document.InsertText(insertionIndex, attributeText);
            }
        }
 protected abstract void OptimizeRefs(IRangeMarker marker, IFile file);
Example #37
0
        private void Accept(ITextControl textControl, IRangeMarker rangeMarker, ISolution solution)
        {
            var psiServices = solution.GetPsiServices();

            // Get the node at the caret. This will be the identifier
            var identifierNode = TextControlToPsi.GetElement <ITreeNode>(solution, textControl);

            if (identifierNode == null)
            {
                return;
            }

            // Delete the half completed identifier node. Also delete any explicitly entered
            // return type, as our declared element will create one anyway
            if (!(identifierNode.GetPreviousMeaningfulSibling() is ITypeUsage typeUsage))
            {
                // E.g. `void OnAnim{caret} [SerializeField]...` This is parsed as a field with an array specifier
                var fieldDeclaration = identifierNode.GetContainingNode <IFieldDeclaration>();
                typeUsage = fieldDeclaration?.GetPreviousMeaningfulSibling() as ITypeUsage;
            }

            using (var cookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "RemoveIdentifier"))
                using (new DisableCodeFormatter())
                {
                    using (WriteLockCookie.Create())
                    {
                        ModificationUtil.DeleteChild(identifierNode);
                        if (typeUsage != null)
                        {
                            ModificationUtil.DeleteChild(typeUsage);
                        }
                    }

                    cookie.Commit();
                }

            // Insert a dummy method declaration, as text, which means the PSI is reparsed.
            // This will remove empty type usages and merge leading attributes into a method
            // declaration, such that we can copy them and replace them once the declared
            // element has expanded. This also fixes up the case where the type usage picks
            // up the attribute of the next code construct as an array specifier.
            // E.g. `OnAni{caret} [SerializeField]`
            using (WriteLockCookie.Create())
                textControl.Document.InsertText(rangeMarker.DocumentRange.StartOffset, "void Foo(){}");

            psiServices.Files.CommitAllDocuments();

            var methodDeclaration = TextControlToPsi.GetElement <IMethodDeclaration>(solution, textControl);

            if (methodDeclaration == null)
            {
                return;
            }

            var attributeList = methodDeclaration.FirstChild as IAttributeSectionList;

            using (var cookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "RemoveInsertedDeclaration"))
                using (new DisableCodeFormatter())
                {
                    using (WriteLockCookie.Create())
                        ModificationUtil.DeleteChild(methodDeclaration);
                    cookie.Commit();
                }

            // Get the UnityEventFunction generator to actually insert the methods
            GenerateCodeWorkflowBase.ExecuteNonInteractive(
                GeneratorUnityKinds.UnityEventFunctions, solution, textControl, identifierNode.Language,
                configureContext: context =>
            {
                var inputElements = from e in context.ProvidedElements.Cast <GeneratorDeclaredElement <IMethod> >()
                                    where myEventFunction.Match(e.DeclaredElement) != MethodSignatureMatch.NoMatch
                                    select e;

                context.InputElements.Clear();
                context.InputElements.AddRange(inputElements);
            });

            if (attributeList != null)
            {
                methodDeclaration = TextControlToPsi.GetElement <IMethodDeclaration>(solution, textControl);
                if (methodDeclaration != null)
                {
                    using (var transactionCookie =
                               new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "InsertAttributes"))
                    {
                        methodDeclaration.SetAttributeSectionList(attributeList);
                        transactionCookie.Commit();
                    }
                }
            }
        }
 public T4OutsideSolutionOccurrence([NotNull] IRangeMarker rangeMarker) => RangeMarker = rangeMarker;
        protected override void OnAfterComplete(ITextControl textControl, ref TextRange nameRange,
            ref TextRange decorationRange, TailType tailType, ref Suffix suffix,
            ref IRangeMarker caretPositionRangeMarker)
        {
            // TODO: completion with a space can break this
            base.OnAfterComplete(textControl, ref nameRange, ref decorationRange,
                tailType, ref suffix, ref caretPositionRangeMarker);

            if (context != null)
            {
                context.CompletionManager.Locks.QueueReadLock("Code completion inside markup extension",
                    () => ExecuteManualCompletion(textControl));
            }
        }
		public T4OutsideSolutionOccurence([NotNull] IRangeMarker rangeMarker) {
			_rangeMarker = rangeMarker;
		}
Example #41
0
 public ProjectReferenceLookupItem(IProject project, IconId image, IRangeMarker rangeMarker)
     : base(GetCompleteText(project), image)
 {
     this.project             = project;
     VisualReplaceRangeMarker = rangeMarker;
 }
        /// <summary>
        /// Process clean-up on file.
        /// </summary>
        /// <param name="projectFile">
        /// The project file to process.
        /// </param>
        /// <param name="rangeMarker">
        /// The range marker to process.
        /// </param>
        /// <param name="profile">
        /// The code cleanup settings to use.
        /// </param>
        /// <param name="progressIndicator">
        /// The progress indicator.
        /// </param>
        public void Process(
            IPsiSourceFile projectFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, JetBrains.Application.Progress.IProgressIndicator progressIndicator)
        {
            if (projectFile == null)
            {
                return;
            }

            if (!this.IsAvailable(projectFile))
            {
                return;
            }

            ISolution solution = projectFile.GetSolution();

            ICSharpFile file = projectFile.GetDominantPsiFile<CSharpLanguage>() as ICSharpFile;

            if (file == null)
            {
                return;
            }

            var services = solution.GetPsiServices(); 
            services.Transactions.Execute("Code cleanup", () => this.InternalProcess(profile, file));

            StyleCopTrace.Out();
        }
Example #43
0
 public KeyValueSettingLookupItem(KeyValueSetting keyValueSetting, IconId image, IRangeMarker rangeMarker)
     : base(GetCompleteText(keyValueSetting), image)
 {
     _keyValueSetting         = keyValueSetting;
     VisualReplaceRangeMarker = rangeMarker;
 }