David and Harm, I'm really impressed by the level of expertise you both have showed in this thread. The function works wonderfully, and I'm really grateful for your help!
I feel kind of bad for asking, but I'm stuck after trying to do what I thought would be a minor tweak. I wanted to make it so that the two lines that form the hairpin would end in the same vertical line, since when the hairpin is rotated the end-points of the two lines are displaced. I tried achieve this by drawing a white box that overlaps with the line that overextends, therefore "deleting" the excess.
While I could not always place the box correctly, due to how
ly:stencil-stack works (I don't explain this further because of the following), the real problem I found is that even when the box is properly placed, the shortened line looks off. This is because Lilypond naturally makes line endings smooth, so the "cut the excess with a box" approach creates a hairpin with one line ending smoothly and the other ending harshly. This is less evident for thinner lines but is easy to see with thicker ones. Another flaw of this approach is that the white box reserves unused space.