Pharo中方法保存的自动格式化



Pharo有一个内置的代码格式化程序。我希望每当我保存一个方法时,Pharo都会忽略我的所有格式,而是自动格式化代码。能做到吗?

当然,如果您使用重构引擎和OmniBrowser,会有一个设置:在"设置浏览器"中导航到接受时的重构引擎>自动格式。还有一个设置重构引擎>显示时自动格式化,它会在显示代码之前自动格式化代码。格式化设置本身位于重构引擎>可配置格式化程序中。

我想出了一种破解方法,来处理自格式化方法保存。它可能会派上用场。

NautilusUi -> compileSource: aText notifying: aController

在开头加上这一行。

self refactor formatSourceCode.

这将创建保存时的自动格式功能。我也承认,这不是正确的方式,但它对我有效。

 **compileSource: aText notifying: aController
        | source category method |
        self refactor formatSourceCode.
        source := aText asString.
        category := self selectedCategory.
        method := self selectedMethod.
        category ifNil: [ method ifNotNil: [ category := method protocol. ]. ].
        (category isNil and: [ method isNil. ])
            ifTrue: [
                source first isUppercase
                    ifTrue: [ ^ self compileAClassFrom: source notifying: aController. ].
                category := Categorizer default.
                ]
            ifFalse: [
                (category = self allLabel and: [ self selectedMethod notNil. ])
                    ifTrue: [ category := self selectedMethod protocol. ].
                ].
        self compileAMethodFromCategory: category withSource: source notifying: aController.**

对于OmniBrowser,我添加了这个新方法:

OBTextMorphEditorWithShout>>accept
"
This method did not previously exist for this class.
It is a subclass hook to auto format code on accept.
"
(ORCmdFormat on: 'TargetIsNotUsed' for: self model) execute.
super accept

不完全是OP的要求,但我认为这值得考虑。在项目中工作时,当Pull Request只显示功能性代码更改而没有与编码风格相关的误报时,规范化代码格式将有助于同行评审员的生活。

我发布PharoPackageFormatter正是为了这个。

以下是如何使用它的示例:

packages := { 
    'AST-Core'.
    'AST-Core-Tests'
    }.
packages do: [ :each | PharoPackageFormatter formatPackageNamed: each ].

最新更新