Adding attachment custom field metadata to TinyMCE tag

Currently I’ve achieved a somewhat acceptable solution by using the do_shortcode_tag filter as mentioned in this answer, and using get_post_meta to fetch the value, as mentioned in this answer.

There are (at least!) two caveats, however:

  • The id in do_shortcode_tag‘s $attr isn’t the attachment post ID, but rather the CSS id from the original shortcode. I’m having to hope it’ll be always attachment_NNN (where NNN is the attachment ID),
  • The user can’t edit the value on TinyMCE. It can be actually a good thing, because of consistency.

I’m hoping someone can come up with a better answer!