Problem

I was working on a react native application and I needed to insert the relative path of an import statement based on the current file/buffer. Since this involves files, I immediately checked f.el for any function that would immediately get the relative path from a file to a file. The closest I got and was f-relative but it wasn't cutting it, it was giving me a file relative to a directory. After an hour or two of finding which function it is, I decided to just write it myself.

So write it I did and in such poor time, it took me another hour or two to get it done for whatever reason I could not comprehend. Once I did that, it was a simple matter to write the commands to get what I wanted.

Screencast

Here is a link of the code for the curious. I hope the screencast is helpful as it is my first and won't be my last. I hope I can make more simpler posts showing something done in Emacs, thanks to camcorder.el.

Notes

At first I thought it would be easy to implement by finding their common parent, determining the relative paths of the source and target path by f-relative, converting the relative source path into .. and just appending the relative target path with the path separator. Some things aren't just that easy.

But the use of f-relative and f-join did not return consistent outputs that I expected. So out of frustration, I just decided to find the common parent instead and thankfully f-split is one thing I can rely on.

By converting the source and target paths into lists and dropping the head until it wasn't equal, I thought I nailed it but apparently that wasn't enough. I realized after chopping the list of until there was no common parent, it didn't handle the case of neighboring files properly. What I needed was the last common parent which I dropped. As hard as I thought about it, I needed a recursive function maintaining that singular value which is helpful in both cases where either source or parent node is a parent of one another. I really hoped I didn't have to use a cond and recursion but I had to and it pains me to do so. Sometimes I just have to bite the bullet.

One small thing also tripped me up is the use of find-file-read-args where I needed a find-file interface without going to the file. You could argue I could use find-file-noselect but I didn't want to open the file at all. I just needed the file path, I didn't have to open it. It took me some time to find the function and the hazard that it returns a pair instead of just the filename. The bigger concern here is that I might have used a private function and maybe I should have just read the manual. Oh well.w