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

Handle multiple formatters #2328

Merged
merged 5 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions Default.sublime-commands
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
"caption": "LSP: Format File",
"command": "lsp_format_document",
},
{
"caption": "LSP: Format File With…",
"command": "lsp_format_document",
"args": {"select": true}
},
{
"caption": "LSP: Format Selection",
"command": "lsp_format_document_range",
Expand Down
5 changes: 5 additions & 0 deletions plugin/core/windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ def __init__(self, window: sublime.Window, workspace: ProjectFolders, config_man
self._server_log = [] # type: List[Tuple[str, str]]
self.panel_manager = PanelManager(self._window) # type: Optional[PanelManager]
self.tree_view_sheets = {} # type: Dict[str, TreeViewSheet]
self.formatters = {} # type: Dict[str, str]
self.formatter_updated_in_project = False
self.total_error_count = 0
self.total_warning_count = 0
sublime.set_timeout(functools.partial(self._update_panel_main_thread, _NO_DIAGNOSTICS_PLACEHOLDER, []))
Expand All @@ -106,6 +108,9 @@ def on_load_project_async(self) -> None:
self._config_manager.update()

def on_post_save_project_async(self) -> None:
if self.formatter_updated_in_project:
self.formatter_updated_in_project = False
return
jwortmann marked this conversation as resolved.
Show resolved Hide resolved
self.on_load_project_async()

def update_workspace_folders_async(self) -> None:
Expand Down
62 changes: 59 additions & 3 deletions plugin/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from .core.protocol import TextDocumentSaveReason
from .core.protocol import TextEdit
from .core.registry import LspTextCommand
from .core.registry import windows
from .core.sessions import Session
from .core.settings import userprefs
from .core.typing import Any, Callable, List, Optional, Iterator, Union
Expand All @@ -15,6 +16,7 @@
from .core.views import text_document_ranges_formatting
from .core.views import will_save_wait_until
from .save_command import LspSaveCommand, SaveTask
from functools import partial
import sublime


Expand Down Expand Up @@ -100,16 +102,70 @@ class LspFormatDocumentCommand(LspTextCommand):

capability = 'documentFormattingProvider'

def is_enabled(self, event: Optional[dict] = None, point: Optional[int] = None) -> bool:
def is_enabled(self, event: Optional[dict] = None, select: bool = False) -> bool:
if select:
return len(list(self.sessions(self.capability))) > 1
return super().is_enabled() or bool(self.best_session(LspFormatDocumentRangeCommand.capability))

def run(self, edit: sublime.Edit, event: Optional[dict] = None) -> None:
format_document(self).then(self.on_result)
def run(self, edit: sublime.Edit, event: Optional[dict] = None, select: bool = False) -> None:
session_names = [session.config.name for session in self.sessions(self.capability)]
base_scope = self.view.scope_name(0).split()[0]
jwortmann marked this conversation as resolved.
Show resolved Hide resolved
if select:
self.select_formatter(base_scope, session_names)
elif len(session_names) > 1:
window = self.view.window()
if not window:
return
formatter = None
project_data = window.project_data()
if isinstance(project_data, dict):
formatter = project_data.get('settings', {}).get('LSP', {}).get('formatters', {}).get(base_scope)
jwortmann marked this conversation as resolved.
Show resolved Hide resolved
else:
window_manager = windows.lookup(window)
if window_manager:
rchl marked this conversation as resolved.
Show resolved Hide resolved
formatter = window_manager.formatters.get(base_scope)
if formatter:
session = self.session_by_name(formatter, self.capability)
if session:
session.send_request_task(text_document_formatting(self.view)).then(self.on_result)
else:
self.select_formatter(base_scope, session_names)
else:
format_document(self).then(self.on_result)

def on_result(self, result: FormatResponse) -> None:
if result and not isinstance(result, Error):
apply_text_edits_to_view(result, self.view)

def select_formatter(self, base_scope: str, session_names: List[str]) -> None:
window = self.view.window()
if not window:
return
window.show_quick_panel(
session_names, partial(self.on_select_formatter, base_scope, session_names), placeholder="Select Formatter")

def on_select_formatter(self, base_scope: str, session_names: List[str], index: int) -> None:
if index > -1:
jwortmann marked this conversation as resolved.
Show resolved Hide resolved
session_name = session_names[index]
window = self.view.window()
if window:
window_manager = windows.lookup(window)
if window_manager:
project_data = window.project_data()
if isinstance(project_data, dict):
project_settings = project_data.setdefault('settings', dict())
project_lsp_settings = project_settings.setdefault('LSP', dict())
project_formatter_settings = project_lsp_settings.setdefault('formatters', dict())
project_formatter_settings[base_scope] = session_name
# Prevent restart of all sessions after project file save
window_manager.formatter_updated_in_project = True
window.set_project_data(project_data)
rchl marked this conversation as resolved.
Show resolved Hide resolved
else: # Save temporarily for this window
window_manager.formatters[base_scope] = session_name
session = self.session_by_name(session_name, self.capability)
if session:
session.send_request_task(text_document_formatting(self.view)).then(self.on_result)


class LspFormatDocumentRangeCommand(LspTextCommand):

Expand Down
8 changes: 8 additions & 0 deletions sublime-package.json
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,14 @@
"LSP": {
"type": "object",
"markdownDescription": "The dictionary of your configured language servers or overrides for existing configurations. The keys of this dictionary are free-form. They give a humany-friendly name to the server configuration. They are shown in the bottom-left corner in the status bar once attached to a view (unless you have `\"show_view_status\"` set to `false`).",
"properties": {
"formatters": {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we can assume that there will be no client config with this name.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feels weird to mix client configurations and other settings but I suppose this could be considered a bad initial design...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively we could use a different top-level key under "settings", for example "lsp_formatters". But I'd prefer to keep all LSP settings together under "LSP". And even if there were a config named "formatters" everything should still work fine, because the settings from that config and the formatter scope keys stored under the same name wouldn't influence each other.

"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"additionalProperties": {
"$ref": "sublime://settings/LSP#/definitions/ClientConfig"
}
Expand Down