lmcarreiro / vscode-smart-column-indenter

Visual Studio Code extension that adds support for indenting code into columns, to make the code more beautiful, readable, clear and with fewer lines of code.
MIT License
12 stars 4 forks source link

Add option to automatically indent TypeScript import blocks into N columns on save #1

Open ghost opened 6 years ago

ghost commented 6 years ago

I like your extension and would use it for my import blocks, unfortunately both the VSCode formatter and Prettier remove the formatting. I'd like to ask, whether it is possible to add an option that would, once a file is being saved (hopefully after VSCode's auto formatting), do the following:

ghost commented 6 years ago

If anyone is looking for this feature as well I have a bandaid solution. I am leveraging the forked (NOT the original Save and Run extension) with the following configuration:

{
    "saveAndRun": {
        "commands": [
            {
                "match": "\\.tsx?$",
                "cmd": "npm run hygiene ${file}",
                "useShortcut": false,
                "silent": true
            }
        ]
    }
}

My package.json defines the hygiene script as follows: "hygiene": "ts-node Scripts/ImportIndenter.ts". Finally the script itself looks like this:

import * as fs       from "fs"                   ;
import      Indenter from "smart-column-indenter";

/**
 * Applies smart column indentation by N columns to all import blocks in the specified file.
 */
((): void => {
    const filePath: string = process.argv[2];
    if (filePath !== null && fs.existsSync(filePath)) {
        const fileContents: string = fs.readFileSync(filePath).toString();
        const importMatcher: RegExp = new RegExp(/import.*;\n(?:import.*;(?:\n)?)+/g);
        const matches: RegExpMatchArray | null = fileContents.match(importMatcher);
        if (matches !== null) {
            let newContents: string = fileContents;
            matches.forEach((match: string): void => {
                newContents = newContents.replace(match, new Indenter(match, "ts").indent("N"));
            });
            fs.writeFileSync(filePath, newContents);
        }
    }
})();
lmcarreiro commented 6 years ago

Sorry for not giving a reply to this issue earlier, I'm in a private side project right now and don't have time to spend in this extension right now.

Feel free to make a Pull Request if you want, just put this as an option in the settings of vscode, leaving the default behavior with this option disabled and I'll gladly merge it.