Add a full link-tag with automatic title
From Vim Tips Wiki
Tip 1178 Previous Tip • Next Tip
Created: March 18, 2006 Complexity: basic Author: Gerhard Siegesmund Minimum version: 6.0 Karma: 2/2 Imported from: Tip#1178
If you use Vim to edit html pages or blog entries, you sometimes want to enter links of the form: <a href="somelink" target="sometarget">title of the page</a>
With the following script (which only works under Unix with the lynx browser installed) you are interactively asked which URL to add, and what target to use (with the default "_blank"). The title of the page is automagically parsed from the source of the linked page using lynx.
" This small function simplifies the addition of links to an html-Page. The
" title of the linked page automagically is requested and added to the output
" The line is added after the current line.
" Author: Gerhard Siegesmund
map <leader>al :call AddLinkToText()<CR>
function! AddLinkToText()
let url = input("URL to add? ", "")
if strlen(url) == 0
return
endif
" Save b register
let saveB = @b
" Get the target
let target = input("Target for this link? ", "_blank")
if strlen(target) > ""
let target = " target=\"" . target . "\""
endif
" Get the source of the page
let code = system("lynx -dump -source " . url)
" Find the title of the page
let title = substitute(code, '\c.*head.*<title[^>]*>\(.*\)<\/title>.*head.*', '\1', '')
if title == code
" If nothing changed we couldn't find the regular expression
let title = "Unknown"
endif
" Remove newline-characters (not yet tested!)
let title = substitute(title, "\n", " ", "g")
" Output the code
let @b = "<a href=\"" . url . "\"" . target . ">" . title . "</a>"
put b
" Restore b register
let @b = saveB
endfunction
