| // Copyright 2020 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package langserver |
| |
| import ( |
| "strings" |
| |
| "github.com/sourcegraph/go-lsp" |
| |
| "fidl-lsp/state" |
| ) |
| |
| // handleFormat asks the Analyzer for the formatted version of the document |
| // specified in `params` and returns any resulting TextEdits, or an error. |
| // |
| // In practice, since fidl-format only runs on an entire document, when |
| // successful this will always return a single TextEdit spanning (and replacing) |
| // the entire document with its formatted version. |
| func (h *LangHandler) handleFormat(params lsp.DocumentFormattingParams) ([]lsp.TextEdit, error) { |
| formatted, err := h.analyzer.FormatFile(h.fs, state.FileID(params.TextDocument.URI)) |
| if err != nil { |
| return nil, err |
| } |
| |
| lines := strings.Split(formatted, "\n") |
| lastLine := lines[len(lines)-1] |
| lastChar := len([]rune(lastLine)) |
| |
| return []lsp.TextEdit{{ |
| Range: lsp.Range{ |
| Start: lsp.Position{}, |
| End: lsp.Position{Line: len(lines), Character: lastChar}, |
| }, |
| NewText: formatted, |
| }}, nil |
| } |