kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

completion.cc (5839B)


      1 #include "completion.hh"
      2 #include "file.hh"
      3 #include "context.hh"
      4 #include "option_types.hh"
      5 #include "option_manager.hh"
      6 #include "regex.hh"
      7 
      8 #if defined(__APPLE__)
      9 #define st_mtim st_mtimespec
     10 #endif
     11 
     12 namespace Kakoune
     13 {
     14 
     15 static CandidateList candidates(ConstArrayView<RankedMatch> matches, StringView dirname)
     16 {
     17     CandidateList res;
     18     res.reserve(matches.size());
     19     for (auto& match : matches)
     20         res.push_back(dirname + match.candidate());
     21     return res;
     22 }
     23 
     24 CandidateList complete_filename(StringView prefix, const Regex& ignored_regex,
     25                                 ByteCount cursor_pos, FilenameFlags flags)
     26 {
     27     prefix = prefix.substr(0, cursor_pos);
     28     auto [dirname, fileprefix] = split_path(prefix);
     29     auto parsed_dirname = parse_filename(dirname);
     30 
     31     Optional<ThreadedRegexVM<const char*, RegexMode::Forward | RegexMode::AnyMatch | RegexMode::NoSaves>> vm;
     32     if (not ignored_regex.empty())
     33     {
     34         vm.emplace(*ignored_regex.impl());
     35         if (vm->exec(fileprefix.begin(), fileprefix.end(), fileprefix.begin(), fileprefix.end(), RegexExecFlags::None))
     36             vm.reset();
     37     }
     38 
     39     const bool only_dirs = (flags & FilenameFlags::OnlyDirectories);
     40 
     41     Vector<String> files;
     42     list_files(parsed_dirname, [&](StringView filename, const struct stat& st) {
     43         if ((not vm or not vm->exec(filename.begin(), filename.end(),
     44                                     filename.begin(), filename.end(),
     45                                     RegexExecFlags::None)) and
     46                (not only_dirs or S_ISDIR(st.st_mode)))
     47             files.push_back(filename.str());
     48     });
     49     Vector<RankedMatch> matches;
     50     for (auto& file : files)
     51     {
     52         if (RankedMatch match{file, fileprefix})
     53             matches.push_back(match);
     54     }
     55     // Hack: when completing directories, also echo back the query if it
     56     // is a valid directory. This enables menu completion to select the
     57     // directory instead of a child.
     58     if (only_dirs and not dirname.empty() and dirname.back() == '/' and fileprefix.empty()
     59         and /* exists on disk */ not files.empty())
     60     {
     61         matches.push_back(RankedMatch{fileprefix, fileprefix});
     62     }
     63     std::sort(matches.begin(), matches.end());
     64     const bool expand = (flags & FilenameFlags::Expand);
     65     return candidates(matches, expand ? parsed_dirname : dirname);
     66 }
     67 
     68 CandidateList complete_command(StringView prefix, ByteCount cursor_pos)
     69 {
     70     String real_prefix = parse_filename(prefix.substr(0, cursor_pos));
     71     auto [dirname, fileprefix] = split_path(real_prefix);
     72 
     73     if (not dirname.empty())
     74     {
     75         Vector<String> files;
     76         list_files(dirname, [&](StringView filename, const struct stat& st) {
     77             bool executable = st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH);
     78             if (S_ISDIR(st.st_mode) or (S_ISREG(st.st_mode) and executable))
     79                 files.push_back(filename.str());
     80         });
     81         Vector<RankedMatch> matches;
     82         for (auto& file : files)
     83         {
     84             if (RankedMatch match{file, fileprefix})
     85                 matches.push_back(match);
     86         }
     87         std::sort(matches.begin(), matches.end());
     88         return candidates(matches, dirname);
     89     }
     90 
     91     using TimeSpec = decltype(stat::st_mtim);
     92 
     93     struct CommandCache
     94     {
     95         TimeSpec mtim = {};
     96         Vector<String, MemoryDomain::Completion> commands;
     97     };
     98     static HashMap<String, CommandCache, MemoryDomain::Completion> command_cache;
     99 
    100     Vector<RankedMatch> matches;
    101     for (auto dir : StringView{getenv("PATH")} | split<StringView>(':'))
    102     {
    103         auto dirname = ((not dir.empty() and dir.back() == '/') ? dir.substr(0, dir.length()-1) : dir).str();
    104 
    105         struct stat st;
    106         if (stat(dirname.c_str(), &st))
    107             continue;
    108 
    109         auto& cache = command_cache[dirname];
    110         if (memcmp(&cache.mtim, &st.st_mtim, sizeof(TimeSpec)) != 0)
    111         {
    112             cache.commands.clear();
    113             list_files(dirname, [&](StringView filename, const struct stat& st) {
    114                 bool executable = st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH);
    115                 if (S_ISREG(st.st_mode) and executable)
    116                     cache.commands.push_back(filename.str());
    117             });
    118             memcpy(&cache.mtim, &st.st_mtim, sizeof(TimeSpec));
    119         }
    120         for (auto& cmd : cache.commands)
    121         {
    122             if (RankedMatch match{cmd, fileprefix})
    123                 matches.push_back(match);
    124         }
    125     }
    126     std::sort(matches.begin(), matches.end());
    127     auto it = std::unique(matches.begin(), matches.end());
    128     matches.erase(it, matches.end());
    129     return candidates(matches, "");
    130 }
    131 
    132 Completions shell_complete(const Context& context, StringView prefix, ByteCount cursor_pos)
    133 {
    134     ByteCount word_start = 0;
    135     ByteCount word_end = 0;
    136 
    137     bool command = true;
    138     const ByteCount len = prefix.length();
    139     for (ByteCount pos = 0; pos < cursor_pos and pos < len;)
    140     {
    141         command = (pos == 0 or prefix[pos-1] == ';' or prefix[pos-1] == '|' or
    142                    (pos > 1 and prefix[pos-1] == '&' and prefix[pos-2] == '&'));
    143         while (pos != len and is_horizontal_blank(prefix[pos]))
    144             ++pos;
    145         word_start = pos;
    146         while (pos != len and not is_horizontal_blank(prefix[pos]))
    147             ++pos;
    148         word_end = pos;
    149     }
    150     Completions completions{word_start, word_end};
    151     if (command)
    152         completions.candidates = complete_command(prefix.substr(word_start, word_end),
    153                                                   cursor_pos - word_start);
    154     else
    155         completions.candidates = complete_filename(prefix.substr(word_start, word_end),
    156                                                    context.options()["ignored_files"].get<Regex>(),
    157                                                    cursor_pos - word_start);
    158     return completions;
    159 }
    160 
    161 }