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