EeyoreLee/vscode-extension-yapf

Range Formatting

Closed this issue · 6 comments

From my experience working with the ma-python.black-formatter and ms-python.autopep8, users often seem to trigger selection formatting. I have implemented this support in black and autopep8. You could replicate that here to provide a better experience in those scenarios.

If range formatting is not supported, black does not have range formatting. so in that case we leave a warning in logs and return edits for the whole file.
microsoft/vscode-black-formatter#342

if range formating is supported. autopep8 supports range formatting. For this case we use the range formatting option in autopep8. Edits are returned only for the lines with changes.
microsoft/vscode-autopep8#175

@karthiknadig - Thanks for your implement. I'll add this feature next. BTW, I wonder if a user has the code below

x = 1 + 2 + \
3+4
y = [1, 2]

but only select the last two lines. what's the result should be expected

3 + 4
y = [1, 2]

or

3+4
y = [1, 2]

cause the last result is same as formatting the whole file but seems different from formatting only the snippet.

That feels like a bug in the tool itself. I would say the first result with 3 + 4, seems like the correct answer.

@karthiknadig - sorry for the ambiguity. For yapf, if the line end of a backslash, the line and the next line will be ignored to format means 3+4 shouldn't be format if users format the whole file. so 3 + 4 is different from formatOnSave mode. formatOnType mode has the same situation. I originally planned to get a new range that contain the origin range and find the true complete rows of the first row and last row of the selection. Then it will be consistent cross all modes. Do you have a better idea?

I see.

I originally planned to get a new range that contain the origin range and find the true complete rows of the first row and last row of the selection.

That is a good solution.

@karthiknadig - I just found out the Format Selection knob use the same LSP feature with modification mode. I think I already implemented it at begining of the extension by PR #9 and #11 XD. But just provide a range to yapf. Do you think I need to do anything else for range format as I saw you also calculate Levenshtein distance and other things.

The way we did format document was we provided a single Edit for the whole document. For selections, this may result in changing areas users don't expect to change. So, I added a narrow edit calculator to cover those scenarios.