summaryrefslogtreecommitdiff
path: root/src/selection.cc
blob: baab004d3c16238c828f0569a30252b7552eb71b (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
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
#include "selection.hh"

#include "utf8.hh"

namespace Kakoune
{

Selection::Selection(const BufferIterator& first, const BufferIterator& last)
    : m_first(first), m_last(last)
{
    check_invariant();
    register_with_buffer();
}

Selection::Selection(const Selection& other)
    : m_first(other.m_first), m_last(other.m_last)
{
   register_with_buffer();
}

Selection::~Selection()
{
   unregister_with_buffer();
}

Selection& Selection::operator=(const Selection& other)
{
   const bool new_buffer = &m_first.buffer() != &other.m_first.buffer();
   if (new_buffer)
       unregister_with_buffer();

   m_first    = other.m_first;
   m_last     = other.m_last;

   if (new_buffer)
       register_with_buffer();

   return *this;
}

BufferIterator Selection::begin() const
{
    return std::min(m_first, m_last);
}

BufferIterator Selection::end() const
{
    return utf8::next(std::max(m_first, m_last));
}

void Selection::merge_with(const Selection& selection)
{
    if (m_first < m_last)
        m_first = std::min(m_first, selection.m_first);
    if (m_first > m_last)
        m_first = std::max(m_first, selection.m_first);
    m_last = selection.m_last;
}

static void avoid_eol(BufferIterator& it)
{
    const auto column = it.column();
    if (column != 0 and column == it.buffer().line_length(it.line()) - 1)
        it = utf8::previous(it);
}

void Selection::avoid_eol()
{
    Kakoune::avoid_eol(m_first);
    Kakoune::avoid_eol(m_last);
}

void Selection::on_insert(const BufferIterator& begin, const BufferIterator& end)
{
    m_first.on_insert(begin.coord(), end.coord());
    m_last.on_insert(begin.coord(), end.coord());
    check_invariant();
}

void Selection::on_erase(const BufferIterator& begin, const BufferIterator& end)
{
    m_first.on_erase(begin.coord(), end.coord());
    m_last.on_erase(begin.coord(), end.coord());
    check_invariant();
}

void Selection::register_with_buffer()
{
    Buffer& buffer = const_cast<Buffer&>(m_first.buffer());
    buffer.add_change_listener(*this);
}

void Selection::unregister_with_buffer()
{
    Buffer& buffer = const_cast<Buffer&>(m_first.buffer());
    buffer.remove_change_listener(*this);
}

void Selection::check_invariant() const
{
    assert(utf8::is_character_start(m_first));
    assert(utf8::is_character_start(m_last));
}

}