Last active
August 29, 2015 13:55
-
-
Save LeEnno/8692434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# SearchLink – Generate Markdown links from web searches without leaving your | |
# editor. | |
# | |
# All tribute to [@ttscoff](http://brettterpstra.com/projects/searchlink/) | |
# | |
# Script is modified to my needs. You may want to explore details (in German) | |
# [here](http://www.ienno.de/search-link-enno-style). | |
# | |
require 'json' | |
require 'cgi' | |
# set to true to force inline links | |
inline = true | |
# adding empty string prevents referencing which would lead to "can't modify frozen string error" | |
input = ENV['KMVAR_param'] + "" | |
# input = input.force_encoding("utf-8") | |
inline = true if input.scan(/\]\(!/).length == 1 | |
def google(terms, define = false) | |
resp = `curl -4 --silent 'ajax.googleapis.com/ajax/services/search/web?v=1.0&q=#{CGI.escape(terms)}&filter=1&rsz=small'`.force_encoding('iso-8859-1').encode('utf-8') | |
json = JSON.parse(resp) | |
if json['responseData'] | |
result = json['responseData']['results'][0] | |
return false if result.nil? | |
output_url = result['unescapedUrl'] | |
if define && output_url =~ /dictionary/ | |
output_title = result['content'].gsub(/<\/?.*?>/,'') | |
else | |
CGI.unescapeHTML result['titleNoFormatting'].encode('iso-8859-1') | |
end | |
return [output_url, output_title] | |
else | |
return false | |
end | |
end | |
links = {} | |
footer = '' | |
highest_marker = 0 | |
input.scan(/\[(\d+)\]: /).each do |match| | |
highest_marker = $1.to_i if $1.to_i > highest_marker | |
end | |
input.gsub!(/\[(.*?)\]\((\!.+?)\)/) do |match| | |
link_text = $1 | |
link_info = $2 | |
search_type = '' | |
search_terms = '' | |
if link_info =~ /\!(.+) "(.*?)"$/ | |
search_type = $1 | |
search_terms = $2 | |
else | |
search_word = link_info.match(/\!(.+)/) | |
search_type = search_word[1] unless search_word.nil? | |
search_terms = link_text | |
end | |
url = false | |
title = false | |
url, title = google(search_terms) | |
if url | |
link_text = title if link_text == '' && title | |
if inline | |
title ? %Q{[#{link_text}](#{url} "#{title}")} : %Q{[#{link_text}](#{url})} | |
else | |
if links.has_key? url | |
marker = links[url].to_i + highest_marker | |
else | |
links[url] = links.length + 1 + highest_marker | |
footer += %Q{\n[#{links[url]}]: #{url}} | |
footer += %Q{ "#{title}"} if title | |
end | |
if title | |
%Q{[#{link_text}][#{links[url]}]} | |
else | |
%Q{[#{link_text}](#{url})} | |
end | |
end | |
else | |
match | |
end | |
end | |
if inline | |
print input | |
else | |
puts input | |
puts footer | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment