Calva: Adding ns form to a newly created clojure file

Created on 13 Nov 2020  路  7Comments  路  Source: BetterThanTomorrow/calva

Cursive and Emacs have this feature. It would be nice to have it in Calva too.

When I create a new clojure file, I'd like its ns form is created automatically. For example if a new file is src/my_app/core.clj, I'd expect to see (ns my-app.core) in it.

To do it we need to add a handler for workspace.onDidCreateFiles.
https://code.visualstudio.com/api/references/vscode-api#workspace

Also the vscode-java extension already supports similar feature for java files.

Most helpful comment

ns-form-autocreation

All 7 comments

We need a way to collect all current source paths.

Why are all source paths needed?

Because to get ns form we need to build a relative path first.

function resolvePackageName(sourcePaths: string[], filePath: string): string {
    if (!sourcePaths || !sourcePaths.length) {
        return "";
    }
    for (const sourcePath of sourcePaths) {
        if (isPrefix(sourcePath, filePath)) {
            const relative = path.relative(sourcePath, path.dirname(filePath));
            return relative.replace(/[\/\\]/g, ".")
                           .replace("_", "-");
        }
    }
    return "";
}

In general, any directory under a clojure project could be a source path.

There are at least two common ways to get source paths.
1) Read deps.edn or project.clj (Cursive)
2) Ask nREPL for a classpath and extract source paths from it (CIDER, but also it has a fallback way).

Today I made a prototype with a hardcoded source path. Works fine.

ns-form-autocreation

Ah, so wherever the file is created you need to find the first parent folder that is a source directory (which probably would be the only in that path)?

Right.

Was this page helpful?
0 / 5 - 0 ratings