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