Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add mix fmt external format processor #2578

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,16 @@
* `--module`
* `--sup`
* `--umbrella`
* [#2578](https://github.com/KronicDeth/intellij-elixir/pull/2578) - [@yordis](https://github.com/yordis)
yordis marked this conversation as resolved.
Show resolved Hide resolved
* Add `mix format` external formatter.
Requires project or module SDK be set in order to run. If the SDK is not available, only the internal formatter will be used. The internal formatter is still used for file subsection formatting and new line indenting as `mix format` works at the file-level.
* Allow `mix format` external formatter to be disabled.

1. Preferences
2. Editor > Code Style > Elixir
3. Click the `mix format` tab
4. Expand the General group
5. Uncheck "Format files with `mix format`".

### Bug Fixes

Expand Down Expand Up @@ -348,6 +358,8 @@
* [#2688]](https://github.com/KronicDeth/intellij-elixir/pull/2688) - [@KronicDeth](https://github.com/KronicDeth)
* Remove references to `ElementClassHint` in BeamFileImpl that only work in IntelliJ.
`ElementClassHint` is part of the `processDeclaration` system used in Java and so was in the code because `BeamFileImpl` was original based on `ClassFileImpl`, but since the Elixir resolvers don't use the hint system at all, it can just be removed.
* [#2578](https://github.com/KronicDeth/intellij-elixir/pull/2578) - [@yordis](https://github.com/KronicDeth/intellij-elixir/pull/2578)
* Remove `CodeStyleSettingsProvider` because it is redundant with `LanguageCodeStyleSettingsProvider`

## v13.0.0

Expand Down
64 changes: 53 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4177,7 +4177,13 @@ If you hold `Cmd` and hover over the variable before clicking, it will say `para

### Formatting

IntelliJ Elixir can reformat code to follow a consistent style.
IntelliJ Elixir both has an internal formatter used to format new linees and parts of files, but also can use `mix format` to format entire files.

#### Formatters

##### Internal

IntelliJ Elixir's internal formatter can reformat code to follow a consistent style.

* `do` block lines are indented
* `do` blocks `end` as the last argument of a no parentheses call unindents to the start of the call
Expand Down Expand Up @@ -4244,9 +4250,46 @@ IntelliJ Elixir can reformat code to follow a consistent style.
* Key exclusivity: if an association operation or keyword key is already on a line, the container value automatically has it's elements wrapped if there is nested associations or keyword pairs, so that two levels of keys are not on the same line.
* Indent bit string (`<< >>`) elements when wrapped

#### Directory
##### External (`mix format`)

IntelliJ Elixir will run `mix format -` on the text of the file. As `mix format` works on entire files, only whole
file, multiple file, or directory formatting is supported using this external formatter. Formatting subsections and
new lines use the internal formatter until the next full file format uses `mix format`.

**NOTE: The module or project SDK *MUST* be set in order to run `mix format`. If the SDK is not set, only the internal formatter will be run.**

###### Disabling

`mix format` can be disabled if you only want to use the Internal Formatter.

1. Preferences
2. Editor > Code Style > Elixir
3. Click the `mix format` tab
4. Expand the General group
4. Uncheck "Format files with `mix format`".

#### Format on Save

To tun on format on save:

1. Preferences
2. Tools > Actions on Save.
3. Check "Reformat code".
4. Make sure "All file types" is set or at least "Files: Elixir" is set.

##### Autosave

[JetBrains IDEs have autosave](https://www.jetbrains.com/help/idea/saving-and-reverting-changes.html) turned on by default when you click away from the editor window, but you can adjust the settings:

1. Preferences
2. Appearance & Behavior > System Settings.
3. Check or uncheck the settings in the Autosave section.

#### Formattables

##### Directory

All files in a directory can be reformatted.
All files in a directory can be reformatted using the External Formatter (`mix format`)

Using context menu:

Expand All @@ -4264,11 +4307,11 @@ Using keyboard shortcuts:
4. Set the desired options in the Reformat Code dialog
5. Click Run

#### File
##### File

##### Other File
###### Other File

All lines in a file can be reformatted.
All lines in a file can be reformatted with the External Formatter (`mix format`).

Using context menu:

Expand All @@ -4286,18 +4329,17 @@ Using keyboard shortcuts:
4. Set the desired options in the Reformat Code dialog
5. Click OK

##### Current File
###### Current File

All the lines in the current editor tab file can be reformatted with the
current settings.
All the lines in the current editor tab file can be reformatted with External Formatter (`mix format`).

* Code > Reformat
* `Alt+Cmd+L`
* `Alt+Shift+Cmd+L` to get the Reformat Code dialog.

#### Selection
##### Selection

A subset of a file can be reformatted.
A subset of a file can be reformatted using the Internal Formatter

1. Highlight the selection
2. Use the Reformat Code action
Expand Down
18 changes: 17 additions & 1 deletion resources/META-INF/changelog.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<html>
<body>
<h1>v13.0.1</h1>
<h1>v13.1.0</h1>
<ul>
<li>
<p>Enhancements</p>
Expand Down Expand Up @@ -37,6 +37,21 @@ <h1>v13.0.1</h1>
<li><code class="notranslate">--umbrella</code></li>
</ul>
</li>
<li>Add <code class="notranslate">mix format</code> external formatter.<br>
Requires project or module SDK be set in order to run. If the SDK is not available, only the internal formatter will be used. The internal formatter is still used for file subsection formatting and new line indenting as <code class="notranslate">mix format</code> works at the file-level.
<ul dir="auto">
<li>
<p dir="auto">Allow <code class="notranslate">mix format</code> external formatter to be disabled.</p>
<ol dir="auto">
<li>Preferences</li>
<li>Editor &gt; Code Style &gt; Elixir</li>
<li>Click the <code class="notranslate">mix format</code> tab</li>
<li>Expand the General group</li>
<li>Uncheck "Format files with <code class="notranslate">mix format</code>".</li>
</ol>
</li>
</ul>
</li>
</ul>
</li>
<li>
Expand Down Expand Up @@ -108,6 +123,7 @@ <h1>v13.0.1</h1>
<li>In IntelliJ 2022, the New Project dialog changed and it no longer automatically listed <code class="notranslate">ModuleType.getBuilder</code> <code class="notranslate">ModuleBuilder</code>s as potential project builders, so it looked like Elixir New Project support disappeared. Fix this by implementing the <code class="notranslate">newProjectWizard.language</code> extension that was added to control the Language switching in the new New Project dialog.</li>
<li>Remove references to <code class="notranslate">ElementClassHint</code> in BeamFileImpl that only work in IntelliJ.<br>
<code class="notranslate">ElementClassHint</code> is part of the <code class="notranslate">processDeclaration</code> system used in Java and so was in the code because <code class="notranslate">BeamFileImpl</code> was original based on <code class="notranslate">ClassFileImpl</code>, but since the Elixir resolvers don't use the hint system at all, it can just be removed.</li>
<li>Remove <code class="notranslate">CodeStyleSettingsProvider</code> because it is redundant with <code class="notranslate">LanguageCodeStyleSettingsProvider</code></li>
</ul>
</li>
</ul>
Expand Down
2 changes: 1 addition & 1 deletion resources/META-INF/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,12 @@
<lang.foldingBuilder language="Elixir" implementationClass="org.elixir_lang.folding.Builder"/>

<!-- formatting -->
<codeStyleSettingsProvider implementation="org.elixir_lang.formatter.settings.CodeStyleSettingsProvider"/>
<lang.formatter language="Elixir" implementationClass="org.elixir_lang.formatting.ModelBuilder"/>
<lang.formatter language="EEx"
implementationClass="com.intellij.psi.templateLanguages.SimpleTemplateLanguageFormattingModelBuilder"/>
<langCodeStyleSettingsProvider
implementation="org.elixir_lang.formatter.settings.LanguageCodeStyleSettingsProvider"/>
<externalFormatProcessor implementation="org.elixir_lang.formatter.MixFormatExternalFormatProcessor"/>

<!-- test -->
<runLineMarkerContributor language="Elixir"
Expand Down
1 change: 1 addition & 0 deletions src/org/elixir_lang/code_style/CodeStyleSettings.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public class CodeStyleSettings extends CustomCodeStyleSettings {
public boolean ALIGN_TWO_OPERANDS = true;
public boolean ALIGN_TYPE_DEFINITION_TO_RIGHT_OF_OPERATOR = true;
public int ALIGN_UNMATCHED_CALL_DO_BLOCKS = UnmatchedCallDoBlockAlignment.LINE.value;
public boolean MIX_FORMAT = true;
public boolean SPACE_AFTER_CAPTURE_OPERATOR = false;
public boolean SPACE_AROUND_AND_OPERATORS = true;
public boolean SPACE_AROUND_ARROW_OPERATORS = true;
Expand Down
111 changes: 111 additions & 0 deletions src/org/elixir_lang/formatter/MixFormatExternalFormatProcessor.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package org.elixir_lang.formatter

import com.intellij.application.options.CodeStyle
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.ExternalFormatProcessor
import org.elixir_lang.Mix
import org.elixir_lang.code_style.CodeStyleSettings
import org.elixir_lang.psi.ElixirFile
import org.elixir_lang.sdk.elixir.Type.Companion.mostSpecificSdk
import java.util.concurrent.TimeUnit

@Suppress("UnstableApiUsage")
@SuppressWarnings("UnstableApiUsage")
class MixFormatExternalFormatProcessor : ExternalFormatProcessor {
override fun activeForFile(source: PsiFile): Boolean =
source is ElixirFile && CodeStyle.getCustomSettings(source, CodeStyleSettings::class.java).MIX_FORMAT

override fun getId(): String = javaClass.name

override fun format(
source: PsiFile,
range: TextRange,
canChangeWhiteSpacesOnly: Boolean,
keepLineBreaks: Boolean,
enableBulkUpdate: Boolean,
cursorOffset: Int
): TextRange? =
// `mix format` doesn't support to format parts of a file
if (source.isValid && range == source.textRange) {
source.viewProvider.document?.let { document ->
val application = ApplicationManager.getApplication()

application.executeOnPooledThread {
workingDirectory(source)?.let { workingDirectory ->
mostSpecificSdk(source)?.let { sdk ->
format(workingDirectory, sdk, document.text)?.let { formattedText ->
application.invokeLater {
if (source.isValid) {
CommandProcessor.getInstance().runUndoTransparentAction {
application.runWriteAction {
document.setText(formattedText)
}
}
}
}
}
}
}
}

source.textRange
}
} else {
null
}

override fun indent(source: PsiFile, lineStartOffset: Int): String? = null

companion object {
private val LOGGER = Logger.getInstance(MixFormatExternalFormatProcessor::class.java)

private fun workingDirectory(psiFile: PsiFile): String? =
psiFile
.virtualFile
?.let { virtualFile ->
ProjectRootManager.getInstance(psiFile.project).fileIndex.getContentRootForFile(virtualFile)
}
?.takeIf { contentRoot ->
contentRoot.findChild("mix.exs") != null
}
?.path

private fun format(workingDirectory: String, sdk: Sdk, unformattedText: String): String? {
val commandline = Mix.commandLine(emptyMap(), workingDirectory, sdk)
commandline.addParameter("format")
// `-` turns on stdin/stdout for text to format
commandline.addParameter("-")
val processHandler = CapturingProcessHandler(commandline)
processHandler.processInput.use { stdin ->
stdin.write(unformattedText.toByteArray())
stdin.flush()
}

val indicator = ProgressManager.getGlobalProgressIndicator()
val timeout = TimeUnit.SECONDS.toMillis(5).toInt()
val output = if (indicator != null) {
processHandler.runProcessWithProgressIndicator(
indicator,
timeout,
true
)
} else {
processHandler.runProcess(timeout, true)
}

return if (output.checkSuccess(LOGGER)) {
output.stdout
} else {
null
}
}
}
}

This file was deleted.

17 changes: 17 additions & 0 deletions src/org/elixir_lang/formatter/settings/ElixirCodeStyleMainPanel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.elixir_lang.formatter.settings

import com.intellij.application.options.TabbedLanguageCodeStylePanel
import com.intellij.psi.codeStyle.CodeStyleSettings
import org.elixir_lang.ElixirLanguage

class ElixirCodeStyleMainPanel(currentSettings: CodeStyleSettings?, baseSettings: CodeStyleSettings) :
TabbedLanguageCodeStylePanel(ElixirLanguage, currentSettings, baseSettings) {

override fun initTabs(settings: CodeStyleSettings?) {
addTab(MixFormatPanel(settings))
addIndentOptionsTab(settings)
addSpacesTab(settings)
addWrappingAndBracesTab(settings)
// DO NOT have Blank Lines tab
}
}
Loading