I recently came across similar problem, I basically wanted to fontify code snippets in the documentation which I got some other source. I followed the approach mentioned towards the end of your answer and it worked fine for me. The function I ended up with some thing like the following
(defun my-fontify-yaml (text) (with-temp-buffer (erase-buffer) (insert text) (delay-mode-hooks (yaml-mode)) (font-lock-default-function 'yaml-mode) (font-lock-default-fontify-region (point-min) (point-max) nil) (buffer-string))) As @Malabarba pointed out in comments the simple approach above does not work if destination buffer uses font-lock-mode. However we can trick font-lock-mode into believing that the string is already font locked by setting the text property font-lock-face to the face, (we get the face property set, when we use the function above) and setting text-property fontified to t. The following function takes a string returned by the function above and does the required processing so that the string is inserted fontified (this is taken from org-mode's org-src-font-lock-fontify-block function
(defun my-fontify-using-faces (text) (let ((pos 0)) (while (setq next (next-single-property-change pos 'face text)) (put-text-property pos next 'font-lock-face (get-text-property pos 'face text) text) (setq pos next)) (add-text-properties 0 (length text) '(fontified t) text) text)) Now you can use it as follows
(insert (my-fontify-using-faces (my-fontify-yaml "application: test\nversion: 1")))