#!/usr/bin/env ruby
#
# openurls - opens URLs embedded in STDIN (for use in vim by select/run text)
#
# for use in vim:
#   `nnoremap gx :execute '!echo ' . shellescape(getline('.'), 1) . "\| openurls &"<CR><CR>`
#   `:'<,'>!openurls`

require 'uri'

input = $stdin.read.split("\n")

# the closing parenthesis character might or might not be valid, but we remove
# it if it's the end since it might be part of a URL specified in Markdown like
# this "[label](url)" or "[label](url),"
urls = input.map do |line|
  # URI.extract(line, ['http', 'https'])
  URI.extract(line, %w[http https])
end.flatten.map { |e| e.chomp('.').chomp(',').chomp(')') }

urls.each do |each|
  `open "#{each}"`
end
# echo the input so we can run this in vim and the original text will be there
puts input
