string-pixel-width respects the selected window and also, more importantly, respects face remappings as one has to when using text-scale-mode. In Emacs 31, it uses work buffers which are an order of magnitude faster than temp buffers (reused pool) which eliminates gc pressure. I'm sure there was a reason to avoid the standard function but as the code could have been written by an LLM, it's hard to reason about as it/the author did not add a comment about that. Emacs 31 also has the function truncate-string-pixelwise which you could use to fit strings into constrained specified space.
string-pixel-widthrespects the selected window and also, more importantly, respects face remappings as one has to when usingtext-scale-mode. In Emacs 31, it uses work buffers which are an order of magnitude faster than temp buffers (reused pool) which eliminates gc pressure. I'm sure there was a reason to avoid the standard function but as the code could have been written by an LLM, it's hard to reason about as it/the author did not add a comment about that. Emacs 31 also has the functiontruncate-string-pixelwisewhich you could use to fit strings into constrained specified space.