Emacs: Embed Youtube Vid 🚀

By Xah Lee. Date: . Last updated: .

This command turns a YouTube URL into a embedded YouTube video on your blog.

(defun xah-html--get-youtube-id (Url)
  "Return the ID string inside a YouTube Url string.
If not found, error.
YouTube ID looks like this: gjiAjtGzC64
URL variations:
https://www.youtube.com/watch?v=gjiAjtGzC64
https://youtu.be/gjiAjtGzC64
https://www.youtube.com/embed/gjiAjtGzC64
 https://youtube.com/live/Z0DLy7zW_Ak?feature=share

Created: 2020-08-27
Version: 2024-04-25"
  (cond
   ((eq 11 (length Url))
    Url)
   ((string-match "v=\\(.\\{11\\}\\)" Url)
    (match-string-no-properties 1 Url))
   ((string-match "youtu\\.be/\\(.\\{11\\}\\)" Url)
    (match-string-no-properties 1 Url))
   ((string-match "youtube.com/embed/\\(.\\{11\\}\\)" Url)
    (match-string-no-properties 1 Url))
   ((string-match "youtube.com/live/\\(.\\{11\\}\\)" Url)
    (match-string-no-properties 1 Url))
   ((string-match "youtube.com/shorts/\\(.\\{11\\}\\)" Url)
    (match-string-no-properties 1 Url))
   (t (error "YouTube video ID cannot be found in: %s" Url))))

(defun xah-html-youtube-url-embed (&optional Begin End)
  "Make the YouTube URL under cursor into a embeded video.

The line can be any of

 https://www.youtube.com/watch?v=gjiAjtGzC64
 https://www.youtube.com/watch?v=gjiAjtGzC64?t=198
 https://www.youtube.com/watch?v=gjiAjtGzC64?t=3m18s
 https://youtu.be/gjiAjtGzC64
 https://www.youtube.com/embed/gjiAjtGzC64
 https://youtube.com/live/Z0DLy7zW_Ak?feature=share
 gjiAjtGzC64

Here's sample result:

<figure>
<iframe width=\"640\" height=\"480\" src=\"https://www.youtube.com/embed/gjiAjtGzC64\" allowfullscreen></iframe>
<figcaption>
</figcaption>
</figure>

URL `http://xahlee.info/emacs/emacs/elisp_embed_youtube_vid.html'
Created: 2020-08-27
Version: 2024-03-19"
  (interactive)
  (let (xp1 xp2 xinput xid xtimeStamp)
    (seq-setq (xp1 xp2) (if (and Begin End) (vector Begin End) (xah-get-pos-of-glyphs-or)))
    (setq xinput (buffer-substring-no-properties xp1 xp2))
    (setq xtimeStamp
          (if (or
               (string-match "t=\\([0-9ms]+\\)" xinput)
               (string-match "time_continue=\\([0-9ms]+\\)" xinput))
              (match-string 1 xinput)
            ""))
    (setq xid (xah-html--get-youtube-id xinput))
    (delete-region xp1 xp2)
    (insert
     (format "\n
<figure>
<iframe width=\"640\" height=\"480\" src=\"https://www.youtube.com/embed/%s%s\" allowfullscreen></iframe>
<figcaption>
</figcaption>
</figure>\n\n"
             xid
             (if (string-equal xtimeStamp "")
                 ""
               (concat "?start=" xtimeStamp))))
    (search-backward "</figcaption>")
    (backward-char 1)))

requires package Emacs: xah-get-thing.el