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