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