]> git.lyx.org Git - features.git/blob - src/TexRow.cpp
New LFUN paragraph-goto id_start pos_start id_end pos_end
[features.git] / src / TexRow.cpp
1 /**
2  * \file TexRow.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Matthias Ettrich
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author Guillaume Munch
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Buffer.h"
17 #include "Cursor.h"
18 #include "FuncRequest.h"
19 #include "Paragraph.h"
20 #include "TexRow.h"
21
22 #include "mathed/InsetMath.h"
23
24 #include "support/convert.h"
25 #include "support/debug.h"
26 #include "support/docstring_list.h"
27 #include "support/lassert.h"
28
29 #include <algorithm>
30 #include <iterator>
31 #include <sstream>
32
33 using namespace std;
34
35
36 namespace lyx {
37
38
39 TexString::TexString(docstring s)
40         : str(move(s)), texrow(TexRow())
41 {
42         texrow.setRows(1 + count(str.begin(), str.end(), '\n'));
43 }
44
45
46 TexString::TexString(docstring s, TexRow t)
47         : str(move(s)), texrow(move(t))
48 {
49         validate();
50 }
51
52
53 void TexString::validate()
54 {
55         size_t lines = 1 + count(str.begin(), str.end(), '\n');
56         size_t rows = texrow.rows();
57         bool valid = lines == rows;
58         if (!valid)
59                 LYXERR0("TexString has " << lines << " lines but " << rows << " rows." );
60         // Assert in devel mode.  This is important to catch bugs early, otherwise
61         // they might be hard to notice and find.  Recover gracefully in release
62         // mode.
63         LASSERT(valid, texrow.setRows(lines));
64 }
65
66
67 bool TexRow::RowEntryList::addEntry(RowEntry entry)
68 {
69         if (!entry.is_math) {
70                 if (isNone(text_entry_))
71                         text_entry_ = entry.text;
72                 else if (!v_.empty() && TexRow::sameParOrInsetMath(v_.back(), entry))
73                         return false;
74         }
75         forceAddEntry(entry);
76         return true;
77 }
78
79
80 void TexRow::RowEntryList::forceAddEntry(RowEntry entry)
81 {
82         if (v_.empty() || !(v_.back() == entry))
83                 v_.push_back(entry);
84 }
85
86
87 TextEntry TexRow::RowEntryList::getTextEntry() const
88 {
89         if (!isNone(text_entry_))
90                 return text_entry_;
91         return TexRow::text_none;
92 }
93
94
95 void TexRow::RowEntryList::append(RowEntryList row)
96 {
97         if (isNone(text_entry_))
98                 text_entry_ = row.text_entry_;
99         move(row.begin(), row.end(), back_inserter(v_));
100 }
101
102
103 TexRow::TexRow()
104 {
105         reset();
106 }
107
108
109 TextEntry const TexRow::text_none = { -1, 0 };
110 RowEntry const TexRow::row_none = { false, { TexRow::text_none } };
111
112
113 //static
114 bool TexRow::isNone(TextEntry t)
115 {
116         return t.id < 0;
117 }
118
119
120 //static
121 bool TexRow::isNone(RowEntry r)
122 {
123         return !r.is_math && isNone(r.text);
124 }
125
126
127 void TexRow::reset()
128 {
129         rowlist_.clear();
130         newline();
131 }
132
133
134 TexRow::RowEntryList & TexRow::currentRow()
135 {
136         return rowlist_.back();
137 }
138
139
140 //static
141 RowEntry TexRow::textEntry(int id, pos_type pos)
142 {
143         RowEntry entry;
144         entry.is_math = false;
145         entry.text.pos = pos;
146         entry.text.id = id;
147         return entry;
148 }
149
150
151 //static
152 RowEntry TexRow::mathEntry(uid_type id, idx_type cell)
153 {
154         RowEntry entry;
155         entry.is_math = true;
156         entry.math.cell = cell;
157         entry.math.id = id;
158         return entry;
159 }
160
161
162 bool operator==(RowEntry entry1, RowEntry entry2)
163 {
164         return entry1.is_math == entry2.is_math
165                 && (entry1.is_math
166                     ? (entry1.math.id == entry2.math.id
167                        && entry1.math.cell == entry2.math.cell)
168                     : (entry1.text.id == entry2.text.id
169                        && entry1.text.pos == entry2.text.pos));
170 }
171
172
173 bool TexRow::start(RowEntry entry)
174 {
175         return currentRow().addEntry(entry);
176 }
177
178
179 bool TexRow::start(int id, pos_type pos)
180 {
181         return start(textEntry(id,pos));
182 }
183
184
185 void TexRow::forceStart(int id, pos_type pos)
186 {
187         return currentRow().forceAddEntry(textEntry(id,pos));
188 }
189
190
191 void TexRow::startMath(uid_type id, idx_type cell)
192 {
193         start(mathEntry(id,cell));
194 }
195
196
197 void TexRow::newline()
198 {
199         rowlist_.push_back(RowEntryList());
200 }
201
202
203 void TexRow::newlines(size_t num_lines)
204 {
205         while (num_lines--)
206                 newline();
207 }
208
209
210 void TexRow::append(TexRow other)
211 {
212         RowList::iterator it = other.rowlist_.begin();
213         RowList::iterator const end = other.rowlist_.end();
214         LASSERT(it != end, return);
215         currentRow().append(move(*it++));
216         move(it, end, back_inserter(rowlist_));
217 }
218
219
220 bool TexRow::getIdFromRow(int row, int & id, int & pos) const
221 {
222         LYXERR(Debug::LATEX, "getIdFromRow: row " << row << " requested");
223         TextEntry t = text_none;
224         if (row <= int(rowlist_.size()))
225                 while (row > 0 && isNone(t = rowlist_[row - 1].getTextEntry()))
226                         --row;
227         id = t.id;
228         pos = t.pos;
229         return !isNone(t);
230 }
231
232
233 pair<TextEntry, TextEntry> TexRow::getEntriesFromRow(int const row) const
234 {
235         LYXERR(Debug::LATEX, "getEntriesFromRow: row " << row << " requested");
236         // check bounds for row - 1, our target index
237         if (row <= 0)
238                 return {text_none, text_none};
239         size_t const i = static_cast<size_t>(row - 1);
240         if (i >= rowlist_.size())
241                 return {text_none, text_none};
242         // find the start entry
243         size_t j = i;
244         while (j > 0 && isNone(rowlist_[j].getTextEntry()))
245                 --j;
246         TextEntry start = rowlist_[j].getTextEntry();
247         // find the end entry
248         j = i + 1;
249         while (j < rowlist_.size() && isNone(rowlist_[j].getTextEntry()))
250                 ++j;
251         TextEntry end =
252                 (j < rowlist_.size()) ? rowlist_[j].getTextEntry() : text_none;
253         // The following occurs for a displayed math inset for instance (for good
254         // reasons involving subtleties of the algorithm in getRowFromDocIterator).
255         // We want this inset selected.
256         if (start.id == end.id && start.pos == end.pos)
257                 ++end.pos;
258         return {start, end};
259 }
260
261
262 pair<DocIterator, DocIterator> TexRow::getDocIteratorsFromRow(
263     int const row,
264     Buffer const & buf) const
265 {
266         TextEntry start, end;
267         tie(start,end) = getEntriesFromRow(row);
268         return getDocIteratorsFromEntries(start, end, buf);
269 }
270
271
272 //static
273 pair<DocIterator, DocIterator> TexRow::getDocIteratorsFromEntries(
274             TextEntry start,
275             TextEntry end,
276             Buffer const & buf)
277 {
278         // Finding start
279         DocIterator dit_start = buf.getParFromID(start.id);
280         if (dit_start)
281                 dit_start.pos() = min(start.pos, dit_start.lastpos());
282         // Finding end
283         DocIterator dit_end = buf.getParFromID(end.id);
284         if (dit_end) {
285                 dit_end.pos() = min(end.pos, dit_end.lastpos());
286                 // So far dit_end belongs to the next row. Step backwards.
287                 if (!dit_end.top().at_cell_begin()) {
288                         CursorSlice end_top = dit_end.top();
289                         end_top.backwardPos();
290                         if (dit_start && end_top != dit_start.top())
291                                 dit_end.top() = end_top;
292                 }
293                 dit_end.boundary(true);
294         }
295         return {dit_start, dit_end};
296 }
297
298
299 //static
300 FuncRequest TexRow::goToFunc(TextEntry start, TextEntry end)
301 {
302         return {LFUN_PARAGRAPH_GOTO,
303                         convert<string>(start.id) + " " + convert<string>(start.pos) + " " +
304                         convert<string>(end.id) + " " + convert<string>(end.pos)};
305 }
306
307
308
309 //static
310 RowEntry TexRow::rowEntryFromCursorSlice(CursorSlice const & slice)
311 {
312         RowEntry entry;
313         InsetMath * insetMath = slice.asInsetMath();
314         if (insetMath) {
315                 entry.is_math = 1;
316                 entry.math.id = insetMath->id();
317                 entry.math.cell = slice.idx();
318         } else if (slice.text()) {
319                 entry.is_math = 0;
320                 entry.text.id = slice.paragraph().id();
321                 entry.text.pos = slice.pos();
322         } else
323                 LASSERT(false, return row_none);
324         return entry;
325 }
326
327
328 //static
329 bool TexRow::sameParOrInsetMath(RowEntry entry1, RowEntry entry2)
330 {
331         return entry1.is_math == entry2.is_math
332                 && (entry1.is_math
333                     ? (entry1.math.id == entry2.math.id)
334                     : (entry1.text.id == entry2.text.id));
335 }
336
337
338 //static
339 int TexRow::comparePos(RowEntry entry1, RowEntry entry2)
340 {
341         // assume it is sameParOrInsetMath
342         if (entry1.is_math)
343                 return entry2.math.cell - entry1.math.cell;
344         else
345                 return entry2.text.pos - entry1.text.pos;
346 }
347
348
349 // An iterator on RowList that goes top-down, left-right
350 //
351 // We assume that the end of RowList does not change, which makes things simpler
352 //
353 // Records a pair of iterators on the RowEntryList (row_it_, row_end_) and a
354 // pair of iterators on the current row (it_, it_end_).
355 //
356 // it_ always points to a valid position unless row_it_ == row_end_.
357 //
358 // We could turn this into a proper bidirectional iterator, but we don't need as
359 // much.
360 //
361 class TexRow::RowListIterator
362 {
363 public:
364         RowListIterator(RowList::const_iterator r,
365                         RowList::const_iterator r_end)
366                 : row_it_(r), row_end_(r_end),
367                   it_(r == r_end ? RowEntryList::const_iterator() : r->begin()),
368                   it_end_(r == r_end ? RowEntryList::const_iterator() : r->end())
369         {
370                 normalize();
371         }
372
373
374         RowListIterator() :
375                 row_it_(RowList::const_iterator()),
376                 row_end_(RowList::const_iterator()),
377                 it_(RowEntryList::const_iterator()),
378                 it_end_(RowEntryList::const_iterator()) { }
379
380
381         RowEntry const & operator*()
382         {
383                 return *it_;
384         }
385
386
387         RowListIterator & operator++()
388         {
389                 ++it_;
390                 normalize();
391                 return *this;
392         }
393
394
395         bool atEnd() const
396         {
397                 return row_it_ == row_end_;
398         }
399
400
401         bool operator==(RowListIterator const & a) const
402         {
403                 return row_it_ == a.row_it_ && ((atEnd() && a.atEnd()) || it_ == a.it_);
404         }
405
406
407         bool operator!=(RowListIterator const & a) const { return !operator==(a); }
408
409
410         // Current row.
411         RowList::const_iterator const & row() const
412         {
413                 return row_it_;
414         }
415 private:
416         // ensures that it_ points to a valid value unless row_it_ == row_end_
417         void normalize()
418         {
419                 if (row_it_ == row_end_)
420                         return;
421                 while (it_ == it_end_) {
422                         ++row_it_;
423                         if (row_it_ != row_end_) {
424                                 it_ = row_it_->begin();
425                                 it_end_ = row_it_->end();
426                         } else
427                                 return;
428                 }
429         }
430         //
431         RowList::const_iterator row_it_;
432         //
433         RowList::const_iterator row_end_;
434         //
435         RowEntryList::const_iterator it_;
436         //
437         RowEntryList::const_iterator it_end_;
438 };
439
440
441 TexRow::RowListIterator TexRow::begin() const
442 {
443         return RowListIterator(rowlist_.begin(), rowlist_.end());
444 }
445
446
447 TexRow::RowListIterator TexRow::end() const
448 {
449         return RowListIterator(rowlist_.end(), rowlist_.end());
450 }
451
452
453 pair<int,int> TexRow::rowFromDocIterator(DocIterator const & dit) const
454 {
455         bool beg_found = false;
456         bool end_is_next = true;
457         int end_offset = 1;
458         size_t best_slice = 0;
459         RowEntry best_entry = row_none;
460         size_t const n = dit.depth();
461         // this loop finds a pair (best_beg_row,best_end_row) where best_beg_row is
462         // the first row of the topmost possible CursorSlice, and best_end_row is
463         // the one just before the first row matching the next CursorSlice.
464         RowListIterator const begin = this->begin();//necessary disambiguation
465         RowListIterator const end = this->end();
466         RowListIterator best_beg_entry;
467         //best last entry with same pos as the beg_entry, or first entry with pos
468         //immediately following the beg_entry
469         RowListIterator best_end_entry;
470         RowListIterator it = begin;
471         for (; it != end; ++it) {
472                 // Compute the best end row.
473                 if (beg_found
474                         && (!sameParOrInsetMath(*it, *best_end_entry)
475                                 || comparePos(*it, *best_end_entry) <= 0)
476                         && sameParOrInsetMath(*it, best_entry)) {
477                     switch (comparePos(*it, best_entry)) {
478                         case 0:
479                                 // Either it is the last one that matches pos...
480                                 best_end_entry = it;
481                                 end_is_next = false;
482                                 end_offset = 1;
483                                 break;
484                         case -1: {
485                                 // ...or it is the row preceding the first that matches pos+1
486                                 if (!end_is_next) {
487                                         end_is_next = true;
488                                         if (it.row() != best_end_entry.row())
489                                                 end_offset = 0;
490                                         best_end_entry = it;
491                                 }
492                                 break;
493                         }
494                         }
495                 }
496                 // Compute the best begin row. It is better than the previous one if it
497                 // matches either at a deeper level, or at the same level but not
498                 // before.
499                 for (size_t i = best_slice; i < n; ++i) {
500                         RowEntry entry_i = rowEntryFromCursorSlice(dit[i]);
501                         if (sameParOrInsetMath(*it, entry_i)) {
502                                 if (comparePos(*it, entry_i) >= 0
503                                         && (i > best_slice
504                                                 || !beg_found
505                                                 || !sameParOrInsetMath(*it, *best_beg_entry)
506                                                 || (comparePos(*it, *best_beg_entry) <= 0
507                                                         && comparePos(entry_i, *best_beg_entry) != 0)
508                                                 )
509                                         ) {
510                                         beg_found = true;
511                                         end_is_next = false;
512                                         end_offset = 1;
513                                         best_slice = i;
514                                         best_entry = entry_i;
515                                         best_beg_entry = best_end_entry = it;
516                                 }
517                                 //found CursorSlice
518                                 break;
519                         }
520                 }
521         }
522         if (!beg_found)
523                 return make_pair(-1,-1);
524         int const best_beg_row = distance(rowlist_.begin(),
525                                                                           best_beg_entry.row()) + 1;
526         int const best_end_row = distance(rowlist_.begin(),
527                                                                           best_end_entry.row()) + end_offset;
528         return make_pair(best_beg_row, best_end_row);
529 }
530
531
532 pair<int,int> TexRow::rowFromCursor(Cursor const & cur) const
533 {
534         DocIterator beg = cur.selectionBegin();
535         pair<int,int> beg_rows = rowFromDocIterator(beg);
536         if (cur.selection()) {
537                 DocIterator end = cur.selectionEnd();
538                 if (!cur.selIsMultiCell() && !end.top().at_cell_begin())
539                         end.top().backwardPos();
540                 pair<int,int> end_rows = rowFromDocIterator(end);
541                 return make_pair(min(beg_rows.first, end_rows.first),
542                                  max(beg_rows.second, end_rows.second));
543         } else
544                 return make_pair(beg_rows.first, beg_rows.second);
545 }
546
547
548 size_t TexRow::rows() const
549 {
550         return rowlist_.size();
551 }
552
553
554 void TexRow::setRows(size_t r)
555 {
556         rowlist_.resize(r, RowEntryList());
557 }
558
559
560 // debugging functions
561
562 ///
563 docstring TexRow::asString(RowEntry entry)
564 {
565         odocstringstream os;
566         if (entry.is_math)
567                 os << "(1," << entry.math.id << "," << entry.math.cell << ")";
568         else
569                 os << "(0," << entry.text.id << "," << entry.text.pos << ")";
570         return os.str();
571 }
572
573
574 ///prepends the texrow to the source given by tex, for debugging purpose
575 void TexRow::prepend(docstring_list & tex) const
576 {
577         size_type const prefix_length = 25;
578         if (tex.size() < rowlist_.size())
579                 tex.resize(rowlist_.size());
580         auto it = rowlist_.cbegin();
581         auto const beg = rowlist_.cbegin();
582         auto const end = rowlist_.cend();
583         for (; it < end; ++it) {
584                 docstring entry;
585                 for (RowEntry const & e : *it)
586                         entry += asString(e);
587                 if (entry.length() < prefix_length)
588                         entry = entry + docstring(prefix_length - entry.length(), ' ');
589                 ptrdiff_t i = it - beg;
590                 tex[i] = entry + "  " + tex[i];
591         }
592 }
593
594
595 } // namespace lyx