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