]> git.lyx.org Git - features.git/blob - src/Cursor.cpp
Avoid inserting spurious \text insets in mathed
[features.git] / src / Cursor.cpp
1 /**
2  * \file Cursor.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author Dov Feldstern
9  * \author André Pönitz
10  * \author Stefan Schimanski
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "Buffer.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "Encoding.h"
24 #include "Font.h"
25 #include "FuncCode.h"
26 #include "FuncRequest.h"
27 #include "Language.h"
28 #include "Layout.h"
29 #include "LyXAction.h"
30 #include "LyXRC.h"
31 #include "Paragraph.h"
32 #include "ParIterator.h"
33 #include "Row.h"
34 #include "texstream.h"
35 #include "Text.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
38
39 #include "support/debug.h"
40 #include "support/docstream.h"
41 #include "support/ExceptionMessage.h"
42 #include "support/gettext.h"
43 #include "support/lassert.h"
44
45 #include "insets/InsetTabular.h"
46 #include "insets/InsetText.h"
47
48 #include "mathed/InsetMath.h"
49 #include "mathed/InsetMathBrace.h"
50 #include "mathed/InsetMathEnsureMath.h"
51 #include "mathed/InsetMathScript.h"
52 #include "mathed/MacroTable.h"
53 #include "mathed/MathData.h"
54 #include "mathed/MathFactory.h"
55 #include "mathed/MathMacro.h"
56
57 #include <sstream>
58 #include <limits>
59 #include <map>
60 #include <algorithm>
61
62 using namespace std;
63
64 namespace lyx {
65
66 namespace {
67
68 // Find position closest to (x, y) in cell given by iter.
69 // Used only in mathed
70 DocIterator bruteFind(Cursor const & c, int x, int y)
71 {
72         double best_dist = numeric_limits<double>::max();
73
74         DocIterator result;
75
76         DocIterator it = c;
77         it.pos() = 0;
78         DocIterator et = c;
79         et.pos() = et.lastpos();
80         for (size_t i = 0;; ++i) {
81                 int xo;
82                 int yo;
83                 Inset const * inset = &it.inset();
84                 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
85
86                 // FIXME: in the case where the inset is not in the cache, this
87                 // means that no part of it is visible on screen. In this case
88                 // we don't do elaborate search and we just return the forwarded
89                 // DocIterator at its beginning.
90                 if (!insetCache.has(inset)) {
91                         it.top().pos() = 0;
92                         return it;
93                 }
94
95                 Point const o = insetCache.xy(inset);
96                 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
97                 // Convert to absolute
98                 xo += o.x_;
99                 yo += o.y_;
100                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
101                 // '<=' in order to take the last possible position
102                 // this is important for clicking behind \sum in e.g. '\sum_i a'
103                 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
104                         << " best: " << best_dist);
105                 if (d <= best_dist) {
106                         best_dist = d;
107                         result = it;
108                 }
109                 if (it == et)
110                         break;
111                 it.forwardPos();
112         }
113         return result;
114 }
115
116
117 } // namespace anon
118
119
120 CursorData::CursorData()
121         : DocIterator(), anchor_(),
122           selection_(false), mark_(false), word_selection_(false),
123           current_font(inherit_font),
124           autocorrect_(false), macromode_(false)
125 {}
126
127
128 CursorData::CursorData(Buffer * buffer)
129         : DocIterator(buffer), anchor_(),
130           selection_(false), mark_(false), word_selection_(false),
131           current_font(inherit_font),
132           autocorrect_(false), macromode_(false)
133 {}
134
135
136 CursorData::CursorData(DocIterator const & dit)
137         : DocIterator(dit), anchor_(),
138           selection_(false), mark_(false), word_selection_(false),
139           current_font(inherit_font),
140           autocorrect_(false), macromode_(false)
141 {}
142
143
144
145
146 ostream & operator<<(ostream & os, CursorData const & cur)
147 {
148         os << "\n cursor:                                | anchor:\n";
149         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
150                 os << " " << cur[i] << " | ";
151                 if (i < cur.anchor_.depth())
152                         os << cur.anchor_[i];
153                 else
154                         os << "-------------------------------";
155                 os << "\n";
156         }
157         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
158                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
159         }
160         os << " selection: " << cur.selection_
161 //         << " x_target: " << cur.x_target_
162            << " boundary: " << cur.boundary() << endl;
163         return os;
164 }
165
166
167 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
168 {
169         os.stream() << cur;
170         return os;
171 }
172
173
174 // be careful: this is called from the bv's constructor, too, so
175 // bv functions are not yet available!
176 Cursor::Cursor(BufferView & bv)
177         : CursorData(&bv.buffer()), bv_(&bv),
178           x_target_(-1), textTargetOffset_(0),
179           beforeDispatchPosX_(0), beforeDispatchPosY_(0)
180 {}
181
182
183 void Cursor::reset()
184 {
185         clear();
186         push_back(CursorSlice(buffer()->inset()));
187         anchor_ = doc_iterator_begin(buffer());
188         anchor_.clear();
189         new_word_ = doc_iterator_begin(buffer());
190         new_word_.clear();
191         clearTargetX();
192         selection_ = false;
193         mark_ = false;
194 }
195
196
197 // this (intentionally) does neither touch anchor nor selection status
198 void Cursor::setCursor(DocIterator const & cur)
199 {
200         DocIterator::operator=(cur);
201 }
202
203
204 void Cursor::setCursorToAnchor()
205 {
206         if (selection()) {
207                 DocIterator normal = anchor_;
208                 while (depth() < normal.depth())
209                         normal.pop_back();
210                 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
211                         ++normal.pos();
212                 setCursor(normal);
213         }
214 }
215
216
217 void Cursor::setCursorData(CursorData const & data)
218 {
219         CursorData::operator=(data);
220 }
221
222
223 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
224 {
225         Cursor cur = *this;
226
227         // Try to fix cursor in case it is broken.
228         cur.fixIfBroken();
229
230         // Is this a function that acts on inset at point?
231         Inset * inset = cur.nextInset();
232         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
233             && inset && inset->getStatus(cur, cmd, status))
234                 return true;
235
236         // This is, of course, a mess. Better create a new doc iterator and use
237         // this in Inset::getStatus. This might require an additional
238         // BufferView * arg, though (which should be avoided)
239         //Cursor safe = *this;
240         bool res = false;
241         for ( ; cur.depth(); cur.pop()) {
242                 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
243                 // LASSERT: Is it safe to continue here, or should we return?
244                 LASSERT(cur.idx() <= cur.lastidx(), /**/);
245                 LASSERT(cur.pit() <= cur.lastpit(), /**/);
246                 LASSERT(cur.pos() <= cur.lastpos(), /**/);
247
248                 // The inset's getStatus() will return 'true' if it made
249                 // a definitive decision on whether it want to handle the
250                 // request or not. The result of this decision is put into
251                 // the 'status' parameter.
252                 if (cur.inset().getStatus(cur, cmd, status)) {
253                         res = true;
254                         break;
255                 }
256         }
257         return res;
258 }
259
260
261 void Cursor::saveBeforeDispatchPosXY()
262 {
263         getPos(beforeDispatchPosX_, beforeDispatchPosY_);
264 }
265
266
267 void Cursor::dispatch(FuncRequest const & cmd0)
268 {
269         LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
270         if (empty())
271                 return;
272
273         fixIfBroken();
274         FuncRequest cmd = cmd0;
275         Cursor safe = *this;
276         Cursor old = *this;
277         disp_ = DispatchResult();
278
279         beginUndoGroup();
280
281         // Is this a function that acts on inset at point?
282         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
283             && nextInset()) {
284                 disp_.dispatched(true);
285                 disp_.screenUpdate(Update::FitCursor | Update::Force);
286                 FuncRequest tmpcmd = cmd;
287                 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
288                         << cmd0 << endl << *this);
289                 nextInset()->dispatch(*this, tmpcmd);
290                 if (disp_.dispatched()) {
291                         endUndoGroup();
292                         return;
293                 }
294         }
295
296         // store some values to be used inside of the handlers
297         beforeDispatchCursor_ = *this;
298         for (; depth(); pop(), boundary(false)) {
299                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
300                         << cmd0 << endl << *this);
301
302                 // In any of these cases, the cursor is invalid, and we should
303                 // try to save this document rather than crash.
304                 LBUFERR(pos() <= lastpos());
305                 LBUFERR(idx() <= lastidx());
306                 LBUFERR(pit() <= lastpit());
307
308                 // The common case is 'LFUN handled, need update', so make the
309                 // LFUN handler's life easier by assuming this as default value.
310                 // The handler can reset the update and val flags if necessary.
311                 disp_.screenUpdate(Update::FitCursor | Update::Force);
312                 disp_.dispatched(true);
313                 inset().dispatch(*this, cmd);
314                 if (disp_.dispatched())
315                         break;
316         }
317
318         // it completely to get a 'bomb early' behaviour in case this
319         // object will be used again.
320         if (!disp_.dispatched()) {
321                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
322                 // We might have invalidated the cursor when removing an empty
323                 // paragraph while the cursor could not be moved out the inset
324                 // while we initially thought we could. This might happen when
325                 // a multiline inset becomes an inline inset when the second
326                 // paragraph is removed.
327                 if (safe.pit() > safe.lastpit()) {
328                         safe.pit() = safe.lastpit();
329                         safe.pos() = safe.lastpos();
330                 }
331                 operator=(safe);
332                 disp_.screenUpdate(Update::None);
333                 disp_.dispatched(false);
334         } else {
335                 // restore the previous one because nested Cursor::dispatch calls
336                 // are possible which would change it
337                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
338         }
339         endUndoGroup();
340
341         // NOTE: The code below has been copied to BufferView::dispatch.
342         // If you need to modify this, please update the other one too.
343
344         // notify insets we just left
345         if (*this != old) {
346                 old.beginUndoGroup();
347                 old.fixIfBroken();
348                 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
349                 if (badcursor) {
350                         fixIfBroken();
351                         bv().resetInlineCompletionPos();
352                 }
353                 old.endUndoGroup();
354         }
355 }
356
357
358 DispatchResult const & Cursor::result() const
359 {
360         return disp_;
361 }
362
363
364 BufferView & Cursor::bv() const
365 {
366         LBUFERR(bv_);
367         return *bv_;
368 }
369
370
371 void Cursor::pop()
372 {
373         LBUFERR(depth() >= 1);
374         pop_back();
375 }
376
377
378 void Cursor::push(Inset & p)
379 {
380         push_back(CursorSlice(p));
381         p.setBuffer(*buffer());
382 }
383
384
385 void Cursor::pushBackward(Inset & p)
386 {
387         LASSERT(!empty(), return);
388         //lyxerr << "Entering inset " << t << " front" << endl;
389         push(p);
390         p.idxFirst(*this);
391 }
392
393
394 bool Cursor::popBackward()
395 {
396         LASSERT(!empty(), return false);
397         if (depth() == 1)
398                 return false;
399         pop();
400         return true;
401 }
402
403
404 bool Cursor::popForward()
405 {
406         LASSERT(!empty(), return false);
407         //lyxerr << "Leaving inset from in back" << endl;
408         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
409         if (depth() == 1)
410                 return false;
411         pop();
412         pos() += lastpos() - lp + 1;
413         return true;
414 }
415
416
417 int Cursor::currentMode()
418 {
419         LASSERT(!empty(), return Inset::UNDECIDED_MODE);
420         for (int i = depth() - 1; i >= 0; --i) {
421                 int res = operator[](i).inset().currentMode();
422                 bool locked_mode = operator[](i).inset().lockedMode();
423                 // Also return UNDECIDED_MODE when the mode is locked,
424                 // as in this case it is treated the same as TEXT_MODE
425                 if (res != Inset::UNDECIDED_MODE || locked_mode)
426                         return res;
427         }
428         return Inset::TEXT_MODE;
429 }
430
431
432 bool Cursor::inCoordCache() const
433 {
434         // the root inset is not in cache, but we do not need it.
435         if (depth() == 1)
436                 return true;
437         CoordCache::Insets const & icache = bv_->coordCache().getInsets();
438         for (size_t i = 1 ; i < depth() ; ++i)
439                 if (!icache.has(&(*this)[i].inset()))
440                         return false;
441         return true;
442 }
443
444
445 void Cursor::getPos(int & x, int & y) const
446 {
447         Point p = bv().getPos(*this);
448         x = p.x_;
449         y = p.y_;
450 }
451
452
453 Row const & Cursor::textRow() const
454 {
455         CursorSlice const & cs = innerTextSlice();
456         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
457         return pm.getRow(pos(), boundary());
458 }
459
460
461 void Cursor::resetAnchor()
462 {
463         anchor_ = *this;
464         checkNewWordPosition();
465 }
466
467
468 void Cursor::markNewWordPosition()
469 {
470         if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
471                 FontSpan nw = locateWord(WHOLE_WORD);
472                 if (nw.size() == 1) {
473                         LYXERR(Debug::DEBUG, "start new word: "
474                                 << " par: " << pit()
475                                 << " pos: " << nw.first);
476                         new_word_ = *this;
477                 }
478         }
479 }
480
481
482 void Cursor::clearNewWordPosition()
483 {
484         if (!new_word_.empty()) {
485                 LYXERR(Debug::DEBUG, "clear new word: "
486                         << " par: " << pit()
487                         << " pos: " << pos());
488                 new_word_.resize(0);
489         }
490 }
491
492
493 void Cursor::checkNewWordPosition()
494 {
495         if (!lyxrc.spellcheck_continuously || new_word_.empty())
496                 return ;
497         if (!inTexted())
498                 clearNewWordPosition();
499         else {
500                 // forget the position of the current new word if
501                 // 1) the paragraph changes or
502                 // 2) the count of nested insets changes or
503                 // 3) the cursor pos is out of paragraph bound
504                 if (pit() != new_word_.pit() ||
505                         depth() != new_word_.depth() ||
506                         new_word_.pos() > new_word_.lastpos()) {
507                         clearNewWordPosition();
508                 } else if (new_word_.fixIfBroken())
509                         // 4) or the remembered position was "broken"
510                         clearNewWordPosition();
511                 else {
512                         FontSpan nw = locateWord(WHOLE_WORD);
513                         if (!nw.empty()) {
514                                 FontSpan ow = new_word_.locateWord(WHOLE_WORD);
515                                 if (nw.intersect(ow).empty())
516                                         clearNewWordPosition();
517                                 else
518                                         LYXERR(Debug::DEBUG, "new word: "
519                                                    << " par: " << pit()
520                                                    << " pos: " << nw.first << ".." << nw.last);
521                         } else {
522                                 clearNewWordPosition();
523                         }
524                 }
525         }
526 }
527
528
529 bool Cursor::posBackward()
530 {
531         if (pos() == 0)
532                 return false;
533         --pos();
534         return true;
535 }
536
537
538 bool Cursor::posForward()
539 {
540         if (pos() == lastpos())
541                 return false;
542         ++pos();
543         return true;
544 }
545
546
547 bool Cursor::posVisRight(bool skip_inset)
548 {
549         Cursor new_cur = *this; // where we will move to
550         pos_type left_pos; // position visually left of current cursor
551         pos_type right_pos; // position visually right of current cursor
552
553         getSurroundingPos(left_pos, right_pos);
554
555         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
556
557         // Are we at an inset?
558         new_cur.pos() = right_pos;
559         new_cur.boundary(false);
560         if (!skip_inset &&
561                 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
562                 // we actually move the cursor at the end of this
563                 // function, for now we just keep track of the new
564                 // position in new_cur...
565                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
566         }
567
568         // Are we already at rightmost pos in row?
569         else if (text()->empty() || right_pos == -1) {
570
571                 new_cur = *this;
572                 if (!new_cur.posVisToNewRow(false)) {
573                         LYXERR(Debug::RTL, "not moving!");
574                         return false;
575                 }
576
577                 // we actually move the cursor at the end of this
578                 // function, for now just keep track of the new
579                 // position in new_cur...
580                 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
581                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
582
583         }
584         // normal movement to the right
585         else {
586                 new_cur = *this;
587                 // Recall, if the cursor is at position 'x', that
588                 // means *before* the character at position 'x'. In
589                 // RTL, "before" means "to the right of", in LTR, "to
590                 // the left of". So currently our situation is this:
591                 // the position to our right is 'right_pos' (i.e.,
592                 // we're currently to the left of 'right_pos'). In
593                 // order to move to the right, it depends whether or
594                 // not the character at 'right_pos' is RTL.
595                 bool const new_pos_is_RTL = paragraph().getFontSettings(
596                         buffer()->params(), right_pos).isVisibleRightToLeft();
597                 // If the character at 'right_pos' *is* LTR, then in
598                 // order to move to the right of it, we need to be
599                 // *after* 'right_pos', i.e., move to position
600                 // 'right_pos' + 1.
601                 if (!new_pos_is_RTL) {
602                         new_cur.pos() = right_pos + 1;
603                         // set the boundary to true in two situations:
604                         if (
605                         // 1. if new_pos is now lastpos, and we're in
606                         // an RTL paragraph (this means that we're
607                         // moving right to the end of an LTR chunk
608                         // which is at the end of an RTL paragraph);
609                                 (new_cur.pos() == lastpos()
610                                  && paragraph().isRTL(buffer()->params()))
611                         // 2. if the position *after* right_pos is RTL
612                         // (we want to be *after* right_pos, not
613                         // before right_pos + 1!)
614                                 || paragraph().getFontSettings(buffer()->params(),
615                                                 new_cur.pos()).isVisibleRightToLeft()
616                         )
617                                 new_cur.boundary(true);
618                         else // set the boundary to false
619                                 new_cur.boundary(false);
620                 }
621                 // Otherwise (if the character at position 'right_pos'
622                 // is RTL), then moving to the right of it is as easy
623                 // as setting the new position to 'right_pos'.
624                 else {
625                         new_cur.pos() = right_pos;
626                         new_cur.boundary(false);
627                 }
628
629         }
630
631         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
632
633         if (moved) {
634                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
635                         << (new_cur.boundary() ? " (boundary)" : ""));
636                 *this = new_cur;
637         }
638
639         return moved;
640 }
641
642
643 bool Cursor::posVisLeft(bool skip_inset)
644 {
645         Cursor new_cur = *this; // where we will move to
646         pos_type left_pos; // position visually left of current cursor
647         pos_type right_pos; // position visually right of current cursor
648
649         getSurroundingPos(left_pos, right_pos);
650
651         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
652
653         // Are we at an inset?
654         new_cur.pos() = left_pos;
655         new_cur.boundary(false);
656         if (!skip_inset &&
657                 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
658                 // we actually move the cursor at the end of this
659                 // function, for now we just keep track of the new
660                 // position in new_cur...
661                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
662         }
663
664         // Are we already at leftmost pos in row?
665         else if (text()->empty() || left_pos == -1) {
666
667                 new_cur = *this;
668                 if (!new_cur.posVisToNewRow(true)) {
669                         LYXERR(Debug::RTL, "not moving!");
670                         return false;
671                 }
672
673                 // we actually move the cursor at the end of this
674                 // function, for now just keep track of the new
675                 // position in new_cur...
676                 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
677                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
678
679         }
680         // normal movement to the left
681         else {
682                 new_cur = *this;
683                 // Recall, if the cursor is at position 'x', that
684                 // means *before* the character at position 'x'. In
685                 // RTL, "before" means "to the right of", in LTR, "to
686                 // the left of". So currently our situation is this:
687                 // the position to our left is 'left_pos' (i.e., we're
688                 // currently to the right of 'left_pos'). In order to
689                 // move to the left, it depends whether or not the
690                 // character at 'left_pos' is RTL.
691                 bool const new_pos_is_RTL = paragraph().getFontSettings(
692                         buffer()->params(), left_pos).isVisibleRightToLeft();
693                 // If the character at 'left_pos' *is* RTL, then in
694                 // order to move to the left of it, we need to be
695                 // *after* 'left_pos', i.e., move to position
696                 // 'left_pos' + 1.
697                 if (new_pos_is_RTL) {
698                         new_cur.pos() = left_pos + 1;
699                         // set the boundary to true in two situations:
700                         if (
701                         // 1. if new_pos is now lastpos and we're in
702                         // an LTR paragraph (this means that we're
703                         // moving left to the end of an RTL chunk
704                         // which is at the end of an LTR paragraph);
705                                 (new_cur.pos() == lastpos()
706                                  && !paragraph().isRTL(buffer()->params()))
707                         // 2. if the position *after* left_pos is not
708                         // RTL (we want to be *after* left_pos, not
709                         // before left_pos + 1!)
710                                 || !paragraph().getFontSettings(buffer()->params(),
711                                                 new_cur.pos()).isVisibleRightToLeft()
712                         )
713                                 new_cur.boundary(true);
714                         else // set the boundary to false
715                                 new_cur.boundary(false);
716                 }
717                 // Otherwise (if the character at position 'left_pos'
718                 // is LTR), then moving to the left of it is as easy
719                 // as setting the new position to 'left_pos'.
720                 else {
721                         new_cur.pos() = left_pos;
722                         new_cur.boundary(false);
723                 }
724
725         }
726
727         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
728
729         if (moved) {
730                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
731                         << (new_cur.boundary() ? " (boundary)" : ""));
732                 *this = new_cur;
733         }
734
735         return moved;
736 }
737
738
739 namespace {
740
741 // Return true on success
742 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
743 {
744         if (onleft) {
745                 while (cit != row.begin() && cit->isVirtual())
746                         --cit;
747         } else {
748                 while (cit != row.end() && cit->isVirtual())
749                         ++cit;
750         }
751         return cit != row.end() && !cit->isVirtual();
752 }
753
754 }
755
756 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
757 {
758         // by default, we know nothing.
759         left_pos = -1;
760         right_pos = -1;
761
762         Row const & row = textRow();
763         TextMetrics const & tm = bv_->textMetrics(text());
764         double dummy = 0;
765         Row::const_iterator cit = tm.findRowElement(row, pos(), boundary(), dummy);
766         // Handle the case of empty row
767         if (cit == row.end()) {
768                 if (paragraph().isRTL(buffer()->params()))
769                         right_pos = row.pos();
770                 else
771                         left_pos = row.pos() - 1;
772                 return;
773         }
774
775         // skip virtual elements and exit if no non-virtual one exists
776         if (!findNonVirtual(row, cit, !cit->isRTL()))
777                 return;
778
779         // if the position is at the left side of the element, we have to
780         // look at the previous element
781         if (pos() == cit->left_pos()) {
782                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
783                            << "), AT LEFT of *cit=" << *cit);
784                 // this one is easy (see common case below)
785                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
786                 // at the left of the row
787                 if (cit == row.begin())
788                         return;
789                 --cit;
790                 if (!findNonVirtual(row, cit, true))
791                         return;
792                 // [...[ is the row element, | is cursor position (! with boundary)
793                 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
794                 // ] 2 1] is an rtl row element with pos=1 and endpos=3
795                 //    [ 1 2 [  [|3 4 [ => (2, 3)
796                 // or [ 1 2 [  ]!4 3 ] => (2, 4)
797                 // or ] 2 1 ]  [|3 4 [ => (1, 3)
798                 // or ] 4 3 ]  ]!2 1 ] => (3, 2)
799                 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
800                 // happens with consecutive row of same direction
801                 if (left_pos == right_pos) {
802                         left_pos += cit->isRTL() ? 1 : -1;
803                 }
804         }
805         // same code but with the element at the right
806         else if (pos() == cit->right_pos()) {
807                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
808                            << "), AT RIGHT of *cit=" << *cit);
809                 // this one is easy (see common case below)
810                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
811                 // at the right of the row
812                 if (cit + 1 == row.end())
813                         return;
814                 ++cit;
815                 if (!findNonVirtual(row, cit, false))
816                         return;
817                 //    [ 1 2![  [ 3 4 [ => (2, 3)
818                 // or [ 1 2![  ] 4 3 ] => (2, 4)
819                 // or ] 2 1|]  [ 3 4 [ => (1, 3)
820                 // or ] 4 3|]  ] 2 1 ] => (3, 2)
821                 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
822                 // happens with consecutive row of same direction
823                 if (right_pos == left_pos)
824                         right_pos += cit->isRTL() ? -1 : 1;
825         }
826         // common case: both positions are inside the row element
827         else {
828                 //    [ 1 2|3 [ => (2, 3)
829                 // or ] 3|2 1 ] => (3, 2)
830                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
831                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
832         }
833
834         // Note that debug message does not catch all early returns above
835         LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
836                    << ") => (" << left_pos << ", " << right_pos <<")");
837 }
838
839
840 bool Cursor::posVisToNewRow(bool movingLeft)
841 {
842         Paragraph const & par = paragraph();
843         Buffer const & buf = *buffer();
844         Row const & row = textRow();
845         bool par_is_LTR = !par.isRTL(buf.params());
846
847         // Inside a table, determining whether to move to the next or
848         // previous row should be done based on the table's direction.
849         if (inset().asInsetTabular()) {
850                 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
851                 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
852         }
853
854         // if moving left in an LTR paragraph or moving right in an
855         // RTL one, move to previous row
856         if (par_is_LTR == movingLeft) {
857                 if (row.pos() == 0) { // we're at first row in paragraph
858                         if (pit() == 0) // no previous paragraph! don't move
859                                 return false;
860                         // move to last pos in previous par
861                         --pit();
862                         pos() = lastpos();
863                         boundary(false);
864                 } else { // move to previous row in this par
865                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
866                         boundary(false);
867                 }
868         }
869         // if moving left in an RTL paragraph or moving right in an
870         // LTR one, move to next row
871         else {
872                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
873                         if (pit() == lastpit()) // last paragraph! don't move
874                                 return false;
875                         // move to first row in next par
876                         ++pit();
877                         pos() = 0;
878                         boundary(false);
879                 } else { // move to next row in this par
880                         pos() = row.endpos();
881                         boundary(false);
882                 }
883         }
884
885         // make sure we're at left-/right-most pos in new row
886         posVisToRowExtremity(!movingLeft);
887
888         return true;
889 }
890
891
892 void Cursor::posVisToRowExtremity(bool left)
893 {
894         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
895                 << (boundary() ? 1 : 0));
896
897         TextMetrics const & tm = bv_->textMetrics(text());
898         // Looking for extremities is like clicking on the left or the
899         // right of the row.
900         int x = tm.origin().x_ + (left ? 0 : textRow().width());
901         bool b = false;
902         pos() = tm.getPosNearX(textRow(), x, b);
903         boundary(b);
904
905         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
906                 << (boundary() ? 1 : 0));
907 }
908
909
910 bool Cursor::reverseDirectionNeeded() const
911 {
912         /*
913          * We determine the directions based on the direction of the
914          * bottom() --- i.e., outermost --- paragraph, because that is
915          * the only way to achieve consistency of the arrow's movements
916          * within a paragraph, and thus avoid situations in which the
917          * cursor gets stuck.
918          */
919         return bottom().paragraph().isRTL(bv().buffer().params());
920 }
921
922
923 CursorSlice Cursor::normalAnchor() const
924 {
925         if (!selection())
926                 return top();
927         // LASSERT: There have been several bugs around this code, that seem
928         // to involve failures to reset the anchor. We can at least not crash
929         // in release mode by resetting it ourselves.
930         if (anchor_.depth() < depth()) {
931                 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
932                         << *this);
933                 const_cast<DocIterator &>(anchor_) = *this;
934         }
935
936         CursorSlice normal = anchor_[depth() - 1];
937         if (depth() < anchor_.depth() && top() <= normal) {
938                 // anchor is behind cursor -> move anchor behind the inset
939                 ++normal.pos();
940         }
941         return normal;
942 }
943
944
945 CursorSlice Cursor::selBegin() const
946 {
947         if (!selection())
948                 return top();
949         return normalAnchor() < top() ? normalAnchor() : top();
950 }
951
952
953 CursorSlice Cursor::selEnd() const
954 {
955         if (!selection())
956                 return top();
957         return normalAnchor() > top() ? normalAnchor() : top();
958 }
959
960
961 DocIterator Cursor::selectionBegin() const
962 {
963         if (!selection())
964                 return *this;
965
966         DocIterator di;
967         // FIXME: This is a work-around for the problem that
968         // CursorSlice doesn't keep track of the boundary.
969         if (normalAnchor() == top())
970                 di = anchor_.boundary() > boundary() ? anchor_ : *this;
971         else
972                 di = normalAnchor() < top() ? anchor_ : *this;
973         di.resize(depth());
974         return di;
975 }
976
977
978 DocIterator Cursor::selectionEnd() const
979 {
980         if (!selection())
981                 return *this;
982
983         DocIterator di;
984         // FIXME: This is a work-around for the problem that
985         // CursorSlice doesn't keep track of the boundary.
986         if (normalAnchor() == top())
987                 di = anchor_.boundary() < boundary() ? anchor_ : *this;
988         else
989                 di = normalAnchor() > top() ? anchor_ : *this;
990
991         if (di.depth() > depth()) {
992                 di.resize(depth());
993                 ++di.pos();
994         }
995         return di;
996 }
997
998
999 void Cursor::setSelection()
1000 {
1001         selection(true);
1002         if (idx() == normalAnchor().idx() &&
1003             pit() == normalAnchor().pit() &&
1004             pos() == normalAnchor().pos())
1005                 selection(false);
1006 }
1007
1008
1009 void Cursor::setSelection(DocIterator const & where, int n)
1010 {
1011         setCursor(where);
1012         selection(true);
1013         anchor_ = where;
1014         pos() += n;
1015 }
1016
1017
1018 void Cursor::clearSelection()
1019 {
1020         selection(false);
1021         setWordSelection(false);
1022         setMark(false);
1023         resetAnchor();
1024 }
1025
1026
1027 void Cursor::setTargetX(int x)
1028 {
1029         x_target_ = x;
1030         textTargetOffset_ = 0;
1031 }
1032
1033
1034 int Cursor::x_target() const
1035 {
1036         return x_target_;
1037 }
1038
1039
1040 void Cursor::clearTargetX()
1041 {
1042         x_target_ = -1;
1043         textTargetOffset_ = 0;
1044 }
1045
1046
1047 void Cursor::updateTextTargetOffset()
1048 {
1049         int x;
1050         int y;
1051         getPos(x, y);
1052         textTargetOffset_ = x - x_target_;
1053 }
1054
1055
1056 void Cursor::info(odocstream & os) const
1057 {
1058         for (int i = 1, n = depth(); i < n; ++i) {
1059                 operator[](i).inset().infoize(os);
1060                 os << "  ";
1061         }
1062         if (pos() != 0) {
1063                 Inset const * inset = prevInset();
1064                 // prevInset() can return 0 in certain case.
1065                 if (inset)
1066                         prevInset()->infoize2(os);
1067         }
1068 }
1069
1070
1071 bool Cursor::selHandle(bool sel)
1072 {
1073         //lyxerr << "Cursor::selHandle" << endl;
1074         if (mark())
1075                 sel = true;
1076         if (sel == selection())
1077                 return false;
1078
1079         if (!sel)
1080                 cap::saveSelection(*this);
1081
1082         resetAnchor();
1083         selection(sel);
1084         return true;
1085 }
1086 } // namespace lyx
1087
1088
1089 ///////////////////////////////////////////////////////////////////
1090 //
1091 // FIXME: Look here
1092 // The part below is the non-integrated rest of the original math
1093 // cursor. This should be either generalized for texted or moved
1094 // back to mathed (in most cases to InsetMathNest).
1095 //
1096 ///////////////////////////////////////////////////////////////////
1097
1098 #include "mathed/InsetMathChar.h"
1099 #include "mathed/InsetMathGrid.h"
1100 #include "mathed/InsetMathScript.h"
1101 #include "mathed/InsetMathUnknown.h"
1102 #include "mathed/MathFactory.h"
1103 #include "mathed/MathStream.h"
1104 #include "mathed/MathSupport.h"
1105
1106
1107 namespace lyx {
1108
1109 bool Cursor::isInside(Inset const * p) const
1110 {
1111         for (size_t i = 0; i != depth(); ++i)
1112                 if (&operator[](i).inset() == p)
1113                         return true;
1114         return false;
1115 }
1116
1117
1118 void Cursor::leaveInset(Inset const & inset)
1119 {
1120         for (size_t i = 0; i != depth(); ++i) {
1121                 if (&operator[](i).inset() == &inset) {
1122                         resize(i);
1123                         return;
1124                 }
1125         }
1126 }
1127
1128
1129 bool Cursor::openable(MathAtom const & t) const
1130 {
1131         if (!t->isActive())
1132                 return false;
1133
1134         if (t->lock())
1135                 return false;
1136
1137         if (!selection())
1138                 return true;
1139
1140         // we can't move into anything new during selection
1141         if (depth() >= anchor_.depth())
1142                 return false;
1143         if (t.nucleus() != &anchor_[depth()].inset())
1144                 return false;
1145
1146         return true;
1147 }
1148
1149
1150 void Cursor::setScreenPos(int x, int /*y*/)
1151 {
1152         setTargetX(x);
1153         //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
1154 }
1155
1156
1157
1158 void Cursor::plainErase()
1159 {
1160         cell().erase(pos());
1161 }
1162
1163
1164 void Cursor::markInsert()
1165 {
1166         insert(char_type(0));
1167 }
1168
1169
1170 void Cursor::markErase()
1171 {
1172         cell().erase(pos());
1173 }
1174
1175
1176 void Cursor::plainInsert(MathAtom const & t)
1177 {
1178         cell().insert(pos(), t);
1179         ++pos();
1180         inset().setBuffer(bv_->buffer());
1181         inset().initView();
1182         checkBufferStructure();
1183 }
1184
1185
1186 void Cursor::insert(docstring const & str)
1187 {
1188         for (char_type c : str)
1189                 insert(c);
1190 }
1191
1192
1193 void Cursor::insert(char_type c)
1194 {
1195         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1196         LASSERT(!empty(), return);
1197         if (inMathed()) {
1198                 cap::selClearOrDel(*this);
1199                 insert(new InsetMathChar(c));
1200         } else {
1201                 text()->insertChar(*this, c);
1202         }
1203 }
1204
1205
1206 void Cursor::insert(MathAtom const & t)
1207 {
1208         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1209         macroModeClose();
1210         cap::selClearOrDel(*this);
1211         plainInsert(t);
1212 }
1213
1214
1215 void Cursor::insert(Inset * inset0)
1216 {
1217         LASSERT(inset0, return);
1218         if (inMathed())
1219                 insert(MathAtom(inset0->asInsetMath()));
1220         else {
1221                 text()->insertInset(*this, inset0);
1222                 inset0->setBuffer(bv_->buffer());
1223                 inset0->initView();
1224                 if (inset0->isLabeled())
1225                         forceBufferUpdate();
1226         }
1227 }
1228
1229
1230 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1231 {
1232         MathData ar(buffer());
1233         asArray(t, ar, f);
1234         if (ar.size() == 1 && (enter || selection()))
1235                 niceInsert(ar[0]);
1236         else
1237                 insert(ar);
1238         return ar.size();
1239 }
1240
1241
1242 void Cursor::niceInsert(MathAtom const & t)
1243 {
1244         macroModeClose();
1245         docstring const safe = cap::grabAndEraseSelection(*this);
1246         plainInsert(t);
1247         // If possible, enter the new inset and move the contents of the selection
1248         if (t->isActive()) {
1249                 posBackward();
1250                 // be careful here: don't use 'pushBackward(t)' as this we need to
1251                 // push the clone, not the original
1252                 pushBackward(*nextInset());
1253                 // We may not use niceInsert here (recursion)
1254                 MathData ar(buffer());
1255                 asArray(safe, ar);
1256                 insert(ar);
1257         } else if (t->asMacro() && !safe.empty()) {
1258                 MathData ar(buffer());
1259                 asArray(safe, ar);
1260                 docstring const name = t->asMacro()->name();
1261                 MacroData const * data = buffer()->getMacro(name);
1262                 if (data && data->numargs() - data->optionals() > 0) {
1263                         plainInsert(MathAtom(new InsetMathBrace(ar)));
1264                         posBackward();
1265                 }
1266         }
1267 }
1268
1269
1270 void Cursor::insert(MathData const & ar)
1271 {
1272         macroModeClose();
1273         if (selection())
1274                 cap::eraseSelection(*this);
1275         cell().insert(pos(), ar);
1276         pos() += ar.size();
1277         // FIXME audit setBuffer calls
1278         inset().setBuffer(bv_->buffer());
1279 }
1280
1281
1282 bool Cursor::backspace()
1283 {
1284         if (selection()) {
1285                 cap::eraseSelection(*this);
1286                 return true;
1287         }
1288
1289         if (pos() == 0) {
1290                 // If empty cell, and not part of a big cell
1291                 if (lastpos() == 0 && inset().nargs() == 1) {
1292                         popBackward();
1293                         // Directly delete empty cell: [|[]] => [|]
1294                         if (inMathed()) {
1295                                 plainErase();
1296                                 resetAnchor();
1297                                 return true;
1298                         }
1299                         // [|], can not delete from inside
1300                         return false;
1301                 } else {
1302                         if (inMathed())
1303                                 pullArg();
1304                         else
1305                                 popBackward();
1306                         return true;
1307                 }
1308         }
1309
1310         if (inMacroMode()) {
1311                 InsetMathUnknown * p = activeMacro();
1312                 if (p->name().size() > 1) {
1313                         p->setName(p->name().substr(0, p->name().size() - 1));
1314                         return true;
1315                 }
1316         }
1317
1318         if (pos() != 0 && prevAtom()->nargs() > 0) {
1319                 // let's require two backspaces for 'big stuff' and
1320                 // highlight on the first
1321                 resetAnchor();
1322                 selection(true);
1323                 --pos();
1324         } else {
1325                 --pos();
1326                 plainErase();
1327         }
1328         return true;
1329 }
1330
1331
1332 bool Cursor::erase()
1333 {
1334         if (inMacroMode())
1335                 return true;
1336
1337         if (selection()) {
1338                 cap::eraseSelection(*this);
1339                 return true;
1340         }
1341
1342         // delete empty cells if possible
1343         if (pos() == lastpos() && inset().idxDelete(idx()))
1344                 return true;
1345
1346         // special behaviour when in last position of cell
1347         if (pos() == lastpos()) {
1348                 bool one_cell = inset().nargs() == 1;
1349                 if (one_cell && lastpos() == 0) {
1350                         popBackward();
1351                         // Directly delete empty cell: [|[]] => [|]
1352                         if (inMathed()) {
1353                                 plainErase();
1354                                 resetAnchor();
1355                                 return true;
1356                         }
1357                         // [|], can not delete from inside
1358                         return false;
1359                 }
1360                 // remove markup
1361                 if (!one_cell)
1362                         inset().idxGlue(idx());
1363                 return true;
1364         }
1365
1366         // 'clever' UI hack: only erase large items if previously slected
1367         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1368                 resetAnchor();
1369                 selection(true);
1370                 ++pos();
1371         } else {
1372                 plainErase();
1373         }
1374
1375         return true;
1376 }
1377
1378
1379 bool Cursor::up()
1380 {
1381         macroModeClose();
1382         DocIterator save = *this;
1383         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1384         this->dispatch(cmd);
1385         if (disp_.dispatched())
1386                 return true;
1387         setCursor(save);
1388         return false;
1389 }
1390
1391
1392 bool Cursor::down()
1393 {
1394         macroModeClose();
1395         DocIterator save = *this;
1396         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1397         this->dispatch(cmd);
1398         if (disp_.dispatched())
1399                 return true;
1400         setCursor(save);
1401         return false;
1402 }
1403
1404
1405 bool Cursor::macroModeClose()
1406 {
1407         if (!inMacroMode())
1408                 return false;
1409         InsetMathUnknown * p = activeMacro();
1410         p->finalize();
1411         MathData selection(buffer());
1412         asArray(p->selection(), selection);
1413         docstring const s = p->name();
1414         --pos();
1415         cell().erase(pos());
1416
1417         // do nothing if the macro name is empty
1418         if (s == "\\")
1419                 return false;
1420
1421         // trigger updates of macros, at least, if no full
1422         // updates take place anyway
1423         screenUpdateFlags(Update::Force);
1424
1425         docstring const name = s.substr(1);
1426         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1427         if (in && in->interpretString(*this, s))
1428                 return true;
1429         MathAtom atom = buffer()->getMacro(name, *this, false) ?
1430                 MathAtom(new MathMacro(buffer(), name)) : createInsetMath(name, buffer());
1431
1432         // try to put argument into macro, if we just inserted a macro
1433         bool macroArg = false;
1434         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1435         if (atomAsMacro) {
1436                 // macros here are still unfolded (in init mode in fact). So
1437                 // we have to resolve the macro here manually and check its arity
1438                 // to put the selection behind it if arity > 0.
1439                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1440                 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1441                         macroArg = true;
1442                         atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1443                 } else
1444                         // non-greedy case. Do not touch the arguments behind
1445                         atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1446         }
1447
1448         // insert remembered selection into first argument of a non-macro
1449         else if (atom.nucleus()->nargs() > 0)
1450                 atom.nucleus()->cell(0).append(selection);
1451
1452         MathWordList const & words = mathedWordList();
1453         MathWordList::const_iterator it = words.find(name);
1454         bool keep_mathmode = it != words.end() && (it->second.inset == "font"
1455                                                 || it->second.inset == "oldfont"
1456                                                 || it->second.inset == "mbox");
1457         bool ert_macro = atomAsMacro && !atomAsMacro->macro();
1458
1459         if (in && in->currentMode() == Inset::TEXT_MODE
1460             && atom.nucleus()->currentMode() == Inset::MATH_MODE
1461             && name != from_ascii("ensuremath") && !ert_macro) {
1462                 MathAtom at(new InsetMathEnsureMath(buffer()));
1463                 at.nucleus()->cell(0).push_back(atom);
1464                 niceInsert(at);
1465                 posForward();
1466         } else if (in && in->currentMode() == Inset::MATH_MODE
1467                    && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1468                    && !keep_mathmode) {
1469                 MathAtom at = createInsetMath("text", buffer());
1470                 at.nucleus()->cell(0).push_back(atom);
1471                 niceInsert(at);
1472                 posForward();
1473         } else
1474                 plainInsert(atom);
1475
1476         // finally put the macro argument behind, if needed
1477         if (macroArg) {
1478                 if (selection.size() > 1 || selection[0]->asScriptInset())
1479                         plainInsert(MathAtom(new InsetMathBrace(selection)));
1480                 else
1481                         insert(selection);
1482         }
1483
1484         return true;
1485 }
1486
1487
1488 docstring Cursor::macroName()
1489 {
1490         return inMacroMode() ? activeMacro()->name() : docstring();
1491 }
1492
1493
1494 void Cursor::handleNest(MathAtom const & a, int c)
1495 {
1496         //lyxerr << "Cursor::handleNest: " << c << endl;
1497         MathAtom t = a;
1498         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1499         insert(t);
1500         posBackward();
1501         pushBackward(*nextInset());
1502 }
1503
1504
1505 int Cursor::targetX() const
1506 {
1507         if (x_target() != -1)
1508                 return x_target();
1509         int x = 0;
1510         int y = 0;
1511         getPos(x, y);
1512         return x;
1513 }
1514
1515
1516 int Cursor::textTargetOffset() const
1517 {
1518         return textTargetOffset_;
1519 }
1520
1521
1522 void Cursor::setTargetX()
1523 {
1524         int x;
1525         int y;
1526         getPos(x, y);
1527         setTargetX(x);
1528 }
1529
1530
1531 bool Cursor::inMacroMode() const
1532 {
1533         if (!inMathed())
1534                 return false;
1535         if (pos() == 0 || cell().empty())
1536                 return false;
1537         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1538         return p && !p->final();
1539 }
1540
1541
1542 InsetMathUnknown * Cursor::activeMacro()
1543 {
1544         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1545 }
1546
1547
1548 InsetMathUnknown const * Cursor::activeMacro() const
1549 {
1550         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1551 }
1552
1553
1554 void Cursor::pullArg()
1555 {
1556         // FIXME: Look here
1557         MathData ar = cell();
1558         if (popBackward() && inMathed()) {
1559                 plainErase();
1560                 cell().insert(pos(), ar);
1561                 resetAnchor();
1562         } else {
1563                 //formula()->mutateToText();
1564         }
1565 }
1566
1567
1568 void Cursor::touch()
1569 {
1570         // FIXME: look here
1571 #if 0
1572         DocIterator::const_iterator it = begin();
1573         DocIterator::const_iterator et = end();
1574         for ( ; it != et; ++it)
1575                 it->cell().touch();
1576 #endif
1577 }
1578
1579
1580 void Cursor::normalize()
1581 {
1582         if (idx() > lastidx()) {
1583                 lyxerr << "this should not really happen - 1: "
1584                        << idx() << ' ' << nargs()
1585                        << " in: " << &inset() << endl;
1586                 idx() = lastidx();
1587         }
1588
1589         if (pos() > lastpos()) {
1590                 lyxerr << "this should not really happen - 2: "
1591                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1592                        << " in atom: '";
1593                 odocstringstream os;
1594                 otexrowstream ots(os, false);
1595                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1596                 inset().asInsetMath()->write(wi);
1597                 lyxerr << to_utf8(os.str()) << endl;
1598                 pos() = lastpos();
1599         }
1600 }
1601
1602
1603 bool Cursor::upDownInMath(bool up)
1604 {
1605         // Be warned: The 'logic' implemented in this function is highly
1606         // fragile. A distance of one pixel or a '<' vs '<=' _really
1607         // matters. So fiddle around with it only if you think you know
1608         // what you are doing!
1609         int xo = 0;
1610         int yo = 0;
1611         getPos(xo, yo);
1612         xo = beforeDispatchPosX_;
1613
1614         // check if we had something else in mind, if not, this is the future
1615         // target
1616         if (x_target_ == -1)
1617                 setTargetX(xo);
1618         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1619                 // In text mode inside the line (not left or right) possibly set a new target_x,
1620                 // but only if we are somewhere else than the previous target-offset.
1621
1622                 // We want to keep the x-target on subsequent up/down movements
1623                 // that cross beyond the end of short lines. Thus a special
1624                 // handling when the cursor is at the end of line: Use the new
1625                 // x-target only if the old one was before the end of line
1626                 // or the old one was after the beginning of the line
1627                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1628                 bool left;
1629                 bool right;
1630                 if (inRTL) {
1631                         left = pos() == textRow().endpos();
1632                         right = pos() == textRow().pos();
1633                 } else {
1634                         left = pos() == textRow().pos();
1635                         right = pos() == textRow().endpos();
1636                 }
1637                 if ((!left && !right) ||
1638                                 (left && !right && xo < x_target_) ||
1639                                 (!left && right && x_target_ < xo))
1640                         setTargetX(xo);
1641                 else
1642                         xo = targetX();
1643         } else
1644                 xo = targetX();
1645
1646         // try neigbouring script insets
1647         Cursor old = *this;
1648         if (inMathed() && !selection()) {
1649                 // try left
1650                 if (pos() != 0) {
1651                         InsetMathScript const * p = prevAtom()->asScriptInset();
1652                         if (p && p->has(up)) {
1653                                 --pos();
1654                                 push(*const_cast<InsetMathScript*>(p));
1655                                 idx() = p->idxOfScript(up);
1656                                 pos() = lastpos();
1657
1658                                 // we went in the right direction? Otherwise don't jump into the script
1659                                 int x;
1660                                 int y;
1661                                 getPos(x, y);
1662                                 int oy = beforeDispatchPosY_;
1663                                 if ((!up && y <= oy) ||
1664                                                 (up && y >= oy))
1665                                         operator=(old);
1666                                 else
1667                                         return true;
1668                         }
1669                 }
1670
1671                 // try right
1672                 if (pos() != lastpos()) {
1673                         InsetMathScript const * p = nextAtom()->asScriptInset();
1674                         if (p && p->has(up)) {
1675                                 push(*const_cast<InsetMathScript*>(p));
1676                                 idx() = p->idxOfScript(up);
1677                                 pos() = 0;
1678
1679                                 // we went in the right direction? Otherwise don't jump into the script
1680                                 int x;
1681                                 int y;
1682                                 getPos(x, y);
1683                                 int oy = beforeDispatchPosY_;
1684                                 if ((!up && y <= oy) ||
1685                                                 (up && y >= oy))
1686                                         operator=(old);
1687                                 else
1688                                         return true;
1689                         }
1690                 }
1691         }
1692
1693         // try to find an inset that knows better then we,
1694         if (inset().idxUpDown(*this, up)) {
1695                 //lyxerr << "idxUpDown triggered" << endl;
1696                 // try to find best position within this inset
1697                 if (!selection())
1698                         setCursor(bruteFind(*this, xo, yo));
1699                 return true;
1700         }
1701
1702         // any improvement going just out of inset?
1703         if (popBackward() && inMathed()) {
1704                 //lyxerr << "updown: popBackward succeeded" << endl;
1705                 int xnew;
1706                 int ynew;
1707                 int yold = beforeDispatchPosY_;
1708                 getPos(xnew, ynew);
1709                 if (up ? ynew < yold : ynew > yold)
1710                         return true;
1711         }
1712
1713         // no success, we are probably at the document top or bottom
1714         operator=(old);
1715         return false;
1716 }
1717
1718
1719 bool Cursor::atFirstOrLastRow(bool up)
1720 {
1721         TextMetrics const & tm = bv_->textMetrics(text());
1722         ParagraphMetrics const & pm = tm.parMetrics(pit());
1723
1724         int row;
1725         if (pos() && boundary())
1726                 row = pm.pos2row(pos() - 1);
1727         else
1728                 row = pm.pos2row(pos());
1729
1730         if (up) {
1731                 if (pit() == 0 && row == 0)
1732                         return true;
1733         } else {
1734                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1735                                 row + 1 >= int(pm.rows().size()))
1736                         return true;
1737         }
1738         return false;
1739 }
1740
1741
1742 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1743 {
1744         LASSERT(text(), return false);
1745
1746         // where are we?
1747         int xo = 0;
1748         int yo = 0;
1749         getPos(xo, yo);
1750         xo = beforeDispatchPosX_;
1751
1752         // update the targetX - this is here before the "return false"
1753         // to set a new target which can be used by InsetTexts above
1754         // if we cannot move up/down inside this inset anymore
1755         if (x_target_ == -1)
1756                 setTargetX(xo);
1757         else if (xo - textTargetOffset() != x_target() &&
1758                                          depth() == beforeDispatchCursor_.depth()) {
1759                 // In text mode inside the line (not left or right)
1760                 // possibly set a new target_x, but only if we are
1761                 // somewhere else than the previous target-offset.
1762
1763                 // We want to keep the x-target on subsequent up/down
1764                 // movements that cross beyond the end of short lines.
1765                 // Thus a special handling when the cursor is at the
1766                 // end of line: Use the new x-target only if the old
1767                 // one was before the end of line or the old one was
1768                 // after the beginning of the line
1769                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1770                 bool left;
1771                 bool right;
1772                 if (inRTL) {
1773                         left = pos() == textRow().endpos();
1774                         right = pos() == textRow().pos();
1775                 } else {
1776                         left = pos() == textRow().pos();
1777                         right = pos() == textRow().endpos();
1778                 }
1779                 if ((!left && !right) ||
1780                                 (left && !right && xo < x_target_) ||
1781                                 (!left && right && x_target_ < xo))
1782                         setTargetX(xo);
1783                 else
1784                         xo = targetX();
1785         } else
1786                 xo = targetX();
1787
1788         // first get the current line
1789         TextMetrics & tm = bv_->textMetrics(text());
1790         ParagraphMetrics const & pm = tm.parMetrics(pit());
1791         int row;
1792         if (pos() && boundary())
1793                 row = pm.pos2row(pos() - 1);
1794         else
1795                 row = pm.pos2row(pos());
1796
1797         if (atFirstOrLastRow(up)) {
1798                 // Is there a place for the cursor to go ? If yes, we
1799                 // can execute the DEPM, otherwise we should keep the
1800                 // paragraph to host the cursor.
1801                 Cursor dummy = *this;
1802                 bool valid_destination = false;
1803                 for(; dummy.depth(); dummy.pop())
1804                         if (!dummy.atFirstOrLastRow(up)) {
1805                                 valid_destination = true;
1806                                 break;
1807                         }
1808
1809                 // will a next dispatch follow and if there is a new
1810                 // dispatch will it move the cursor out ?
1811                 if (depth() > 1 && valid_destination) {
1812                         // The cursor hasn't changed yet. This happens when
1813                         // you e.g. move out of an inset. And to give the
1814                         // DEPM the possibility of doing something we must
1815                         // provide it with two different cursors. (Lgb, vfr)
1816                         dummy = *this;
1817                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
1818                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
1819
1820                         updateNeeded |= bv().checkDepm(dummy, *this);
1821                         updateTextTargetOffset();
1822                         if (updateNeeded)
1823                                 forceBufferUpdate();
1824                 }
1825                 return false;
1826         }
1827
1828         // with and without selection are handled differently
1829         if (!selection()) {
1830                 int yo = bv().getPos(*this).y_;
1831                 Cursor old = *this;
1832                 // To next/previous row
1833                 if (up)
1834                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1835                 else
1836                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1837                 clearSelection();
1838
1839                 // This happens when you move out of an inset.
1840                 // And to give the DEPM the possibility of doing
1841                 // something we must provide it with two different
1842                 // cursors. (Lgb)
1843                 Cursor dummy = *this;
1844                 if (dummy == old)
1845                         ++dummy.pos();
1846                 if (bv().checkDepm(dummy, old)) {
1847                         updateNeeded = true;
1848                         // Make sure that cur gets back whatever happened to dummy (Lgb)
1849                         operator=(dummy);
1850                 }
1851                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
1852                         posBackward();
1853         } else {
1854                 // if there is a selection, we stay out of any inset,
1855                 // and just jump to the right position:
1856                 Cursor old = *this;
1857                 int next_row = row;
1858                 if (up) {
1859                         if (row > 0) {
1860                                 --next_row;
1861                         } else if (pit() > 0) {
1862                                 --pit();
1863                                 TextMetrics & tm = bv_->textMetrics(text());
1864                                 if (!tm.contains(pit()))
1865                                         tm.newParMetricsUp();
1866                                 ParagraphMetrics const & pmcur = tm.parMetrics(pit());
1867                                 next_row = pmcur.rows().size() - 1;
1868                         }
1869                 } else {
1870                         if (row + 1 < int(pm.rows().size())) {
1871                                 ++next_row;
1872                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1873                                 ++pit();
1874                                 TextMetrics & tm = bv_->textMetrics(text());
1875                                 if (!tm.contains(pit()))
1876                                         tm.newParMetricsDown();
1877                                 next_row = 0;
1878                         }
1879                 }
1880
1881                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
1882                 bool bound = false;
1883                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
1884                 boundary(bound);
1885
1886                 updateNeeded |= bv().checkDepm(*this, old);
1887         }
1888
1889         if (updateNeeded)
1890                 forceBufferUpdate();
1891         updateTextTargetOffset();
1892         return true;
1893 }
1894
1895
1896 void Cursor::handleFont(string const & font)
1897 {
1898         LYXERR(Debug::DEBUG, font);
1899         docstring safe;
1900         if (selection()) {
1901                 macroModeClose();
1902                 safe = cap::grabAndEraseSelection(*this);
1903         }
1904
1905         recordUndoInset();
1906
1907         if (lastpos() != 0) {
1908                 // something left in the cell
1909                 if (pos() == 0) {
1910                         // cursor in first position
1911                         popBackward();
1912                 } else if (pos() == lastpos()) {
1913                         // cursor in last position
1914                         popForward();
1915                 } else {
1916                         // cursor in between. split cell
1917                         MathData::iterator bt = cell().begin();
1918                         MathAtom at = createInsetMath(from_utf8(font), buffer());
1919                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
1920                         cell().erase(bt, bt + pos());
1921                         popBackward();
1922                         plainInsert(at);
1923                 }
1924         } else {
1925                 // nothing left in the cell
1926                 popBackward();
1927                 plainErase();
1928                 resetAnchor();
1929         }
1930         insert(safe);
1931 }
1932
1933
1934 void Cursor::message(docstring const & msg) const
1935 {
1936         disp_.setMessage(msg);
1937 }
1938
1939
1940 void Cursor::errorMessage(docstring const & msg) const
1941 {
1942         disp_.setMessage(msg);
1943         disp_.setError(true);
1944 }
1945
1946
1947 namespace {
1948
1949 docstring parbreak(Cursor const * cur)
1950 {
1951         odocstringstream os;
1952         os << '\n';
1953         // only add blank line if we're not in a ParbreakIsNewline situation
1954         if (!cur->inset().getLayout().parbreakIsNewline()
1955             && !cur->paragraph().layout().parbreak_is_newline)
1956                 os << '\n';
1957         return os.str();
1958 }
1959
1960 }
1961
1962
1963 docstring Cursor::selectionAsString(bool with_label) const
1964 {
1965         if (!selection())
1966                 return docstring();
1967
1968         if (inMathed())
1969                 return cap::grabSelection(*this);
1970
1971         int const label = with_label
1972                 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
1973
1974         idx_type const startidx = selBegin().idx();
1975         idx_type const endidx = selEnd().idx();
1976         if (startidx != endidx) {
1977                 // multicell selection
1978                 InsetTabular * table = inset().asInsetTabular();
1979                 LASSERT(table, return docstring());
1980                 return table->asString(startidx, endidx);
1981         }
1982
1983         ParagraphList const & pars = text()->paragraphs();
1984
1985         pit_type const startpit = selBegin().pit();
1986         pit_type const endpit = selEnd().pit();
1987         size_t const startpos = selBegin().pos();
1988         size_t const endpos = selEnd().pos();
1989
1990         if (startpit == endpit)
1991                 return pars[startpit].asString(startpos, endpos, label);
1992
1993         // First paragraph in selection
1994         docstring result = pars[startpit].
1995                 asString(startpos, pars[startpit].size(), label)
1996                 + parbreak(this);
1997
1998         // The paragraphs in between (if any)
1999         for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
2000                 Paragraph const & par = pars[pit];
2001                 result += par.asString(0, par.size(), label)
2002                         + parbreak(this);
2003         }
2004
2005         // Last paragraph in selection
2006         result += pars[endpit].asString(0, endpos, label);
2007
2008         return result;
2009 }
2010
2011
2012 docstring Cursor::currentState() const
2013 {
2014         if (inMathed()) {
2015                 odocstringstream os;
2016                 info(os);
2017 #ifdef DEVEL_VERSION
2018                 InsetMath * math = inset().asInsetMath();
2019                 if (math)
2020                         os << _(", Inset: ") << math->id();
2021                 os << _(", Cell: ") << idx();
2022                 os << _(", Position: ") << pos();
2023 #endif
2024                 return os.str();
2025         }
2026
2027         if (inTexted())
2028                 return text()->currentState(*this);
2029
2030         return docstring();
2031 }
2032
2033
2034 docstring Cursor::getPossibleLabel() const
2035 {
2036         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
2037 }
2038
2039
2040 Encoding const * Cursor::getEncoding() const
2041 {
2042         if (empty())
2043                 return 0;
2044         CursorSlice const & sl = innerTextSlice();
2045         Text const & text = *sl.text();
2046         Font font = text.getPar(sl.pit()).getFont(
2047                 bv().buffer().params(), sl.pos(), text.outerFont(sl.pit()));
2048         return font.language()->encoding();
2049 }
2050
2051
2052 void Cursor::undispatched() const
2053 {
2054         disp_.dispatched(false);
2055 }
2056
2057
2058 void Cursor::dispatched() const
2059 {
2060         disp_.dispatched(true);
2061 }
2062
2063
2064 void Cursor::screenUpdateFlags(Update::flags f) const
2065 {
2066         disp_.screenUpdate(f);
2067 }
2068
2069
2070 void Cursor::forceBufferUpdate() const
2071 {
2072         disp_.forceBufferUpdate();
2073 }
2074
2075
2076 void Cursor::clearBufferUpdate() const
2077 {
2078         disp_.clearBufferUpdate();
2079 }
2080
2081
2082 bool Cursor::needBufferUpdate() const
2083 {
2084         return disp_.needBufferUpdate();
2085 }
2086
2087
2088 void Cursor::noScreenUpdate() const
2089 {
2090         disp_.screenUpdate(Update::None);
2091 }
2092
2093
2094 Font Cursor::getFont() const
2095 {
2096         // The logic here should more or less match to the
2097         // Cursor::setCurrentFont logic, i.e. the cursor height should
2098         // give a hint what will happen if a character is entered.
2099
2100         // HACK. far from being perfect...
2101
2102         CursorSlice const & sl = innerTextSlice();
2103         Text const & text = *sl.text();
2104         Paragraph const & par = text.getPar(sl.pit());
2105
2106         // on boundary, so we are really at the character before
2107         pos_type pos = sl.pos();
2108         if (pos > 0 && boundary())
2109                 --pos;
2110
2111         // on space? Take the font before (only for RTL boundary stay)
2112         if (pos > 0) {
2113                 TextMetrics const & tm = bv().textMetrics(&text);
2114                 if (pos == sl.lastpos()
2115                         || (par.isSeparator(pos)
2116                         && !tm.isRTLBoundary(sl.pit(), pos)))
2117                         --pos;
2118         }
2119
2120         // get font at the position
2121         Font font = par.getFont(buffer()->params(), pos,
2122                 text.outerFont(sl.pit()));
2123
2124         return font;
2125 }
2126
2127
2128 bool Cursor::fixIfBroken()
2129 {
2130         bool const broken_cursor = DocIterator::fixIfBroken();
2131         bool const broken_anchor = anchor_.fixIfBroken();
2132
2133         if (broken_cursor || broken_anchor) {
2134                 clearNewWordPosition();
2135                 clearSelection();
2136                 return true;
2137         }
2138         return false;
2139 }
2140
2141
2142 void Cursor::sanitize()
2143 {
2144         setBuffer(&bv_->buffer());
2145         DocIterator::sanitize();
2146         if (selection())
2147                 anchor_.sanitize();
2148         else
2149                 resetAnchor();
2150 }
2151
2152
2153 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2154 {
2155         // find inset in common
2156         size_type i;
2157         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2158                 if (&old[i].inset() != &cur[i].inset())
2159                         break;
2160         }
2161
2162         // update words if we just moved to another paragraph
2163         if (i == old.depth() && i == cur.depth()
2164             && !cur.buffer()->isClean()
2165             && cur.inTexted() && old.inTexted()
2166             && cur.pit() != old.pit()) {
2167                 old.paragraph().updateWords();
2168         }
2169
2170         // notify everything on top of the common part in old cursor,
2171         // but stop if the inset claims the cursor to be invalid now
2172         for (size_type j = i; j < old.depth(); ++j) {
2173                 Cursor inset_pos = old;
2174                 inset_pos.cutOff(j);
2175                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2176                         return true;
2177         }
2178
2179         // notify everything on top of the common part in new cursor,
2180         // but stop if the inset claims the cursor to be invalid now
2181         for (; i < cur.depth(); ++i) {
2182                 if (cur[i].inset().notifyCursorEnters(cur))
2183                         return true;
2184         }
2185
2186         return false;
2187 }
2188
2189
2190 void Cursor::setCurrentFont()
2191 {
2192         CursorSlice const & cs = innerTextSlice();
2193         Paragraph const & par = cs.paragraph();
2194         pos_type cpit = cs.pit();
2195         pos_type cpos = cs.pos();
2196         Text const & ctext = *cs.text();
2197         TextMetrics const & tm = bv().textMetrics(&ctext);
2198
2199         // are we behind previous char in fact? -> go to that char
2200         if (cpos > 0 && boundary())
2201                 --cpos;
2202
2203         // find position to take the font from
2204         if (cpos != 0) {
2205                 // paragraph end? -> font of last char
2206                 if (cpos == lastpos())
2207                         --cpos;
2208                 // on space? -> look at the words in front of space
2209                 else if (cpos > 0 && par.isSeparator(cpos))     {
2210                         // abc| def -> font of c
2211                         // abc |[WERBEH], i.e. boundary==true -> font of c
2212                         // abc [WERBEH]| def, font of the space
2213                         if (!tm.isRTLBoundary(cpit, cpos))
2214                                 --cpos;
2215                 }
2216         }
2217
2218         // get font
2219         BufferParams const & bufparams = buffer()->params();
2220         current_font = par.getFontSettings(bufparams, cpos);
2221         real_current_font = tm.displayFont(cpit, cpos);
2222
2223         // special case for paragraph end
2224         if (cs.pos() == lastpos()
2225             && tm.isRTLBoundary(cpit, cs.pos())
2226             && !boundary()) {
2227                 Language const * lang = par.getParLanguage(bufparams);
2228                 current_font.setLanguage(lang);
2229                 current_font.fontInfo().setNumber(FONT_OFF);
2230                 real_current_font.setLanguage(lang);
2231                 real_current_font.fontInfo().setNumber(FONT_OFF);
2232         }
2233 }
2234
2235
2236 bool Cursor::textUndo()
2237 {
2238         if (!buffer()->undo().textUndo(*this))
2239                 return false;
2240         sanitize();
2241         return true;
2242 }
2243
2244
2245 bool Cursor::textRedo()
2246 {
2247         if (!buffer()->undo().textRedo(*this))
2248                 return false;
2249         sanitize();
2250         return true;
2251 }
2252
2253
2254 void Cursor::finishUndo() const
2255 {
2256         buffer()->undo().finishUndo();
2257 }
2258
2259
2260 void Cursor::beginUndoGroup() const
2261 {
2262         buffer()->undo().beginUndoGroup(*this);
2263 }
2264
2265
2266 void Cursor::endUndoGroup() const
2267 {
2268         buffer()->undo().endUndoGroup(*this);
2269 }
2270
2271
2272 void Cursor::recordUndo(pit_type from, pit_type to) const
2273 {
2274         buffer()->undo().recordUndo(*this, from, to);
2275 }
2276
2277
2278 void Cursor::recordUndo(pit_type from) const
2279 {
2280         buffer()->undo().recordUndo(*this, from, pit());
2281 }
2282
2283
2284 void Cursor::recordUndo(UndoKind kind) const
2285 {
2286         buffer()->undo().recordUndo(*this, kind);
2287 }
2288
2289
2290 void Cursor::recordUndoInset(Inset const * in) const
2291 {
2292         buffer()->undo().recordUndoInset(*this, in);
2293 }
2294
2295
2296 void Cursor::recordUndoFullBuffer() const
2297 {
2298         buffer()->undo().recordUndoFullBuffer(*this);
2299 }
2300
2301
2302 void Cursor::recordUndoBufferParams() const
2303 {
2304         buffer()->undo().recordUndoBufferParams(*this);
2305 }
2306
2307
2308 void Cursor::recordUndoSelection() const
2309 {
2310         if (inMathed()) {
2311                 if (cap::multipleCellsSelected(*this))
2312                         recordUndoInset();
2313                 else
2314                         recordUndo();
2315         } else {
2316                 buffer()->undo().recordUndo(*this,
2317                         selBegin().pit(), selEnd().pit());
2318         }
2319 }
2320
2321
2322 void Cursor::checkBufferStructure()
2323 {
2324         Buffer const * master = buffer()->masterBuffer();
2325         master->tocBackend().updateItem(*this);
2326         if (master != buffer() && !master->hasGuiDelegate())
2327                 // In case the master has no gui associated with it,
2328                 // the TocItem is not updated (part of bug 5699).
2329                 buffer()->tocBackend().updateItem(*this);
2330
2331         // If the last tracked change of the paragraph has just been
2332         // deleted, then we need to recompute the buffer flag
2333         // tracked_changes_present_.
2334         if (inTexted() && paragraph().isChangeUpdateRequired())
2335                 disp_.forceChangesUpdate();
2336 }
2337
2338
2339 } // namespace lyx