Kooky wikipedia completion

From awesome

Jump to: navigation, search

[edit] Function code

You will need the lua socket library http://www.tecgraf.puc-rio.br/~diego/professional/luasocket/ and the lua json library http://json.luaforge.net/

 local json = require("json")
 local http = require("socket.http")
 local table = table
 local io = io
 local os = os
 local print = print
 
 function wikipedia(command, cur_pos, ncomp)
   local wstart = 1
   local wend = 1
   local words = {}
   local cword_index = 0
   local cword_start = 0
   local cword_end = 0
   local i = 1
 
   if cur_pos ~= #command + 1 and command:sub(cur_pos, cur_pos) ~= " " then
     return command, cur_pos
   elseif #command == 0 then
     return command, cur_pos
   end
 
   while wend <= #command do
     wend = command:find(" ", wstart)
     if not wend then wend = #command + 1 end
     table.insert(words, command:sub(wstart, wend - 1))
     if cur_pos >= wstart and cur_pos <= wend + 1 then
        cword_start = wstart
        cword_end = wend
        cword_index = i
     end
     wstart = wend + 1
     i = i + 1
   end
   local c, err, h = http.request("http://de.wikipedia.org/w/api.php?action=opensearch&search="..words[cword_index].."&format=json")
   local output = {}
   i = 0
   if c then
     c = json.decode(c)
     for i=2, table.getn(c[2]) do
       local entry = c[2][i]
       if not entry then break end
       table.insert(output, entry)
     end
   else
     print(err)
   end
 
   if #output == 0 then
     return command, cur_pos
   end
   while ncomp > #output do
     ncomp = ncomp - #output
   end
 
   local str = command:sub(1, cword_start - 1) .. output[ncomp] .. command:sub(cword_end)
   cur_pos = cword_end + #output[ncomp] + 1
 
   return str, cur_pos
 end

[edit] Usage

 key({ modkey }, "F7",
       function ()
           awful.prompt.run({ prompt = "Search: " },
           mypromptbox[mouse.screen],
           function(h)
             awful.util.spawn(browser .. " 'http://de.wikipedia.org/w/index.php?title=Spezial:Suche&search=" .. h.."'")
           end, wikipedia,
           awful.util.getdir("cache") .. "/history")
       end),
Personal tools