1

A JavaScript project is setup with webpack path resolver like this:

    resolve: {
        alias: {
            '~': path.resolve(cwd, 'src')
        }
    },

This has the effect that a line in c:/projects/myproject/src/models/User.js

import '~/config/global';

will point to c:/projects/myproject/src/config/global.js.

Can I setup find-file-at-point (or any other interactive function) so that when in User.js the point is at the file path ~/config/global.js and I invoke f-f-a-p (or other magic), the global.js file is opened?

I.e., can I replace the meaning of ~ on a per-project or global basis?

This is Windows 10 if it makes a difference.

1

This custom function finds the file as described by looking for the src directory of the file currently being visited and assumes that the directory one above is the cwd.

As a consequence it only works if used while visiting a file somewhere inside the src directory else it will not find the cwd.

(defun my-find-file-at-point-with-tilde ()
  "Find the file at point changing tilde to project root."
  (interactive)
  (let* ((current-filename buffer-file-name)
         ;; Get cwd from filename.
         (cwd (car (split-string current-filename "/src/")))
         ;; Get filename at point.
         (filename-at-point (thing-at-point 'filename))
         ;; Replace ~ with src
         (filename-stripped (replace-regexp-in-string "~" "src" filename-at-point))
         ;; Get the filename with cwd and the stripped filename.
         (filename (expand-file-name filename-stripped cwd)))
    (if (file-exists-p filename)
        (find-file filename)
      (user-error "File %s does not exist" filename))))

Evaluate the function or add it to your init file and then call it with M-x my-find-file-at-point-with-tilde RET while point is at ~/config/global.js.

Remark:
It would be probably better to use something else than the tilde as this is usually reserved for the home directory and might confuse others.

| improve this answer | |
1

Use https://github.com/technomancy/find-file-in-project (ffip).

What ~ means does not matter. ffip will try to find file in project root using the file name under cursor.

Example, https://emacs.stackexchange.com/a/50567/202

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.