Skip to content

Commit

Permalink
feat: sort block headers
Browse files Browse the repository at this point in the history
  • Loading branch information
1nVitr0 committed May 6, 2021
1 parent bf5ef4c commit 4c3fba5
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/providers/BlockSortProvider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Range, Selection, TextDocument } from 'vscode';
import ConfigurationProvider from './ConfigurationProvider';
import StringProcessingProvider, { Folding } from './StringProcessingProvider';

type SortingStrategy = 'asc' | 'desc';
Expand All @@ -18,7 +19,9 @@ export default class BlockSortProvider {
}

public sortBlocks(blocks: Range[], sort: (a: string, b: string) => number = BlockSortProvider.sort.asc): string[] {
const textBlocks = blocks.map((block) => this.document.getText(block));
let textBlocks = blocks.map((block) => this.document.getText(block));
if (ConfigurationProvider.getSortConsecutiveBlockHeaders())
textBlocks = textBlocks.map((block) => this.sortBlockHeaders(block, sort));

if (this.stringProcessor.isList(blocks) && textBlocks.length && !/,$/.test(textBlocks[textBlocks.length - 1])) {
textBlocks[textBlocks.length - 1] += ',';
Expand Down Expand Up @@ -156,6 +159,23 @@ export default class BlockSortProvider {
return this.document.validateRange(range);
}

private sortBlockHeaders(block: string, sort: (a: string, b: string) => number = BlockSortProvider.sort.asc): string {
let lines = block.split(/\r?\n/);
const headers: string[] = [];

let currentLine;
while ((currentLine = lines.shift()) && this.stringProcessor.isMultiBlockHeader(currentLine)) {
headers.push(currentLine);
currentLine = undefined;
}

if (currentLine !== undefined) lines.unshift(currentLine);
this.applySort(headers, sort);
lines = [...headers, ...lines];

return lines.join('\n');
}

private applySort(blocks: string[], sort: (a: string, b: string) => number = BlockSortProvider.sort.asc) {
blocks.sort((a, b) =>
sort(
Expand Down

0 comments on commit 4c3fba5

Please sign in to comment.