]> git.lyx.org Git - lyx.git/blob - src/TexRow.cpp
fefbeb630c44567ea93b575cc6968f0e9298d51c
[lyx.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()
253                                       : TextEntry{start.id, -1}; // last position
254         // The following occurs for a displayed math inset for instance (for good
255         // reasons involving subtleties of the algorithm in getRowFromDocIterator).
256         // We want this inset selected.
257         if (start.id == end.id && start.pos == end.pos)
258                 ++end.pos;
259         return {start, end};
260 }
261
262
263 pair<DocIterator, DocIterator> TexRow::getDocIteratorsFromRow(
264     int const row,
265     Buffer const & buf) const
266 {
267         TextEntry start, end;
268         tie(start,end) = getEntriesFromRow(row);
269         return getDocIteratorsFromEntries(start, end, buf);
270 }
271
272
273 //static
274 pair<DocIterator, DocIterator> TexRow::getDocIteratorsFromEntries(
275             TextEntry start,
276             TextEntry end,
277             Buffer const & buf)
278 {
279         auto set_pos = [](DocIterator & dit, pos_type pos) {
280                 dit.pos() = (pos >= 0) ? min(pos, dit.lastpos())
281                                        // negative pos values are counted from the end
282                                        : max(dit.lastpos() + pos + 1, pos_type(0));
283         };
284         // Finding start
285         DocIterator dit_start = buf.getParFromID(start.id);
286         if (dit_start)
287                 set_pos(dit_start, start.pos);
288         // Finding end
289         DocIterator dit_end = buf.getParFromID(end.id);
290         if (dit_end) {
291                 set_pos(dit_end, end.pos);
292                 // Step backwards to prevent selecting the beginning of another
293                 // paragraph.
294                 if (dit_end.pos() == 0 && !dit_end.top().at_cell_begin()) {
295                         CursorSlice end_top = dit_end.top();
296                         end_top.backwardPos();
297                         if (dit_start && end_top != dit_start.top())
298                                 dit_end.top() = end_top;
299                 }
300                 dit_end.boundary(true);
301         }
302         return {dit_start, dit_end};
303 }
304
305
306 //static
307 FuncRequest TexRow::goToFunc(TextEntry start, TextEntry end)
308 {
309         return {LFUN_PARAGRAPH_GOTO,
310                         convert<string>(start.id) + " " + convert<string>(start.pos) + " " +
311                         convert<string>(end.id) + " " + convert<string>(end.pos)};
312 }
313
314
315 //static
316 FuncRequest TexRow::goToFunc(std::pair<TextEntry,TextEntry> entries)
317 {
318         return goToFunc(entries.first, entries.second);
319 }
320
321
322 //static
323 RowEntry TexRow::rowEntryFromCursorSlice(CursorSlice const & slice)
324 {
325         RowEntry entry;
326         InsetMath * insetMath = slice.asInsetMath();
327         if (insetMath) {
328                 entry.is_math = 1;
329                 entry.math.id = insetMath->id();
330                 entry.math.cell = slice.idx();
331         } else if (slice.text()) {
332                 entry.is_math = 0;
333                 entry.text.id = slice.paragraph().id();
334                 entry.text.pos = slice.pos();
335         } else
336                 LASSERT(false, return row_none);
337         return entry;
338 }
339
340
341 //static
342 bool TexRow::sameParOrInsetMath(RowEntry entry1, RowEntry entry2)
343 {
344         return entry1.is_math == entry2.is_math
345                 && (entry1.is_math
346                     ? (entry1.math.id == entry2.math.id)
347                     : (entry1.text.id == entry2.text.id));
348 }
349
350
351 //static
352 int TexRow::comparePos(RowEntry entry1, RowEntry entry2)
353 {
354         // assume it is sameParOrInsetMath
355         if (entry1.is_math)
356                 return entry2.math.cell - entry1.math.cell;
357         else
358                 return entry2.text.pos - entry1.text.pos;
359 }
360
361
362 // An iterator on RowList that goes top-down, left-right
363 //
364 // We assume that the end of RowList does not change, which makes things simpler
365 //
366 // Records a pair of iterators on the RowEntryList (row_it_, row_end_) and a
367 // pair of iterators on the current row (it_, it_end_).
368 //
369 // it_ always points to a valid position unless row_it_ == row_end_.
370 //
371 // We could turn this into a proper bidirectional iterator, but we don't need as
372 // much.
373 //
374 class TexRow::RowListIterator
375 {
376 public:
377         RowListIterator(RowList::const_iterator r,
378                         RowList::const_iterator r_end)
379                 : row_it_(r), row_end_(r_end),
380                   it_(r == r_end ? RowEntryList::const_iterator() : r->begin()),
381                   it_end_(r == r_end ? RowEntryList::const_iterator() : r->end())
382         {
383                 normalize();
384         }
385
386
387         RowListIterator() :
388                 row_it_(RowList::const_iterator()),
389                 row_end_(RowList::const_iterator()),
390                 it_(RowEntryList::const_iterator()),
391                 it_end_(RowEntryList::const_iterator()) { }
392
393
394         RowEntry const & operator*()
395         {
396                 return *it_;
397         }
398
399
400         RowListIterator & operator++()
401         {
402                 ++it_;
403                 normalize();
404                 return *this;
405         }
406
407
408         bool atEnd() const
409         {
410                 return row_it_ == row_end_;
411         }
412
413
414         bool operator==(RowListIterator const & a) const
415         {
416                 return row_it_ == a.row_it_ && ((atEnd() && a.atEnd()) || it_ == a.it_);
417         }
418
419
420         bool operator!=(RowListIterator const & a) const { return !operator==(a); }
421
422
423         // Current row.
424         RowList::const_iterator const & row() const
425         {
426                 return row_it_;
427         }
428 private:
429         // ensures that it_ points to a valid value unless row_it_ == row_end_
430         void normalize()
431         {
432                 if (row_it_ == row_end_)
433                         return;
434                 while (it_ == it_end_) {
435                         ++row_it_;
436                         if (row_it_ != row_end_) {
437                                 it_ = row_it_->begin();
438                                 it_end_ = row_it_->end();
439                         } else
440                                 return;
441                 }
442         }
443         //
444         RowList::const_iterator row_it_;
445         //
446         RowList::const_iterator row_end_;
447         //
448         RowEntryList::const_iterator it_;
449         //
450         RowEntryList::const_iterator it_end_;
451 };
452
453
454 TexRow::RowListIterator TexRow::begin() const
455 {
456         return RowListIterator(rowlist_.begin(), rowlist_.end());
457 }
458
459
460 TexRow::RowListIterator TexRow::end() const
461 {
462         return RowListIterator(rowlist_.end(), rowlist_.end());
463 }
464
465
466 pair<int,int> TexRow::rowFromDocIterator(DocIterator const & dit) const
467 {
468         bool beg_found = false;
469         bool end_is_next = true;
470         int end_offset = 1;
471         size_t best_slice = 0;
472         RowEntry best_entry = row_none;
473         size_t const n = dit.depth();
474         // this loop finds a pair (best_beg_row,best_end_row) where best_beg_row is
475         // the first row of the topmost possible CursorSlice, and best_end_row is
476         // the one just before the first row matching the next CursorSlice.
477         RowListIterator const begin = this->begin();//necessary disambiguation
478         RowListIterator const end = this->end();
479         RowListIterator best_beg_entry;
480         //best last entry with same pos as the beg_entry, or first entry with pos
481         //immediately following the beg_entry
482         RowListIterator best_end_entry;
483         RowListIterator it = begin;
484         for (; it != end; ++it) {
485                 // Compute the best end row.
486                 if (beg_found
487                         && (!sameParOrInsetMath(*it, *best_end_entry)
488                                 || comparePos(*it, *best_end_entry) <= 0)
489                         && sameParOrInsetMath(*it, best_entry)) {
490                     switch (comparePos(*it, best_entry)) {
491                         case 0:
492                                 // Either it is the last one that matches pos...
493                                 best_end_entry = it;
494                                 end_is_next = false;
495                                 end_offset = 1;
496                                 break;
497                         case -1: {
498                                 // ...or it is the row preceding the first that matches pos+1
499                                 if (!end_is_next) {
500                                         end_is_next = true;
501                                         if (it.row() != best_end_entry.row())
502                                                 end_offset = 0;
503                                         best_end_entry = it;
504                                 }
505                                 break;
506                         }
507                         }
508                 }
509                 // Compute the best begin row. It is better than the previous one if it
510                 // matches either at a deeper level, or at the same level but not
511                 // before.
512                 for (size_t i = best_slice; i < n; ++i) {
513                         RowEntry entry_i = rowEntryFromCursorSlice(dit[i]);
514                         if (sameParOrInsetMath(*it, entry_i)) {
515                                 if (comparePos(*it, entry_i) >= 0
516                                         && (i > best_slice
517                                                 || !beg_found
518                                                 || !sameParOrInsetMath(*it, *best_beg_entry)
519                                                 || (comparePos(*it, *best_beg_entry) <= 0
520                                                         && comparePos(entry_i, *best_beg_entry) != 0)
521                                                 )
522                                         ) {
523                                         beg_found = true;
524                                         end_is_next = false;
525                                         end_offset = 1;
526                                         best_slice = i;
527                                         best_entry = entry_i;
528                                         best_beg_entry = best_end_entry = it;
529                                 }
530                                 //found CursorSlice
531                                 break;
532                         }
533                 }
534         }
535         if (!beg_found)
536                 return make_pair(-1,-1);
537         int const best_beg_row = distance(rowlist_.begin(),
538                                                                           best_beg_entry.row()) + 1;
539         int const best_end_row = distance(rowlist_.begin(),
540                                                                           best_end_entry.row()) + end_offset;
541         return make_pair(best_beg_row, best_end_row);
542 }
543
544
545 pair<int,int> TexRow::rowFromCursor(Cursor const & cur) const
546 {
547         DocIterator beg = cur.selectionBegin();
548         pair<int,int> beg_rows = rowFromDocIterator(beg);
549         if (cur.selection()) {
550                 DocIterator end = cur.selectionEnd();
551                 if (!cur.selIsMultiCell() && !end.top().at_cell_begin())
552                         end.top().backwardPos();
553                 pair<int,int> end_rows = rowFromDocIterator(end);
554                 return make_pair(min(beg_rows.first, end_rows.first),
555                                  max(beg_rows.second, end_rows.second));
556         } else
557                 return make_pair(beg_rows.first, beg_rows.second);
558 }
559
560
561 size_t TexRow::rows() const
562 {
563         return rowlist_.size();
564 }
565
566
567 void TexRow::setRows(size_t r)
568 {
569         rowlist_.resize(r, RowEntryList());
570 }
571
572
573 // debugging functions
574
575 ///
576 docstring TexRow::asString(RowEntry entry)
577 {
578         odocstringstream os;
579         if (entry.is_math)
580                 os << "(1," << entry.math.id << "," << entry.math.cell << ")";
581         else
582                 os << "(0," << entry.text.id << "," << entry.text.pos << ")";
583         return os.str();
584 }
585
586
587 ///prepends the texrow to the source given by tex, for debugging purpose
588 void TexRow::prepend(docstring_list & tex) const
589 {
590         size_type const prefix_length = 25;
591         if (tex.size() < rowlist_.size())
592                 tex.resize(rowlist_.size());
593         auto it = rowlist_.cbegin();
594         auto const beg = rowlist_.cbegin();
595         auto const end = rowlist_.cend();
596         for (; it < end; ++it) {
597                 docstring entry;
598                 for (RowEntry const & e : *it)
599                         entry += asString(e);
600                 if (entry.length() < prefix_length)
601                         entry = entry + docstring(prefix_length - entry.length(), ' ');
602                 ptrdiff_t i = it - beg;
603                 tex[i] = entry + "  " + tex[i];
604         }
605 }
606
607
608 } // namespace lyx