summaryrefslogtreecommitdiff
path: root/src/completion.cc
blob: 17482d14a78139bc8b695365d718fdaf310a16f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "completion.hh"

#include "buffer_manager.hh"
#include "utils.hh"

#include <dirent.h>
#include <algorithm>

namespace Kakoune
{

CandidateList complete_filename(const std::string& prefix,
                                size_t cursor_pos)
{
    std::string real_prefix = prefix.substr(0, cursor_pos);
    size_t dir_end = real_prefix.find_last_of('/');
    std::string dirname = "./";
    std::string dirprefix;
    std::string fileprefix = real_prefix;

    if (dir_end != std::string::npos)
    {
        dirname = real_prefix.substr(0, dir_end + 1);
        dirprefix = dirname;
        fileprefix = real_prefix.substr(dir_end + 1, std::string::npos);
    }

    auto dir = auto_raii(opendir(dirname.c_str()), closedir);

    CandidateList result;
    if (not dir)
        return result;

    while (dirent* entry = readdir(dir))
    {
        std::string filename = entry->d_name;
        if (filename.empty())
            continue;

        if (filename.substr(0, fileprefix.length()) == fileprefix)
        {
            std::string name = dirprefix + filename;
            if (entry->d_type == DT_DIR)
                name += '/';
            if (fileprefix.length() or filename[0] != '.')
                result.push_back(name);
        }
    }
    std::sort(result.begin(), result.end());
    return result;
}

}