Skip to content

Commit 2b471cf

Browse files
committed
Force a different clang-formatter configuration on autoformat
The configuration is provided just for the time needed for the formatter to run, afterwards the file is removed. This should not affect users since the file is created in the temporary folder.
1 parent 63e2721 commit 2b471cf

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: handler/handler.go

+33
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,11 @@ func (handler *InoHandler) HandleMessageFromIDE(ctx context.Context, conn *jsonr
411411
p.TextDocument, err = handler.ino2cppTextDocumentIdentifier(p.TextDocument)
412412
cppURI = p.TextDocument.URI
413413
log.Printf(" --> formatting(%s)", p.TextDocument.URI)
414+
if cleanup, e := handler.createClangdFormatterConfig(cppURI); e != nil {
415+
err = e
416+
} else {
417+
defer cleanup()
418+
}
414419

415420
case *lsp.DocumentRangeFormattingParams:
416421
// Method: "textDocument/rangeFormatting"
@@ -420,6 +425,11 @@ func (handler *InoHandler) HandleMessageFromIDE(ctx context.Context, conn *jsonr
420425
params = cppParams
421426
cppURI = cppParams.TextDocument.URI
422427
log.Printf(" --> %s(%s:%s)", req.Method, cppParams.TextDocument.URI, cppParams.Range)
428+
if cleanup, e := handler.createClangdFormatterConfig(cppURI); e != nil {
429+
err = e
430+
} else {
431+
defer cleanup()
432+
}
423433
} else {
424434
err = e
425435
}
@@ -1749,6 +1759,29 @@ func (handler *InoHandler) FromClangd(ctx context.Context, connection *jsonrpc2.
17491759
return result, err
17501760
}
17511761

1762+
func (handler *InoHandler) createClangdFormatterConfig(cppuri lsp.DocumentURI) (func(), error) {
1763+
// clangd looks for a .clang-format configuration file on the same directory
1764+
// pointed by the uri passed in the lsp command parameters.
1765+
// https://github.com/llvm/llvm-project/blob/64d06ed9c9e0389cd27545d2f6e20455a91d89b1/clang-tools-extra/clangd/ClangdLSPServer.cpp#L856-L868
1766+
// https://github.com/llvm/llvm-project/blob/64d06ed9c9e0389cd27545d2f6e20455a91d89b1/clang-tools-extra/clangd/ClangdServer.cpp#L402-L404
1767+
1768+
config := `
1769+
AllowShortFunctionsOnASingleLine: None
1770+
`
1771+
targetFile := cppuri.AsPath()
1772+
if targetFile.IsNotDir() {
1773+
targetFile = targetFile.Parent()
1774+
}
1775+
targetFile = targetFile.Join(".clang-format")
1776+
cleanup := func() {
1777+
targetFile.Remove()
1778+
log.Printf(" formatter config cleaned")
1779+
}
1780+
log.Printf(" writing formatter config in: %s", targetFile)
1781+
err := targetFile.WriteFile([]byte(config))
1782+
return cleanup, err
1783+
}
1784+
17521785
func (handler *InoHandler) showMessage(ctx context.Context, msgType lsp.MessageType, message string) {
17531786
defer streams.CatchAndLogPanic()
17541787

0 commit comments

Comments
 (0)