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