Advertisement
Guest User

Untitled

a guest
Jul 10th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/cjs
  2.  
  3. const Clutter = imports.gi.Clutter;
  4. const Gio = imports.gi.Gio;
  5. const GLib = imports.gi.GLib;
  6. const Lang = imports.lang;
  7. const Mainloop = imports.mainloop;
  8.  
  9. function completeCommand(text) {
  10.     // Replace an escaped space "\ " with a random unicode character, find the
  11.     // last space, and then restore "\ " since we don't want to split at escaped strings
  12.     let last = text.replace(/\\ /g, '\uf001').match(/[^ ]*$/)[0].replace(/\uf001/g, '\\ ');
  13.     if (last.length == 0)
  14.         return ["",[]];
  15.  
  16.     let last_path = last.replace(/[^/]*$/, "");
  17.     let paths = [];
  18.     if (last.charAt(0) == '/') {
  19.         // Match absolute path
  20.         paths = [last_path];
  21.     } else if (last.length != text.length) {
  22.         // Match filename in home directory
  23.         paths = [GLib.build_filenamev([GLib.get_home_dir(), last_path])];
  24.     } else {
  25.         // Match file in path or home directory
  26.         paths = GLib.getenv('PATH').split(':');
  27.         paths.push(GLib.get_home_dir());
  28.         paths = paths.map(x => GLib.build_filenamev([x, last_path]));
  29.     }
  30.  
  31.     let results = [];
  32.     paths.forEach(function(path) {
  33.         try {
  34.             let file = Gio.File.new_for_path(path);
  35.             let fileEnum = file.enumerate_children('standard::name,standard::type', Gio.FileQueryInfoFlags.NONE, null);
  36.             let info;
  37.  
  38.             while ((info = fileEnum.next_file(null))) {
  39.                 let name = last_path + info.get_name();
  40.                 // Escape strings
  41.                 name = name.replace(/ /g, "\\ ")
  42.  
  43.                 if (info.get_file_type() == Gio.FileType.DIRECTORY)
  44.                     name += "/";
  45.                 else
  46.                     name += " ";
  47.  
  48.                 if (name.slice(0, last.length) == last)
  49.                     results.push(name);
  50.             }
  51.         } catch (e) {
  52.         }
  53.     });
  54.  
  55.     if (results.length == 0) return ["", []];
  56.  
  57.     let common = results.reduce(function(s1, s2) {
  58.         let k = last.length;
  59.         let max = Math.min(s1.length, s2.length);
  60.  
  61.         while (k < max && s1[k] == s2[k]) k++;
  62.  
  63.         return s1.substr(0, k);
  64.     });
  65.  
  66.     return [common.substring(last.length, common.length), results.map(x => x.substring(last.length, x.length))];
  67. }
  68.  
  69. print(completeCommand("gnome-"))
  70. print(completeCommand("gnome-"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement