|
| 1 | +" Copyright 2017 Google Inc. All rights reserved. |
| 2 | +" |
| 3 | +" Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +" you may not use this file except in compliance with the License. |
| 5 | +" You may obtain a copy of the License at |
| 6 | +" |
| 7 | +" http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +" |
| 9 | +" Unless required by applicable law or agreed to in writing, software |
| 10 | +" distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +" See the License for the specific language governing permissions and |
| 13 | +" limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +"" |
| 17 | +" @public |
| 18 | +" Format lines in the current buffer via a formatter invoked by {cmd}. The |
| 19 | +" command includes the explicit range line numbers to use, if any. |
| 20 | +" |
| 21 | +" @throws ShellError if the {cmd} system call fails |
| 22 | +function! codefmt#formatterhelpers#Format(cmd) abort |
| 23 | + let l:lines = getline(1, line('$')) |
| 24 | + let l:input = join(l:lines, "\n") |
| 25 | + |
| 26 | + let l:result = maktaba#syscall#Create(a:cmd).WithStdin(l:input).Call() |
| 27 | + let l:formatted = split(l:result.stdout, "\n") |
| 28 | + |
| 29 | + call maktaba#buffer#Overwrite(1, line('$'), l:formatted) |
| 30 | +endfunction |
| 31 | + |
| 32 | +"" |
| 33 | +" @public |
| 34 | +" Attempt to format a range of lines from {startline} to {endline} in the |
| 35 | +" current buffer via a formatter that doesn't natively support range |
| 36 | +" formatting (invoked by {cmd}), using a hacky strategy of sending those lines |
| 37 | +" to the formatter in isolation. |
| 38 | +" |
| 39 | +" If invoking this hack, please make sure to file a feature request against |
| 40 | +" the tool for range formatting and post a URL for that feature request above |
| 41 | +" code that calls it. |
| 42 | +" |
| 43 | +" @throws ShellError if the {cmd} system call fails |
| 44 | +function! codefmt#formatterhelpers#AttemptFakeRangeFormatting( |
| 45 | + \ startline, endline, cmd) abort |
| 46 | + call maktaba#ensure#IsNumber(a:startline) |
| 47 | + call maktaba#ensure#IsNumber(a:endline) |
| 48 | + |
| 49 | + let l:lines = getline(1, line('$')) |
| 50 | + let l:input = join(l:lines[a:startline - 1 : a:endline - 1], "\n") |
| 51 | + |
| 52 | + let l:result = a:cmd.WithStdin(l:input).Call() |
| 53 | + let l:formatted = split(l:result.stdout, "\n") |
| 54 | + " Special case empty slice: neither l:lines[:0] nor l:lines[:-1] is right. |
| 55 | + let l:before = a:startline > 1 ? l:lines[ : a:startline - 2] : [] |
| 56 | + let l:full_formatted = l:before + l:formatted + l:lines[a:endline :] |
| 57 | + |
| 58 | + call maktaba#buffer#Overwrite(1, line('$'), l:full_formatted) |
| 59 | +endfunction |
0 commit comments