]> git.decadent.org.uk Git - ion3.git/blob - mod_query/mod_query.lua
[svn-upgrade] Integrating new upstream version, ion3 (20071109)
[ion3.git] / mod_query / mod_query.lua
1 --
2 -- ion/query/mod_query.lua -- Some common queries for Ion
3 -- 
4 -- Copyright (c) Tuomo Valkonen 2004-2007.
5 -- 
6 -- See the included file LICENSE for details.
7 --
8
9
10 -- This is a slight abuse of the package.loaded variable perhaps, but
11 -- library-like packages should handle checking if they're loaded instead of
12 -- confusing the user with require/include differences.
13 if package.loaded["mod_query"] then return end
14
15 if not ioncore.load_module("mod_query") then
16     return
17 end
18
19 local mod_query=_G["mod_query"]
20
21 assert(mod_query)
22
23
24 local DIE_TIMEOUT_ERRORCODE=10 -- 10 seconds
25 local DIE_TIMEOUT_NO_ERRORCODE=2 -- 2 seconds
26
27
28 -- Generic helper functions {{{
29
30
31 --DOC
32 -- Display an error message box in the multiplexer \var{mplex}.
33 function mod_query.warn(mplex, str)
34     ioncore.unsqueeze(mod_query.do_warn(mplex, str))
35 end
36
37
38 --DOC
39 -- Display a message in \var{mplex}.
40 function mod_query.message(mplex, str)
41     ioncore.unsqueeze(mod_query.do_message(mplex, str))
42 end
43
44
45 --DOC
46 -- Low-level query routine. \var{mplex} is the \type{WMPlex} to display
47 -- the query in, \var{prompt} the prompt string, and \var{initvalue}
48 -- the initial contents of the query box. \var{handler} is a function
49 -- that receives (\var{mplex}, result string) as parameter when the
50 -- query has been succesfully completed, \var{completor} the completor
51 -- routine which receives a (\var{cp}, \var{str}, \var{point}) as parameters.
52 -- The parameter \var{str} is the string to be completed and \var{point}
53 -- cursor's location within it. Completions should be eventually,
54 -- possibly asynchronously, set with \fnref{WComplProxy.set_completions} 
55 -- on \var{cp}.
56 function mod_query.query(mplex, prompt, initvalue, handler, completor,
57                          context)
58     local function handle_it(str)
59         handler(mplex, str)
60     end
61     local function cycle(wedln)
62         wedln:complete('next', 'normal')
63     end
64     local function bcycle(wedln)
65         wedln:complete('prev', 'normal')
66     end
67
68     -- Check that no other queries are open in the mplex.
69     local ok=mplex:managed_i(function(r) 
70                                  return not obj_is(r, "WEdln") 
71                              end)
72     if not ok then
73         return
74     end
75     
76     local wedln=mod_query.do_query(mplex, prompt, initvalue, 
77                                    handle_it, completor, cycle, bcycle)
78                                    
79     if wedln then
80         ioncore.unsqueeze(wedln)
81         
82         if context then
83             wedln:set_context(context)
84         end
85     end
86     
87     return wedln
88 end
89
90
91 --DOC
92 -- This function query will display a query with prompt \var{prompt} in
93 -- \var{mplex} and if the user answers affirmately, call \var{handler}
94 -- with \var{mplex} as parameter.
95 function mod_query.query_yesno(mplex, prompt, handler)
96     local function handler_yesno(mplex, str)
97         if str=="y" or str=="Y" or str=="yes" then
98             handler(mplex)
99         end
100     end
101     return mod_query.query(mplex, prompt, nil, handler_yesno, nil,
102                            "yesno")
103 end
104
105
106 local errdata={}
107
108 local function maybe_finish(pid)
109     local t=errdata[pid]
110
111     if t and t.closed and t.dietime then
112         errdata[pid]=nil
113         local tmd=os.difftime(t.dietime, t.starttime)
114         --if tmd<DIE_TIMEOUT_ERRORCODE and t.signaled then
115         --    local msg=TR("Program received signal ")..t.termsig.."\n"
116         --    mod_query.warn(t.mplex, msg..(t.errs or ""))
117         --else
118         if ((tmd<DIE_TIMEOUT_ERRORCODE and (t.hadcode or t.signaled)) or
119                 (tmd<DIE_TIMEOUT_NO_ERRORCODE)) and t.errs then
120             mod_query.warn(t.mplex, t.errs)
121         end
122     end
123 end
124
125
126 local badsig_={4, 5, 6, 7, 8, 11}
127 local badsig={}
128 for _, v in pairs(badsig_) do 
129     badsig[v]=true 
130 end
131
132 local function chld_handler(p)
133     local t=errdata[p.pid]
134     if t then
135         t.dietime=os.time()
136         t.signaled=(p.signaled and badsig[p.termsig])
137         t.termsig=p.termsig
138         t.hadcode=(p.exited and p.exitstatus~=0)
139         maybe_finish(pid)
140     end
141 end
142
143 ioncore.get_hook("ioncore_sigchld_hook"):add(chld_handler)
144
145 function mod_query.exec_on_merr(mplex, cmd)
146     local pid
147     
148     local function monitor(str)
149         if pid then
150             local t=errdata[pid]
151             if t then
152                 if str then
153                     t.errs=(t.errs or "")..str
154                 else
155                     t.closed=true
156                     maybe_finish(pid)
157                 end
158             end
159         end
160     end
161     
162     local function timeout()
163         errdata[pid]=nil
164     end
165     
166     pid=ioncore.exec_on(mplex, cmd, monitor)
167     
168     if pid<=0 then
169         return
170     end
171
172     local tmr=ioncore.create_timer();
173     local tmd=math.max(DIE_TIMEOUT_NO_ERRORCODE, DIE_TIMEOUT_ERRORCODE)
174     local now=os.time()  
175     tmr:set(tmd*1000, timeout)
176     
177     errdata[pid]={tmr=tmr, mplex=mplex, starttime=now}
178 end
179
180
181 function mod_query.file_completor(wedln, str)
182     local ic=ioncore.lookup_script("ion-completefile")
183     if ic then
184         mod_query.popen_completions(wedln,
185                                    ic.." "..string.shell_safe(str))
186     end
187 end
188
189
190 function mod_query.get_initdir(mplex)
191     --if mod_query.last_dir then
192     --    return mod_query.last_dir
193     --end
194     local wd=(ioncore.get_dir_for(mplex) or os.getenv("PWD"))
195     if wd==nil then
196         wd="/"
197     elseif string.sub(wd, -1)~="/" then
198         wd=wd .. "/"
199     end
200     return wd
201 end
202
203
204 function mod_query.query_execfile(mplex, prompt, prog)
205     assert(prog~=nil)
206     local function handle_execwith(mplex, str)
207         mod_query.exec_on_merr(mplex, prog.." "..string.shell_safe(str))
208     end
209     return mod_query.query(mplex, prompt, mod_query.get_initdir(mplex),
210                            handle_execwith, mod_query.file_completor,
211                            "filename")
212 end
213
214
215 function mod_query.query_execwith(mplex, prompt, dflt, prog, completor,
216                                   context, noquote)
217     local function handle_execwith(frame, str)
218         if not str or str=="" then
219             str=dflt
220         end
221         local args=(noquote and str or string.shell_safe(str))
222         mod_query.exec_on_merr(mplex, prog.." "..args)
223     end
224     return mod_query.query(mplex, prompt, nil, handle_execwith, completor,
225                            context)
226 end
227
228
229 -- }}}
230
231
232 -- Completion helpers {{{
233
234 local pipes={}
235
236 mod_query.COLLECT_THRESHOLD=2000
237
238 --DOC
239 -- This function can be used to read completions from an external source.
240 -- The parameter \var{cp} is the completion proxy to be used,
241 -- and the string \var{cmd} the shell command to be executed, in the directory
242 -- \var{wd}. 
243 -- To its stdout, the command should on the first line write the \var{common_beg}
244 -- parameter of \fnref{WComplProxy.set_completions} (which \var{fn} maybe used
245 -- to override) and a single actual completion on each of the successive lines.
246 -- The function \var{reshnd} may be used to override a result table
247 -- building routine.
248 function mod_query.popen_completions(cp, cmd, fn, reshnd, wd)
249     
250     local pst={cp=cp, maybe_stalled=0}
251     
252     if not reshnd then
253         reshnd = function(rs, a)
254                      if not rs.common_beg then
255                          rs.common_beg=a
256                      else
257                          table.insert(rs, a)
258                      end
259                  end
260     end
261
262     local function rcv(str)
263         local data=""
264         local results={}
265         local totallen=0
266         local lines=0
267         
268         while str do
269             if pst.maybe_stalled>=2 then
270                 pipes[rcv]=nil
271                 return
272             end
273             pst.maybe_stalled=0
274             
275             totallen=totallen+string.len(str)
276             if totallen>ioncore.RESULT_DATA_LIMIT then
277                 error(TR("Too much result data"))
278             end
279             
280
281             data=string.gsub(data..str, "([^\n]*)\n", 
282                              function(s) 
283                                  reshnd(results, s) 
284                                  lines=lines+1
285                                  return ""
286                              end)
287             
288             if lines>mod_query.COLLECT_THRESHOLD then
289                 collectgarbage()
290                 lines=0
291             end
292             
293             str=coroutine.yield()
294         end
295         
296         if not results.common_beg then
297             results.common_beg=beg
298         end
299         
300         (fn or WComplProxy.set_completions)(cp, results)
301         
302         pipes[rcv]=nil
303         results={}
304         
305         collectgarbage()
306     end
307     
308     local found_clean=false
309     
310     for k, v in pairs(pipes) do
311         if v.cp==cp then
312             if v.maybe_stalled<2 then
313                 v.maybe_stalled=v.maybe_stalled+1
314                 found_clean=true
315             end
316         end
317     end
318     
319     if not found_clean then
320         pipes[rcv]=pst
321         ioncore.popen_bgread(cmd, coroutine.wrap(rcv), nil, wd)
322     end
323 end
324
325
326 local function mk_completion_test(str, sub_ok, casei_ok)
327     if not str then
328         return function(s) return true end
329     end
330     
331     local function mk(str, sub_ok)
332         if sub_ok then
333             return function(s) return string.find(s, str, 1, true) end
334         else
335             local len=string.len(str)
336             return function(s) return string.sub(s, 1, len)==str end
337         end
338     end
339     
340     local casei=(casei_ok and mod_query.get().caseicompl)
341     
342     if not casei then
343         return mk(str, sub_ok)
344     else
345         local fn=mk(string.lower(str), sub_ok)
346         return function(s) return fn(string.lower(s)) end
347     end
348 end
349
350
351 local function mk_completion_add(entries, str, sub_ok, casei_ok)
352     local tst=mk_completion_test(str, sub_ok, casei_ok)
353     
354     return function(s) 
355                if s and tst(s) then
356                    table.insert(entries, s)
357                end
358            end
359 end
360
361
362 function mod_query.complete_keys(list, str, sub_ok, casei_ok)
363     local results={}
364     local test_add=mk_completion_add(results, str, sub_ok, casei_ok)
365     
366     for m, _ in pairs(list) do
367         test_add(m)
368     end
369
370     return results
371 end    
372
373
374 function mod_query.complete_name(str, iter)
375     local sub_ok_first=true
376     local casei_ok=true
377     local entries={}
378     local tst_add=mk_completion_add(entries, str, sub_ok_first, casei_ok)
379     
380     iter(function(reg)
381              tst_add(reg:name())
382              return true
383          end)
384     
385     if #entries==0 and not sub_ok_first then
386         local tst_add2=mk_completion_add(entries, str, true, casei_ok)
387         iter(function(reg)
388                  tst_add2(reg:name())
389                  return true
390              end)
391     end
392     
393     return entries
394 end
395
396
397 function mod_query.make_completor(completefn)
398     local function completor(cp, str, point)
399         cp:set_completions(completefn(str, point))
400     end
401     return completor
402 end
403
404
405 -- }}}
406
407
408 -- Simple queries for internal actions {{{
409
410
411 function mod_query.call_warn(mplex, fn)
412     local err = collect_errors(fn)
413     if err then
414         mod_query.warn(mplex, err)
415     end
416     return err
417 end
418
419
420 function mod_query.complete_clientwin(str)
421     return mod_query.complete_name(str, ioncore.clientwin_i)
422 end
423
424
425 function mod_query.complete_workspace(str)
426     local function iter(fn) 
427         return ioncore.region_i(function(obj)
428                                     return (not obj_is(obj, "WGroupWS")
429                                             or fn(obj))
430                                 end)
431     end
432     return mod_query.complete_name(str, iter)
433 end
434
435
436 function mod_query.complete_region(str)
437     return mod_query.complete_name(str, ioncore.region_i)
438 end
439
440
441 function mod_query.gotoclient_handler(frame, str)
442     local cwin=ioncore.lookup_clientwin(str)
443     
444     if cwin==nil then
445         mod_query.warn(frame, TR("Could not find client window %s.", str))
446     else
447         cwin:goto()
448     end
449 end
450
451
452 function mod_query.attachclient_handler(frame, str)
453     local cwin=ioncore.lookup_clientwin(str)
454     
455     if not cwin then
456         mod_query.warn(frame, TR("Could not find client window %s.", str))
457         return
458     end
459     
460     local reg=cwin:groupleader_of()
461     
462     local function attach()
463         frame:attach(reg, { switchto = true })
464     end
465     
466     if frame:rootwin_of()~=reg:rootwin_of() then
467         mod_query.warn(frame, TR("Cannot attach: different root windows."))
468     elseif reg:manager()==frame then
469         reg:goto()
470     else
471         mod_query.call_warn(frame, attach)
472     end
473 end
474
475
476 function mod_query.workspace_handler(mplex, name)
477     local ws=ioncore.lookup_region(name, "WGroupWS")
478     if ws then
479         ws:goto()
480     else
481         local function create_handler(mplex_, layout)
482             if not layout or layout=="" then
483                 layout="default"
484             end
485             
486             if not ioncore.getlayout(layout) then
487                 mod_query.warn(mplex_, TR("Unknown layout"))
488             else
489                 local scr=mplex:screen_of()
490                 
491                 local function mkws()
492                     local tmpl={
493                         name=(name~="" and name),
494                         switchto=true
495                     } 
496                     if not ioncore.create_ws(scr, tmpl, layout) then
497                         error(TR("Unknown error"))
498                     end
499                 end
500
501                 mod_query.call_warn(mplex, mkws)
502             end
503         end
504
505         local function compl_layout(str)
506             local los=ioncore.getlayout(nil, true)
507             return mod_query.complete_keys(los, str, true, true)
508         end
509         
510         mod_query.query(mplex, TR("New workspace layout (default):"), nil,
511                         create_handler, mod_query.make_completor(compl_layout),
512                         "workspacelayout")
513     end
514 end
515
516
517 --DOC
518 -- This query asks for the name of a client window and switches
519 -- focus to the one entered. It uses the completion function
520 -- \fnref{ioncore.complete_clientwin}.
521 function mod_query.query_gotoclient(mplex)
522     mod_query.query(mplex, TR("Go to window:"), nil,
523                     mod_query.gotoclient_handler,
524                     mod_query.make_completor(mod_query.complete_clientwin),
525                     "windowname")
526 end
527
528 --DOC
529 -- This query asks for the name of a client window and attaches
530 -- it to the frame the query was opened in. It uses the completion
531 -- function \fnref{ioncore.complete_clientwin}.
532 function mod_query.query_attachclient(mplex)
533     mod_query.query(mplex, TR("Attach window:"), nil,
534                     mod_query.attachclient_handler, 
535                     mod_query.make_completor(mod_query.complete_clientwin),
536                     "windowname")
537 end
538
539
540 --DOC
541 -- This query asks for the name of a workspace. If a workspace
542 -- (an object inheriting \type{WGroupWS}) with such a name exists,
543 -- it will be switched to. Otherwise a new workspace with the
544 -- entered name will be created and the user will be queried for
545 -- the type of the workspace.
546 function mod_query.query_workspace(mplex)
547     mod_query.query(mplex, TR("Go to or create workspace:"), nil, 
548                     mod_query.workspace_handler,
549                     mod_query.make_completor(mod_query.complete_workspace),
550                     "workspacename")
551 end
552
553
554 --DOC
555 -- This query asks whether the user wants to exit Ion (no session manager)
556 -- or close the session (running under a session manager that supports such
557 -- requests). If the answer is 'y', 'Y' or 'yes', so will happen.
558 function mod_query.query_shutdown(mplex)
559     mod_query.query_yesno(mplex, TR("Exit Ion/Shutdown session (y/n)?"),
560                          ioncore.shutdown)
561 end
562
563
564 --DOC
565 -- This query asks whether the user wants restart Ioncore.
566 -- If the answer is 'y', 'Y' or 'yes', so will happen.
567 function mod_query.query_restart(mplex)
568     mod_query.query_yesno(mplex, TR("Restart Ion (y/n)?"), ioncore.restart)
569 end
570
571
572 --DOC
573 -- This function asks for a name new for the frame where the query
574 -- was created.
575 function mod_query.query_renameframe(frame)
576     mod_query.query(frame, TR("Frame name:"), frame:name(),
577                     function(frame, str) frame:set_name(str) end,
578                     nil, "framename")
579 end
580
581
582 --DOC
583 -- This function asks for a name new for the workspace \var{ws},
584 -- or the one on which \var{mplex} resides, if it is not set.
585 -- If \var{mplex} is not set, one is looked for.
586 function mod_query.query_renameworkspace(mplex, ws)
587     if not mplex then
588         assert(ws)
589         mplex=ioncore.find_manager(ws, "WMPlex")
590     elseif not ws then
591         assert(mplex)
592         ws=ioncore.find_manager(mplex, "WGroupWS")
593     end
594     
595     assert(mplex and ws)
596     
597     mod_query.query(mplex, TR("Workspace name:"), ws:name(),
598                     function(mplex, str) ws:set_name(str) end,
599                     nil, "framename")
600 end
601
602
603 -- }}}
604
605
606 -- Run/view/edit {{{
607
608
609 --DOC
610 -- Asks for a file to be edited. This script uses 
611 -- \command{run-mailcap --mode=edit} by default, but you may provide an
612 -- alternative script to use. The default prompt is "Edit file:" (translated).
613 function mod_query.query_editfile(mplex, script, prompt)
614     mod_query.query_execfile(mplex, 
615                              prompt or TR("Edit file:"), 
616                              script or "run-mailcap --action=edit")
617 end
618
619
620 --DOC
621 -- Asks for a file to be viewed. This script uses 
622 -- \command{run-mailcap --action=view} by default, but you may provide an
623 -- alternative script to use. The default prompt is "View file:" (translated).
624 function mod_query.query_runfile(mplex, script, prompt)
625     mod_query.query_execfile(mplex, 
626                              prompt or TR("View file:"), 
627                              script or "run-mailcap --action=view")
628
629 end
630
631
632 local function isspace(s)
633     return string.find(s, "^%s*$")~=nil
634 end
635
636
637 local function break_cmdline(str, no_ws)
638     local st, en, beg, rest, ch, rem
639     local res={""}
640
641     local function ins(str)
642         local n=#res
643         if string.find(res[n], "^%s+$") then
644             table.insert(res, str)
645         else
646             res[n]=res[n]..str
647         end
648     end
649
650     local function ins_space(str)
651         local n=#res
652         if no_ws then
653             if res[n]~="" then
654                 table.insert(res, "")
655             end
656         else
657             if isspace(res[n]) then
658                 res[n]=res[n]..str
659             else
660                 table.insert(res, str)
661             end
662         end
663     end
664
665     -- Handle terminal startup syntax
666     st, en, beg, ch, rest=string.find(str, "^(%s*)(:+)(.*)")
667     if beg then
668         if string.len(beg)>0 then
669             ins_space(beg)
670         end
671         ins(ch)
672         ins_space("")
673         str=rest
674     end
675
676     while str~="" do
677         st, en, beg, rest, ch=string.find(str, "^(.-)(([%s'\"\\|])(.*))")
678         if not beg then
679             ins(str)
680             break
681         end
682
683         ins(beg)
684         str=rest
685         
686         local sp=false
687         
688         if ch=="\\" then
689             st, en, beg, rest=string.find(str, "^(\\.)(.*)")
690         elseif ch=='"' then
691             st, en, beg, rest=string.find(str, "^(\".-[^\\]\")(.*)")
692             
693             if not beg then
694                 st, en, beg, rest=string.find(str, "^(\"\")(.*)")
695             end
696         elseif ch=="'" then
697             st, en, beg, rest=string.find(str, "^('.-')(.*)")
698         else
699             if ch=='|' then
700                 ins_space('')
701                 ins(ch)
702             else -- ch==' '
703                 ins_space(ch)
704             end
705             st, en, beg, rest=string.find(str, "^.(%s*)(.*)")
706             assert(beg and rest)
707             ins_space(beg)
708             sp=true
709             str=rest
710         end
711         
712         if not sp then
713             if not beg then
714                 beg=str
715                 rest=""
716             end
717             ins(beg)
718             str=rest
719         end
720     end
721     
722     return res
723 end
724
725
726 local function unquote(str)
727     str=string.gsub(str, "^['\"]", "")
728     str=string.gsub(str, "([^\\])['\"]", "%1")
729     str=string.gsub(str, "\\(.)", "%1")
730     return str
731 end
732
733
734 local function quote(str)
735     return string.gsub(str, "([%(%)\"'\\%*%?%[%]%| ])", "\\%1")
736 end
737
738
739 local function find_point(strs, point)
740     for i, s in ipairs(strs) do
741         point=point-string.len(s)
742         if point<=1 then
743             return i
744         end
745     end
746     return #strs
747 end
748
749
750 function mod_query.exec_completor_(wd, wedln, str, point)
751     local parts=break_cmdline(str)
752     local complidx=find_point(parts, point+1)
753     
754     local s_compl, s_beg, s_end="", "", ""
755     
756     if complidx==1 and string.find(parts[1], "^:+$") then
757         complidx=complidx+1
758     end
759     
760     if string.find(parts[complidx], "[^%s]") then
761         s_compl=unquote(parts[complidx])
762     end
763     
764     for i=1, complidx-1 do
765         s_beg=s_beg..parts[i]
766     end
767     
768     for i=complidx+1, #parts do
769         s_end=s_end..parts[i]
770     end
771     
772     local wp=" "
773     if complidx==1 or (complidx==2 and isspace(parts[1])) then
774         wp=" -wp "
775     elseif string.find(parts[1], "^:+$") then
776         if complidx==2 then
777             wp=" -wp "
778         elseif string.find(parts[2], "^%s*$") then
779             if complidx==3 then
780                 wp=" -wp "
781             end
782         end
783     end
784
785     local function set_fn(cp, res)
786         res=table.map(quote, res)
787         res.common_beg=s_beg..(res.common_beg or "")
788         res.common_end=(res.common_end or "")..s_end
789         cp:set_completions(res)
790     end
791
792     local function filter_fn(res, s)
793         if not res.common_beg then
794             if s=="./" then
795                 res.common_beg=""
796             else
797                 res.common_beg=s
798             end
799         else
800             table.insert(res, s)
801         end
802     end
803     
804     local ic=ioncore.lookup_script("ion-completefile")
805     if ic then
806         mod_query.popen_completions(wedln,
807                                    ic..wp..string.shell_safe(s_compl),
808                                    set_fn, filter_fn, wd)
809     end
810 end
811
812
813 function mod_query.exec_completor(...)
814     mod_query.exec_completor_(nil, ...)
815 end
816
817
818 local cmd_overrides={}
819
820
821 --DOC
822 -- Define a command override for the \fnrefx{mod_query}{query_exec} query.
823 function mod_query.defcmd(cmd, fn)
824     cmd_overrides[cmd]=fn
825 end
826
827
828 function mod_query.exec_handler(mplex, cmdline)
829     local parts=break_cmdline(cmdline, true)
830     local cmd=table.remove(parts, 1)
831     
832     if cmd_overrides[cmd] then
833         cmd_overrides[cmd](mplex, table.map(unquote, parts))
834     elseif cmd~="" then
835         mod_query.exec_on_merr(mplex, cmdline)
836     end
837 end
838
839
840 --DOC
841 -- This function asks for a command to execute with \file{/bin/sh}.
842 -- If the command is prefixed with a colon (':'), the command will
843 -- be run in an XTerm (or other terminal emulator) using the script
844 -- \file{ion-runinxterm}. Two colons ('::') will ask you to press 
845 -- enter after the command has finished.
846 function mod_query.query_exec(mplex)
847     local function compl(...)
848         local wd=ioncore.get_dir_for(mplex)
849         mod_query.exec_completor_(wd, ...)
850     end
851     mod_query.query(mplex, TR("Run:"), nil, mod_query.exec_handler,
852                     compl, "run")
853 end
854
855
856 -- }}}
857
858
859 -- SSH {{{
860
861
862 mod_query.known_hosts={}
863 mod_query.hostnicks={}
864 mod_query.ssh_completions={}
865
866
867 function mod_query.get_known_hosts(mplex)
868     mod_query.known_hosts={}
869     local f
870     local h=os.getenv("HOME")
871     if h then 
872         f=io.open(h.."/.ssh/known_hosts")
873     end
874     if not f then 
875         warn(TR("Failed to open ~/.ssh/known_hosts"))
876         return
877     end
878     for l in f:lines() do
879         local st, en, hostname=string.find(l, "^([^%s,]+)")
880         if hostname then
881             table.insert(mod_query.known_hosts, hostname)
882         end
883     end
884     f:close()
885 end
886
887
888 function mod_query.get_hostnicks(mplex)
889     mod_query.hostnicks={}
890     local f
891     local substr, pat, patterns
892     local h=os.getenv("HOME")
893
894     if h then
895         f=io.open(h.."/.ssh/config")
896     end
897     if not f then
898         warn(TR("Failed to open ~/.ssh/config"))
899         return
900     end
901
902     for l in f:lines() do
903         _, _, substr=string.find(l, "^%s*[hH][oO][sS][tT](.*)")
904         if substr then
905             _, _, pat=string.find(substr, "^%s*[=%s]%s*(%S.*)")
906             if pat then
907                 patterns=pat
908             elseif string.find(substr, "^[nN][aA][mM][eE]")
909                 and patterns then
910                 for s in string.gfind(patterns, "%S+") do
911                     if not string.find(s, "[*?]") then
912                         table.insert(mod_query.hostnicks, s)
913                     end
914                 end
915             end
916         end
917     end
918     f:close()
919 end
920
921
922 function mod_query.complete_ssh(str)
923     local st, en, user, at, host=string.find(str, "^([^@]*)(@?)(.*)$")
924     
925     if string.len(at)==0 and string.len(host)==0 then
926         host = user; user = ""
927     end
928     
929     if at=="@" then 
930         user = user .. at 
931     end
932     
933     local res = {}
934     local tst = mk_completion_test(host, true, false)
935     
936     for _, v in ipairs(mod_query.ssh_completions) do
937         if tst(v) then
938             table.insert(res, user .. v)
939         end
940     end
941     
942     return res
943 end
944
945
946 --DOC
947 -- This query asks for a host to connect to with SSH. 
948 -- Hosts to tab-complete are read from \file{\~{}/.ssh/known\_hosts}.
949 function mod_query.query_ssh(mplex, ssh)
950     mod_query.get_known_hosts(mplex)
951     mod_query.get_hostnicks(mplex)
952
953     for _, v in ipairs(mod_query.known_hosts) do
954         table.insert(mod_query.ssh_completions, v)
955     end
956     for _, v in ipairs(mod_query.hostnicks) do
957         table.insert(mod_query.ssh_completions, v)
958     end
959
960     ssh=(ssh or ":ssh")
961
962     local function handle_exec(mplex, str)
963         if not (str and string.find(str, "[^%s]")) then
964             return
965         end
966         
967         mod_query.exec_on_merr(mplex, ssh.." "..string.shell_safe(str))
968     end
969     
970     return mod_query.query(mplex, TR("SSH to:"), nil, handle_exec,
971                            mod_query.make_completor(mod_query.complete_ssh),
972                            "ssh")
973 end
974
975 -- }}}
976
977
978 -- Man pages {{{{
979
980
981 function mod_query.man_completor(wedln, str)
982     local mc=ioncore.lookup_script("ion-completeman")
983     local icase=(mod_query.get().caseicompl and " -icase" or "")
984     local mid=""
985     if mc then
986         mod_query.popen_completions(wedln, (mc..icase..mid.." -complete "
987                                             ..string.shell_safe(str)))
988     end
989 end
990
991
992 --DOC
993 -- This query asks for a manual page to display. By default it runs the
994 -- \command{man} command in an \command{xterm} using \command{ion-runinxterm},
995 -- but it is possible to pass another program as the \var{prog} argument.
996 function mod_query.query_man(mplex, prog)
997     local dflt=ioncore.progname()
998     mod_query.query_execwith(mplex, TR("Manual page (%s):", dflt), 
999                              dflt, prog or ":man", 
1000                              mod_query.man_completor, "man",
1001                              true --[[ no quoting ]])
1002 end
1003
1004
1005 -- }}}
1006
1007
1008 -- Lua code execution {{{
1009
1010
1011 function mod_query.create_run_env(mplex)
1012     local origenv=getfenv()
1013     local meta={__index=origenv, __newindex=origenv}
1014     local env={
1015         _=mplex, 
1016         _sub=mplex:current(),
1017         print=my_print
1018     }
1019     setmetatable(env, meta)
1020     return env
1021 end
1022
1023 function mod_query.do_handle_lua(mplex, env, code)
1024     local print_res
1025     local function collect_print(...)
1026         local tmp=""
1027         local l=#arg
1028         for i=1,l do
1029             tmp=tmp..tostring(arg[i])..(i==l and "\n" or "\t")
1030         end
1031         print_res=(print_res and print_res..tmp or tmp)
1032     end
1033
1034     local f, err=loadstring(code)
1035     if not f then
1036         mod_query.warn(mplex, err)
1037         return
1038     end
1039     
1040     env.print=collect_print
1041     setfenv(f, env)
1042     
1043     err=collect_errors(f)
1044     if err then
1045         mod_query.warn(mplex, err)
1046     elseif print_res then
1047         mod_query.message(mplex, print_res)
1048     end
1049 end
1050
1051 local function getindex(t)
1052     local mt=getmetatable(t)
1053     if mt then return mt.__index end
1054     return nil
1055 end
1056
1057 function mod_query.do_complete_lua(env, str)
1058     -- Get the variable to complete, including containing tables.
1059     -- This will also match string concatenations and such because
1060     -- Lua's regexps don't support optional subexpressions, but we
1061     -- handle them in the next step.
1062     local comptab=env
1063     local metas=true
1064     local _, _, tocomp=string.find(str, "([%w_.:]*)$")
1065     
1066     -- Descend into tables
1067     if tocomp and string.len(tocomp)>=1 then
1068         for t in string.gfind(tocomp, "([^.:]*)[.:]") do
1069             metas=false
1070             if string.len(t)==0 then
1071                 comptab=env;
1072             elseif comptab then
1073                 if type(comptab[t])=="table" then
1074                     comptab=comptab[t]
1075                 elseif type(comptab[t])=="userdata" then
1076                     comptab=getindex(comptab[t])
1077                     metas=true
1078                 else
1079                     comptab=nil
1080                 end
1081             end
1082         end
1083     end
1084     
1085     if not comptab then return {} end
1086     
1087     local compl={}
1088     
1089     -- Get the actual variable to complete without containing tables
1090     _, _, compl.common_beg, tocomp=string.find(str, "(.-)([%w_]*)$")
1091     
1092     local l=string.len(tocomp)
1093     
1094     local tab=comptab
1095     local seen={}
1096     while true do
1097         if type(tab) == "table" then
1098             for k in pairs(tab) do
1099                 if type(k)=="string" then
1100                     if string.sub(k, 1, l)==tocomp then
1101                         table.insert(compl, k)
1102                     end
1103                 end
1104             end
1105         end
1106
1107         -- We only want to display full list of functions for objects, not 
1108         -- the tables representing the classes.
1109         --if not metas then break end
1110         
1111         seen[tab]=true
1112         tab=getindex(tab)
1113         if not tab or seen[tab] then break end
1114     end
1115     
1116     -- If there was only one completion and it is a string or function,
1117     -- concatenate it with "." or "(", respectively.
1118     if #compl==1 then
1119         if type(comptab[compl[1]])=="table" then
1120             compl[1]=compl[1] .. "."
1121         elseif type(comptab[compl[1]])=="function" then
1122             compl[1]=compl[1] .. "("
1123         end
1124     end
1125     
1126     return compl
1127 end
1128
1129
1130 --DOC
1131 -- This query asks for Lua code to execute. It sets the variable '\var{\_}'
1132 -- in the local environment of the string to point to the mplex where the
1133 -- query was created. It also sets the table \var{arg} in the local
1134 -- environment to \code{\{_, _:current()\}}.
1135 function mod_query.query_lua(mplex)
1136     local env=mod_query.create_run_env(mplex)
1137     
1138     local function complete(cp, code)
1139         cp:set_completions(mod_query.do_complete_lua(env, code))
1140     end
1141     
1142     local function handler(mplex, code)
1143         return mod_query.do_handle_lua(mplex, env, code)
1144     end
1145     
1146     mod_query.query(mplex, TR("Lua code:"), nil, handler, complete, "lua")
1147 end
1148
1149 -- }}}
1150
1151
1152 -- Menu query {{{
1153
1154 --DOC
1155 -- This query can be used to create a query of a defined menu.
1156 function mod_query.query_menu(mplex, sub, themenu, prompt)
1157     if type(sub)=="string" then
1158         -- Backwards compat. shift
1159         prompt=themenu
1160         themenu=sub
1161         sub=nil
1162     end
1163     
1164     local menu=ioncore.evalmenu(themenu, mplex, sub)
1165     local menuname=(type(themenu)=="string" and themenu or "?")
1166     
1167     if not menu then
1168         mod_query.warn(mplex, TR("Unknown menu %s.", tostring(themenu)))
1169         return
1170     end
1171     
1172     if not prompt then
1173         prompt=menuname..":"
1174     else
1175         prompt=TR(prompt)
1176     end
1177
1178     local function xform_name(n, is_submenu)
1179         return string.lower(string.gsub(n, "[-/%s]+", "-"))
1180     end
1181
1182     local function xform_menu(t, m, p)
1183         for _, v in ipairs(m) do
1184             if v.name then
1185                 local is_submenu=v.submenu_fn
1186                 local n=p..xform_name(v.name)
1187                 
1188                 while t[n] or t[n..'/'] do
1189                     n=n.."'"
1190                 end
1191                 
1192                 if is_submenu then
1193                     n=n..'/'
1194                 end
1195                 
1196                 t[n]=v
1197                 
1198                 if is_submenu and not v.noautoexpand then
1199                     local sm=v.submenu_fn()
1200                     if sm then
1201                         xform_menu(t, sm, n)
1202                     else
1203                         ioncore.warn_traced(TR("Missing submenu ")
1204                                             ..(v.name or ""))
1205                     end
1206                 end
1207             end
1208         end
1209         return t
1210     end
1211     
1212     local ntab=xform_menu({}, menu, "")
1213     
1214     local function complete(str)
1215         -- casei_ok false, because everything is already in lower case
1216         return mod_query.complete_keys(ntab, str, true, false)
1217     end
1218     
1219     local function handle(mplex, str)
1220         local e=ntab[str]
1221         if e then
1222             if e.func then
1223                 local err=collect_errors(function() 
1224                                              e.func(mplex, _sub) 
1225                                          end)
1226                 if err then
1227                     mod_query.warn(mplex, err)
1228                 end
1229             elseif e.submenu_fn then
1230                 mod_query.query_menu(mplex, e.submenu_fn(),
1231                                      TR("%s:", e.name))
1232             end
1233         else
1234             mod_query.warn(mplex, TR("No entry '%s'", str))
1235         end
1236     end
1237     
1238     mod_query.query(mplex, prompt, nil, handle, 
1239                     mod_query.make_completor(complete), "menu."..menuname)
1240 end
1241
1242 -- }}}
1243
1244
1245 -- Miscellaneous {{{
1246
1247
1248 --DOC 
1249 -- Display an "About Ion" message in \var{mplex}.
1250 function mod_query.show_about_ion(mplex)
1251     mod_query.message(mplex, ioncore.aboutmsg())
1252 end
1253
1254
1255 --DOC
1256 -- Show information about a region tree 
1257 function mod_query.show_tree(mplex, reg, max_depth)
1258     local function indent(s)
1259         local i="    "
1260         return i..string.gsub(s, "\n", "\n"..i)
1261     end
1262     
1263     local function get_info(reg, indent, d)
1264         if not reg then
1265             return (indent .. "No region")
1266         end
1267         
1268         local function n(s) return (s or "") end
1269
1270         local s=string.format("%s%s \"%s\"", indent, obj_typename(reg),
1271                               n(reg:name()))
1272         indent = indent .. "  "
1273         if obj_is(reg, "WClientWin") then
1274             local i=reg:get_ident()
1275             s=s .. TR("\n%sClass: %s\n%sRole: %s\n%sInstance: %s\n%sXID: 0x%x",
1276                       indent, n(i.class), 
1277                       indent, n(i.role), 
1278                       indent, n(i.instance), 
1279                       indent, reg:xid())
1280         end
1281         
1282         if (not max_depth or max_depth > d) and reg.managed_i then
1283             local first=true
1284             reg:managed_i(function(sub)
1285                               if first then
1286                                   s=s .. "\n" .. indent .. "---"
1287                                   first=false
1288                               end
1289                               s=s .. "\n" .. get_info(sub, indent, d+1)
1290                               return true
1291                           end)
1292         end
1293         
1294         return s
1295     end
1296     
1297     mod_query.message(mplex, get_info(reg, "", 0))
1298 end
1299
1300 -- }}}
1301
1302 -- Load extras
1303 dopath('mod_query_chdir')
1304
1305 -- Mark ourselves loaded.
1306 package.loaded["mod_query"]=true
1307
1308
1309 -- Load configuration file
1310 dopath('cfg_query', true)