-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtext_file.cpp
108 lines (99 loc) · 2.13 KB
/
text_file.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "text_file.hpp"
#include "to_utf16.hpp"
#include "to_utf8.hpp"
#include "cpp_highlighter.hpp"
#include "full_file_name.hpp"
#include <fstream>
#include <algorithm>
static std::string baseName(const std::string &fileName)
{
auto p = fileName.rfind('/');
if (p != std::string::npos)
return std::string{ begin(fileName) + p + 1, end(fileName) };
else
return fileName;
}
static bool isCpp(const std::string &fileName)
{
auto p = fileName.rfind(".");
std::string ext;
if (p != std::string::npos)
ext = fileName.substr(p);
static std::string exts[] = {
".c",
".cpp",
".C",
".cc",
".c++",
".h",
".H",
".hpp",
".h++"
};
return std::find(std::begin(exts), std::end(exts), ext) != std::end(exts);
}
TextFile::TextFile(const std::string &fileName):
fileName_(getFullFileName(fileName))
{
if (!fileName.empty())
setName(toUtf16(baseName(fileName)));
else
setName(L"Untitled");
std::ifstream f(fileName_);
if (f.is_open())
while (!f.eof())
{
std::string line;
std::getline(f, line);
buffer_.push_back(toUtf16(line));
}
else
buffer_.push_back(L"");
if (isCpp(fileName))
highlighter_ = new CppHighlighter(this);
}
std::string TextFile::fileName() const
{
return fileName_;
}
void TextFile::save()
{
if (!fileName_.empty())
saveAs(fileName_);
}
void TextFile::saveAs(const std::string &fileName)
{
fileName_ = fileName;
setName(toUtf16(baseName(fileName)));
std::ofstream f(fileName_);
bool first = true;
for (const auto &l: buffer_)
{
if (first)
first = false;
else
f << std::endl;
f << toUtf8(l);
}
clearModified();
}
std::wstring TextFile::preInsert(Coord &cursor, const std::wstring &value)
{
if (value.size() != 1 || value[0] != '\n')
return value;
else
{
auto &line = (*this)[cursor.y];
std::wstring spaces;
int c = 0;
for (auto ch: line)
if (ch == L' ')
++c;
else
break;
for (size_t x = cursor.x; x < line.size() && line[x] == ' '; ++x, --c);
for (int i = 0; i < c; ++i)
spaces += L' ';
return L'\n' + spaces;
}
}