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