]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Avoid full metrics computation with Update:FitCursor
[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         inset.setBuffer(*buffer());
907 }
908
909
910 void Cursor::pushBackward(Inset & inset)
911 {
912         LASSERT(!empty(), return);
913         //lyxerr << "Entering inset " << t << " front" << endl;
914         push(inset);
915         inset.idxFirst(*this);
916 }
917
918
919 void Cursor::editInsertedInset()
920 {
921         LASSERT(!empty(), return);
922         if (pos() == 0)
923                 return;
924
925         InsetMath &p = prevMath();
926         if (!p.isActive())
927                 return;
928
929         posBackward();
930         push(p);
931         p.idxFirst(*this);
932         // this could be a while() loop, but only one cell is not empty in
933         // cases we are interested in. The cell is not empty because we
934         // have inserted the selection in there.
935         if (!cell().empty()) {
936                 // if it is not empty, move to the next one.
937                 if (!inset().idxNext(*this))
938                         // If there is no next one, exit the inset.
939                         popForward();
940         }
941 }
942
943
944 bool Cursor::popBackward()
945 {
946         LASSERT(!empty(), return false);
947         if (depth() == 1)
948                 return false;
949         pop();
950         return true;
951 }
952
953
954 bool Cursor::popForward()
955 {
956         LASSERT(!empty(), return false);
957         //lyxerr << "Leaving inset from in back" << endl;
958         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
959         if (depth() == 1)
960                 return false;
961         pop();
962         pos() += lastpos() - lp + 1;
963         return true;
964 }
965
966
967 void Cursor::getPos(int & x, int & y) const
968 {
969         Point p = bv().getPos(*this);
970         x = p.x_;
971         y = p.y_;
972 }
973
974
975 Row const & Cursor::textRow() const
976 {
977         CursorSlice const & cs = innerTextSlice();
978         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
979         return pm.getRow(pos(), boundary());
980 }
981
982
983 bool Cursor::posVisRight(bool skip_inset)
984 {
985         Cursor new_cur = *this; // where we will move to
986         pos_type left_pos; // position visually left of current cursor
987         pos_type right_pos; // position visually right of current cursor
988
989         getSurroundingPos(left_pos, right_pos);
990
991         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
992
993         // Are we at an inset?
994         new_cur.pos() = right_pos;
995         new_cur.boundary(false);
996         if (!skip_inset &&
997                 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
998                 // we actually move the cursor at the end of this
999                 // function, for now we just keep track of the new
1000                 // position in new_cur...
1001                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1002         }
1003
1004         // Are we already at rightmost pos in row?
1005         else if (text()->empty() || right_pos == -1) {
1006
1007                 new_cur = *this;
1008                 if (!new_cur.posVisToNewRow(false)) {
1009                         LYXERR(Debug::RTL, "not moving!");
1010                         return false;
1011                 }
1012
1013                 // we actually move the cursor at the end of this
1014                 // function, for now just keep track of the new
1015                 // position in new_cur...
1016                 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
1017                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1018
1019         }
1020         // normal movement to the right
1021         else {
1022                 new_cur = *this;
1023                 // Recall, if the cursor is at position 'x', that
1024                 // means *before* the character at position 'x'. In
1025                 // RTL, "before" means "to the right of", in LTR, "to
1026                 // the left of". So currently our situation is this:
1027                 // the position to our right is 'right_pos' (i.e.,
1028                 // we're currently to the left of 'right_pos'). In
1029                 // order to move to the right, it depends whether or
1030                 // not the character at 'right_pos' is RTL.
1031                 bool const new_pos_is_RTL = paragraph().getFontSettings(
1032                         buffer()->params(), right_pos).isVisibleRightToLeft();
1033                 // If the character at 'right_pos' *is* LTR, then in
1034                 // order to move to the right of it, we need to be
1035                 // *after* 'right_pos', i.e., move to position
1036                 // 'right_pos' + 1.
1037                 if (!new_pos_is_RTL) {
1038                         new_cur.pos() = right_pos + 1;
1039                         // set the boundary to true in two situations:
1040                         if (
1041                         // 1. if new_pos is now lastpos, and we're in
1042                         // an RTL paragraph (this means that we're
1043                         // moving right to the end of an LTR chunk
1044                         // which is at the end of an RTL paragraph);
1045                                 (new_cur.pos() == lastpos()
1046                                  && paragraph().isRTL(buffer()->params()))
1047                         // 2. if the position *after* right_pos is RTL
1048                         // (we want to be *after* right_pos, not
1049                         // before right_pos + 1!)
1050                                 || paragraph().getFontSettings(buffer()->params(),
1051                                                 new_cur.pos()).isVisibleRightToLeft()
1052                         )
1053                                 new_cur.boundary(true);
1054                         else // set the boundary to false
1055                                 new_cur.boundary(false);
1056                 }
1057                 // Otherwise (if the character at position 'right_pos'
1058                 // is RTL), then moving to the right of it is as easy
1059                 // as setting the new position to 'right_pos'.
1060                 else {
1061                         new_cur.pos() = right_pos;
1062                         new_cur.boundary(false);
1063                 }
1064
1065         }
1066
1067         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1068
1069         if (moved) {
1070                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1071                         << (new_cur.boundary() ? " (boundary)" : ""));
1072                 *this = new_cur;
1073         }
1074
1075         return moved;
1076 }
1077
1078
1079 bool Cursor::posVisLeft(bool skip_inset)
1080 {
1081         Cursor new_cur = *this; // where we will move to
1082         pos_type left_pos; // position visually left of current cursor
1083         pos_type right_pos; // position visually right of current cursor
1084
1085         getSurroundingPos(left_pos, right_pos);
1086
1087         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1088
1089         // Are we at an inset?
1090         new_cur.pos() = left_pos;
1091         new_cur.boundary(false);
1092         if (!skip_inset &&
1093                 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1094                 // we actually move the cursor at the end of this
1095                 // function, for now we just keep track of the new
1096                 // position in new_cur...
1097                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1098         }
1099
1100         // Are we already at leftmost pos in row?
1101         else if (text()->empty() || left_pos == -1) {
1102
1103                 new_cur = *this;
1104                 if (!new_cur.posVisToNewRow(true)) {
1105                         LYXERR(Debug::RTL, "not moving!");
1106                         return false;
1107                 }
1108
1109                 // we actually move the cursor at the end of this
1110                 // function, for now just keep track of the new
1111                 // position in new_cur...
1112                 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1113                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1114
1115         }
1116         // normal movement to the left
1117         else {
1118                 new_cur = *this;
1119                 // Recall, if the cursor is at position 'x', that
1120                 // means *before* the character at position 'x'. In
1121                 // RTL, "before" means "to the right of", in LTR, "to
1122                 // the left of". So currently our situation is this:
1123                 // the position to our left is 'left_pos' (i.e., we're
1124                 // currently to the right of 'left_pos'). In order to
1125                 // move to the left, it depends whether or not the
1126                 // character at 'left_pos' is RTL.
1127                 bool const new_pos_is_RTL = paragraph().getFontSettings(
1128                         buffer()->params(), left_pos).isVisibleRightToLeft();
1129                 // If the character at 'left_pos' *is* RTL, then in
1130                 // order to move to the left of it, we need to be
1131                 // *after* 'left_pos', i.e., move to position
1132                 // 'left_pos' + 1.
1133                 if (new_pos_is_RTL) {
1134                         new_cur.pos() = left_pos + 1;
1135                         // set the boundary to true in two situations:
1136                         if (
1137                         // 1. if new_pos is now lastpos and we're in
1138                         // an LTR paragraph (this means that we're
1139                         // moving left to the end of an RTL chunk
1140                         // which is at the end of an LTR paragraph);
1141                                 (new_cur.pos() == lastpos()
1142                                  && !paragraph().isRTL(buffer()->params()))
1143                         // 2. if the position *after* left_pos is not
1144                         // RTL (we want to be *after* left_pos, not
1145                         // before left_pos + 1!)
1146                                 || !paragraph().getFontSettings(buffer()->params(),
1147                                                 new_cur.pos()).isVisibleRightToLeft()
1148                         )
1149                                 new_cur.boundary(true);
1150                         else // set the boundary to false
1151                                 new_cur.boundary(false);
1152                 }
1153                 // Otherwise (if the character at position 'left_pos'
1154                 // is LTR), then moving to the left of it is as easy
1155                 // as setting the new position to 'left_pos'.
1156                 else {
1157                         new_cur.pos() = left_pos;
1158                         new_cur.boundary(false);
1159                 }
1160
1161         }
1162
1163         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1164
1165         if (moved) {
1166                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1167                         << (new_cur.boundary() ? " (boundary)" : ""));
1168                 *this = new_cur;
1169         }
1170
1171         return moved;
1172 }
1173
1174
1175 namespace {
1176
1177 // Return true on success
1178 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1179 {
1180         if (onleft) {
1181                 while (cit != row.begin() && cit->isVirtual())
1182                         --cit;
1183         } else {
1184                 while (cit != row.end() && cit->isVirtual())
1185                         ++cit;
1186         }
1187         return cit != row.end() && !cit->isVirtual();
1188 }
1189
1190 } // namespace
1191
1192 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1193 {
1194         // by default, we know nothing.
1195         left_pos = -1;
1196         right_pos = -1;
1197
1198         Row const & row = textRow();
1199         double dummy = 0;
1200         Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1201         // Handle the case of empty row
1202         if (cit == row.end()) {
1203                 if (row.isRTL())
1204                         right_pos = row.pos();
1205                 else
1206                         left_pos = row.pos() - 1;
1207                 return;
1208         }
1209
1210         // skip virtual elements and exit if no non-virtual one exists
1211         if (!findNonVirtual(row, cit, !cit->isRTL()))
1212                 return;
1213
1214         // if the position is at the left side of the element, we have to
1215         // look at the previous element
1216         if (pos() == cit->left_pos()) {
1217                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1218                            << "), AT LEFT of *cit=" << *cit);
1219                 // this one is easy (see common case below)
1220                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1221                 // at the left of the row
1222                 if (cit == row.begin())
1223                         return;
1224                 --cit;
1225                 if (!findNonVirtual(row, cit, true))
1226                         return;
1227                 // [...[ is the row element, | is cursor position (! with boundary)
1228                 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1229                 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1230                 //    [ 1 2 [  [|3 4 [ => (2, 3)
1231                 // or [ 1 2 [  ]!4 3 ] => (2, 4)
1232                 // or ] 2 1 ]  [|3 4 [ => (1, 3)
1233                 // or ] 4 3 ]  ]!2 1 ] => (3, 2)
1234                 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1235                 // happens with consecutive row of same direction
1236                 if (left_pos == right_pos) {
1237                         left_pos += cit->isRTL() ? 1 : -1;
1238                 }
1239         }
1240         // same code but with the element at the right
1241         else if (pos() == cit->right_pos()) {
1242                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1243                            << "), AT RIGHT of *cit=" << *cit);
1244                 // this one is easy (see common case below)
1245                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1246                 // at the right of the row
1247                 if (cit + 1 == row.end())
1248                         return;
1249                 ++cit;
1250                 if (!findNonVirtual(row, cit, false))
1251                         return;
1252                 //    [ 1 2![  [ 3 4 [ => (2, 3)
1253                 // or [ 1 2![  ] 4 3 ] => (2, 4)
1254                 // or ] 2 1|]  [ 3 4 [ => (1, 3)
1255                 // or ] 4 3|]  ] 2 1 ] => (3, 2)
1256                 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1257                 // happens with consecutive row of same direction
1258                 if (right_pos == left_pos)
1259                         right_pos += cit->isRTL() ? -1 : 1;
1260         }
1261         // common case: both positions are inside the row element
1262         else {
1263                 //    [ 1 2|3 [ => (2, 3)
1264                 // or ] 3|2 1 ] => (3, 2)
1265                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1266                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1267         }
1268
1269         // Note that debug message does not catch all early returns above
1270         LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1271                    << ") => (" << left_pos << ", " << right_pos <<")");
1272 }
1273
1274
1275 bool Cursor::posVisToNewRow(bool movingLeft)
1276 {
1277         Row const & row = textRow();
1278         bool par_is_LTR = !row.isRTL();
1279
1280         // Inside a table, determining whether to move to the next or
1281         // previous row should be done based on the table's direction.
1282         if (inset().asInsetTabular()) {
1283                 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1284                 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1285         }
1286
1287         // if moving left in an LTR paragraph or moving right in an
1288         // RTL one, move to previous row
1289         if (par_is_LTR == movingLeft) {
1290                 if (row.pos() == 0) { // we're at first row in paragraph
1291                         if (pit() == 0) // no previous paragraph! don't move
1292                                 return false;
1293                         // move to last pos in previous par
1294                         --pit();
1295                         pos() = lastpos();
1296                         boundary(false);
1297                 } else { // move to previous row in this par
1298                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
1299                         boundary(false);
1300                 }
1301         }
1302         // if moving left in an RTL paragraph or moving right in an
1303         // LTR one, move to next row
1304         else {
1305                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1306                         if (pit() == lastpit()) // last paragraph! don't move
1307                                 return false;
1308                         // move to first row in next par
1309                         ++pit();
1310                         pos() = 0;
1311                         boundary(false);
1312                 } else { // move to next row in this par
1313                         pos() = row.endpos();
1314                         boundary(false);
1315                 }
1316         }
1317
1318         // make sure we're at left-/right-most pos in new row
1319         posVisToRowExtremity(!movingLeft);
1320
1321         return true;
1322 }
1323
1324
1325 void Cursor::posVisToRowExtremity(bool left)
1326 {
1327         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1328                 << (boundary() ? 1 : 0));
1329
1330         TextMetrics const & tm = bv_->textMetrics(text());
1331         // Looking for extremities is like clicking on the left or the
1332         // right of the row.
1333         int x = tm.origin().x_ + (left ? 0 : textRow().width());
1334         bool b = false;
1335         pos() = tm.getPosNearX(textRow(), x, b);
1336         boundary(b);
1337
1338         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1339                 << (boundary() ? 1 : 0));
1340 }
1341
1342
1343 bool Cursor::reverseDirectionNeeded() const
1344 {
1345         /*
1346          * We determine the directions based on the direction of the
1347          * bottom() --- i.e., outermost --- paragraph, because that is
1348          * the only way to achieve consistency of the arrow's movements
1349          * within a paragraph, and thus avoid situations in which the
1350          * cursor gets stuck.
1351          */
1352         return bottom().paragraph().isRTL(bv().buffer().params());
1353 }
1354
1355
1356 void Cursor::setTargetX(int x)
1357 {
1358         x_target_ = x;
1359         textTargetOffset_ = 0;
1360 }
1361
1362
1363 int Cursor::x_target() const
1364 {
1365         return x_target_;
1366 }
1367
1368
1369 void Cursor::clearTargetX()
1370 {
1371         x_target_ = -1;
1372         textTargetOffset_ = 0;
1373 }
1374
1375
1376 void Cursor::updateTextTargetOffset()
1377 {
1378         int x;
1379         int y;
1380         getPos(x, y);
1381         textTargetOffset_ = x - x_target_;
1382 }
1383
1384
1385 void Cursor::setClickPos(int x, int y)
1386 {
1387         x_clickpos_ = x;
1388         y_clickpos_ = y;
1389 }
1390
1391
1392 bool Cursor::selHandle(bool selecting)
1393 {
1394         //lyxerr << "Cursor::selHandle" << endl;
1395         if (mark())
1396                 selecting = true;
1397         if (selecting == selection())
1398                 return false;
1399
1400         if (!selecting)
1401                 cap::saveSelection(*this);
1402
1403         resetAnchor();
1404         selection(selecting);
1405         return true;
1406 }
1407
1408
1409 bool Cursor::atFirstOrLastRow(bool up)
1410 {
1411         TextMetrics const & tm = bv_->textMetrics(text());
1412         ParagraphMetrics const & pm = tm.parMetrics(pit());
1413
1414         int row;
1415         if (pos() && boundary())
1416                 row = pm.pos2row(pos() - 1);
1417         else
1418                 row = pm.pos2row(pos());
1419
1420         if (up) {
1421                 if (pit() == 0 && row == 0)
1422                         return true;
1423         } else {
1424                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1425                         row + 1 >= int(pm.rows().size()))
1426                         return true;
1427         }
1428         return false;
1429 }
1430
1431
1432 } // namespace lyx
1433
1434
1435 ///////////////////////////////////////////////////////////////////
1436 //
1437 // FIXME: Look here
1438 // The part below is the non-integrated rest of the original math
1439 // cursor. This should be either generalized for texted or moved
1440 // back to mathed (in most cases to InsetMathNest).
1441 //
1442 ///////////////////////////////////////////////////////////////////
1443
1444 #include "mathed/InsetMathChar.h"
1445 #include "mathed/InsetMathUnknown.h"
1446 #include "mathed/MathStream.h"
1447 #include "mathed/MathSupport.h"
1448
1449
1450 namespace lyx {
1451
1452 bool Cursor::openable(MathAtom const & t) const
1453 {
1454         if (!t->isActive())
1455                 return false;
1456
1457         if (t->lock())
1458                 return false;
1459
1460         if (!selection())
1461                 return true;
1462
1463         // we can't move into anything new during selection
1464         if (depth() >= realAnchor().depth())
1465                 return false;
1466         if (t.nucleus() != &realAnchor()[depth()].inset())
1467                 return false;
1468
1469         return true;
1470 }
1471
1472
1473 void Cursor::plainErase()
1474 {
1475         cell().erase(pos());
1476 }
1477
1478
1479 void Cursor::plainInsert(MathAtom const & t)
1480 {
1481         cell().insert(pos(), t);
1482         ++pos();
1483         inset().setBuffer(bv_->buffer());
1484         inset().initView();
1485         checkBufferStructure();
1486 }
1487
1488
1489 void Cursor::insert(char_type c)
1490 {
1491         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1492         LASSERT(!empty(), return);
1493         if (inMathed()) {
1494                 cap::selClearOrDel(*this);
1495                 insert(new InsetMathChar(buffer(), c));
1496         } else {
1497                 text()->insertChar(*this, c);
1498         }
1499 }
1500
1501
1502 void Cursor::insert(docstring const & str)
1503 {
1504         for (char_type c : str)
1505                 insert(c);
1506 }
1507
1508
1509 void Cursor::insert(Inset * inset0)
1510 {
1511         LASSERT(inset0, return);
1512         if (inMathed())
1513                 insert(MathAtom(inset0->asInsetMath()));
1514         else {
1515                 text()->insertInset(*this, inset0);
1516                 inset0->setBuffer(bv_->buffer());
1517                 inset0->initView();
1518                 if (inset0->isLabeled())
1519                         forceBufferUpdate();
1520         }
1521 }
1522
1523
1524 void Cursor::insert(MathAtom const & t)
1525 {
1526         LATTEST(inMathed());
1527         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1528         macroModeClose();
1529         cap::selClearOrDel(*this);
1530         plainInsert(t);
1531 }
1532
1533
1534 void Cursor::insert(MathData const & ar)
1535 {
1536         LATTEST(inMathed());
1537         macroModeClose();
1538         if (selection())
1539                 cap::eraseSelection(*this);
1540         cell().insert(pos(), ar);
1541         pos() += ar.size();
1542         // FIXME audit setBuffer calls
1543         inset().setBuffer(bv_->buffer());
1544 }
1545
1546
1547 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1548 {
1549         LATTEST(inMathed());
1550         MathData ar(buffer());
1551         asArray(t, ar, f);
1552         if (ar.size() == 1 && (enter || selection()))
1553                 niceInsert(ar[0]);
1554         else
1555                 insert(ar);
1556         return ar.size();
1557 }
1558
1559
1560 void Cursor::niceInsert(MathAtom const & t)
1561 {
1562         LATTEST(inMathed());
1563         macroModeClose();
1564         docstring const safe = cap::grabAndEraseSelection(*this);
1565         plainInsert(t);
1566         // If possible, enter the new inset and move the contents of the selection
1567         if (t->isActive()) {
1568                 idx_type const idx = prevMath().asNestInset()->firstIdx();
1569                 MathData ar(buffer());
1570                 asArray(safe, ar);
1571                 prevMath().cell(idx).insert(0, ar);
1572                 editInsertedInset();
1573         } else if (t->asMacro() && !safe.empty()) {
1574                 MathData ar(buffer());
1575                 asArray(safe, ar);
1576                 docstring const name = t->asMacro()->name();
1577                 MacroData const * data = buffer()->getMacro(name);
1578                 if (data && data->numargs() - data->optionals() > 0) {
1579                         plainInsert(MathAtom(new InsetMathBrace(buffer(), ar)));
1580                         posBackward();
1581                 }
1582         }
1583 }
1584
1585
1586 bool Cursor::backspace(bool const force)
1587 {
1588         if (selection()) {
1589                 cap::eraseSelection(*this);
1590                 return true;
1591         }
1592
1593         if (pos() == 0) {
1594                 // If empty cell, and not part of a big cell
1595                 if (lastpos() == 0 && inset().nargs() == 1) {
1596                         popBackward();
1597                         // Directly delete empty cell: [|[]] => [|]
1598                         if (inMathed()) {
1599                                 plainErase();
1600                                 resetAnchor();
1601                                 return true;
1602                         }
1603                         // [|], can not delete from inside
1604                         return false;
1605                 } else {
1606                         if (inMathed()) {
1607                                 switch (inset().asInsetMath()->getType()) {
1608                                 case hullEqnArray:
1609                                 case hullAlign:
1610                                 case hullFlAlign: {
1611                                         FuncRequest cmd(LFUN_CHAR_BACKWARD);
1612                                         this->dispatch(cmd);
1613                                         break;
1614                                 }
1615                                 default:
1616                                         pullArg();
1617                                         break;
1618                                 }
1619                         } else
1620                                 popBackward();
1621                         return true;
1622                 }
1623         }
1624
1625         if (inMacroMode()) {
1626                 InsetMathUnknown * p = activeMacro();
1627                 if (p->name().size() > 1) {
1628                         p->setName(p->name().substr(0, p->name().size() - 1));
1629                         return true;
1630                 }
1631         }
1632
1633         if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1634                 // let's require two backspaces for 'big stuff' and
1635                 // highlight on the first
1636                 resetAnchor();
1637                 selection(true);
1638                 --pos();
1639         } else {
1640                 --pos();
1641                 plainErase();
1642         }
1643         return true;
1644 }
1645
1646
1647 bool Cursor::erase(bool const force)
1648 {
1649         if (inMacroMode())
1650                 return true;
1651
1652         if (selection()) {
1653                 cap::eraseSelection(*this);
1654                 return true;
1655         }
1656
1657         // delete empty cells if possible
1658         if (pos() == lastpos() && inset().idxDelete(idx()))
1659                 return true;
1660
1661         // special behaviour when in last position of cell
1662         if (pos() == lastpos()) {
1663                 bool one_cell = inset().nargs() == 1;
1664                 if (one_cell && lastpos() == 0) {
1665                         popBackward();
1666                         // Directly delete empty cell: [|[]] => [|]
1667                         if (inMathed()) {
1668                                 plainErase();
1669                                 resetAnchor();
1670                                 return true;
1671                         }
1672                         // [|], can not delete from inside
1673                         return false;
1674                 }
1675                 // remove markup
1676                 if (!one_cell)
1677                         inset().idxGlue(idx());
1678                 return true;
1679         }
1680
1681         // 'clever' UI hack: only erase large items if previously slected
1682         if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1683                 resetAnchor();
1684                 selection(true);
1685                 ++pos();
1686         } else {
1687                 plainErase();
1688         }
1689
1690         return true;
1691 }
1692
1693
1694 bool Cursor::up()
1695 {
1696         macroModeClose();
1697         DocIterator save = *this;
1698         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1699         this->dispatch(cmd);
1700         if (disp_.dispatched())
1701                 return true;
1702         setCursor(save);
1703         return false;
1704 }
1705
1706
1707 bool Cursor::down()
1708 {
1709         macroModeClose();
1710         DocIterator save = *this;
1711         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1712         this->dispatch(cmd);
1713         if (disp_.dispatched())
1714                 return true;
1715         setCursor(save);
1716         return false;
1717 }
1718
1719
1720 void Cursor::handleNest(MathAtom const & a)
1721 {
1722         idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1723         //lyxerr << "Cursor::handleNest: " << idx << endl;
1724         InsetMath const * im = selectionBegin().inset().asInsetMath();
1725         Parse::flags const f = im && im->currentMode() != InsetMath::MATH_MODE
1726                 ? Parse::TEXTMODE : Parse::NORMAL;
1727         MathAtom t = a;
1728         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx), f);
1729         insert(t);
1730         editInsertedInset();
1731 }
1732
1733
1734 int Cursor::targetX() const
1735 {
1736         if (x_target() != -1)
1737                 return x_target();
1738         int x = 0;
1739         int y = 0;
1740         getPos(x, y);
1741         return x;
1742 }
1743
1744
1745 int Cursor::textTargetOffset() const
1746 {
1747         return textTargetOffset_;
1748 }
1749
1750
1751 void Cursor::setTargetX()
1752 {
1753         int x;
1754         int y;
1755         getPos(x, y);
1756         setTargetX(x);
1757 }
1758
1759
1760 bool Cursor::macroModeClose(bool cancel)
1761 {
1762         if (!inMacroMode())
1763                 return false;
1764         InsetMathUnknown * p = activeMacro();
1765         p->finalize();
1766         MathData selection(buffer());
1767         asArray(p->selection(), selection);
1768         docstring const s = p->name();
1769         --pos();
1770         cell().erase(pos());
1771
1772         // trigger updates of macros, at least, if no full
1773         // updates take place anyway
1774         screenUpdateFlags(Update::Force);
1775
1776         // do nothing if the macro name is empty
1777         if (s == "\\" || cancel) {
1778                 return false;
1779         }
1780
1781         docstring const name = s.substr(1);
1782         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1783         if (in && in->interpretString(*this, s))
1784                 return true;
1785         bool const user_macro = buffer()->getMacro(name, *this, false);
1786         MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1787                                    : createInsetMath(name, buffer());
1788
1789         // try to put argument into macro, if we just inserted a macro
1790         bool macroArg = false;
1791         InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1792         InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1793         if (atomAsMacro) {
1794                 // macros here are still unfolded (in init mode in fact). So
1795                 // we have to resolve the macro here manually and check its arity
1796                 // to put the selection behind it if arity > 0.
1797                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1798                 if (!selection.empty() && data && data->numargs()) {
1799                         macroArg = true;
1800                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1801                 } else
1802                         // non-greedy case. Do not touch the arguments behind
1803                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1804         }
1805
1806         // insert remembered selection into first argument of a non-macro
1807         else if (atomAsNest && atomAsNest->nargs() > 0)
1808                 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1809
1810         MathWordList const & words = mathedWordList();
1811         MathWordList::const_iterator it = words.find(name);
1812         bool keep_mathmode = user_macro
1813                 || (it != words.end() && (it->second.inset == "font"
1814                                           || it->second.inset == "oldfont"
1815                                           || it->second.inset == "textsize"
1816                                           || it->second.inset == "mbox"));
1817         bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1818
1819         if (in && in->currentMode() == Inset::TEXT_MODE
1820             && atom.nucleus()->currentMode() == Inset::MATH_MODE
1821             && name != from_ascii("ensuremath") && !ert_macro) {
1822                 MathAtom at(new InsetMathEnsureMath(buffer()));
1823                 at.nucleus()->cell(0).push_back(atom);
1824                 niceInsert(at);
1825                 posForward();
1826         } else if (in && in->currentMode() == Inset::MATH_MODE
1827                    && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1828                    && !keep_mathmode) {
1829                 MathAtom at = createInsetMath("text", buffer());
1830                 at.nucleus()->cell(0).push_back(atom);
1831                 niceInsert(at);
1832                 posForward();
1833         } else
1834                 plainInsert(atom);
1835
1836         // finally put the macro argument behind, if needed
1837         if (macroArg) {
1838                 if (selection.size() > 1 || selection[0]->asScriptInset())
1839                         plainInsert(MathAtom(new InsetMathBrace(buffer(), selection)));
1840                 else
1841                         insert(selection);
1842         }
1843
1844         return true;
1845 }
1846
1847
1848 bool Cursor::inMacroMode() const
1849 {
1850         if (!inMathed())
1851                 return false;
1852         if (pos() == 0 || cell().empty())
1853                 return false;
1854         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1855         return p && !p->final();
1856 }
1857
1858
1859 InsetMathUnknown * Cursor::activeMacro()
1860 {
1861         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : nullptr;
1862 }
1863
1864
1865 InsetMathUnknown const * Cursor::activeMacro() const
1866 {
1867         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : nullptr;
1868 }
1869
1870
1871 docstring Cursor::macroName()
1872 {
1873         return inMacroMode() ? activeMacro()->name() : docstring();
1874 }
1875
1876
1877 void Cursor::pullArg()
1878 {
1879         // FIXME: Look here
1880         MathData ar = cell();
1881         if (popBackward() && inMathed()) {
1882                 plainErase();
1883                 cell().insert(pos(), ar);
1884                 resetAnchor();
1885         }
1886 }
1887
1888
1889 void Cursor::normalize()
1890 {
1891         if (idx() > lastidx()) {
1892                 lyxerr << "this should not really happen - 1: "
1893                        << idx() << ' ' << nargs()
1894                        << " in: " << &inset() << endl;
1895                 idx() = lastidx();
1896         }
1897
1898         if (pos() > lastpos()) {
1899                 lyxerr << "this should not really happen - 2: "
1900                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1901                        << " in atom: '";
1902                 odocstringstream os;
1903                 otexrowstream ots(os);
1904                 TeXMathStream wi(ots, false, true, TeXMathStream::wsDefault);
1905                 inset().asInsetMath()->write(wi);
1906                 lyxerr << to_utf8(os.str()) << endl;
1907                 pos() = lastpos();
1908         }
1909 }
1910
1911
1912 bool Cursor::upDownInMath(bool up)
1913 {
1914         // Be warned: The 'logic' implemented in this function is highly
1915         // fragile. A distance of one pixel or a '<' vs '<=' _really
1916         // matters. So fiddle around with it only if you think you know
1917         // what you are doing!
1918         int xo = 0;
1919         int yo = 0;
1920         getPos(xo, yo);
1921         xo = beforeDispatchPosX_;
1922
1923         // check if we had something else in mind, if not, this is the future
1924         // target
1925         if (x_target_ == -1)
1926                 setTargetX(xo);
1927         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1928                 // In text mode inside the line (not left or right) possibly set a new target_x,
1929                 // but only if we are somewhere else than the previous target-offset.
1930
1931                 // We want to keep the x-target on subsequent up/down movements
1932                 // that cross beyond the end of short lines. Thus a special
1933                 // handling when the cursor is at the end of line: Use the new
1934                 // x-target only if the old one was before the end of line
1935                 // or the old one was after the beginning of the line
1936                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1937                 bool left;
1938                 bool right;
1939                 if (inRTL) {
1940                         left = pos() == textRow().endpos();
1941                         right = pos() == textRow().pos();
1942                 } else {
1943                         left = pos() == textRow().pos();
1944                         right = pos() == textRow().endpos();
1945                 }
1946                 if ((!left && !right) ||
1947                                 (left && !right && xo < x_target_) ||
1948                                 (!left && right && x_target_ < xo))
1949                         setTargetX(xo);
1950                 else
1951                         xo = targetX();
1952         } else
1953                 xo = targetX();
1954
1955         // try neigbouring script insets
1956         Cursor old = *this;
1957         if (inMathed() && !selection()) {
1958                 // try left
1959                 if (pos() != 0) {
1960                         InsetMathScript const * p = prevAtom()->asScriptInset();
1961                         if (p && p->has(up)) {
1962                                 --pos();
1963                                 push(*const_cast<InsetMathScript*>(p));
1964                                 idx() = p->idxOfScript(up);
1965                                 pos() = lastpos();
1966
1967                                 // we went in the right direction? Otherwise don't jump into the script
1968                                 int x;
1969                                 int y;
1970                                 getPos(x, y);
1971                                 int oy = beforeDispatchPosY_;
1972                                 if ((!up && y <= oy) ||
1973                                                 (up && y >= oy))
1974                                         operator=(old);
1975                                 else
1976                                         return true;
1977                         }
1978                 }
1979
1980                 // try right
1981                 if (pos() != lastpos()) {
1982                         InsetMathScript const * p = nextAtom()->asScriptInset();
1983                         if (p && p->has(up)) {
1984                                 push(*const_cast<InsetMathScript*>(p));
1985                                 idx() = p->idxOfScript(up);
1986                                 pos() = 0;
1987
1988                                 // we went in the right direction? Otherwise don't jump into the script
1989                                 int x;
1990                                 int y;
1991                                 getPos(x, y);
1992                                 int oy = beforeDispatchPosY_;
1993                                 if ((!up && y <= oy) ||
1994                                                 (up && y >= oy))
1995                                         operator=(old);
1996                                 else
1997                                         return true;
1998                         }
1999                 }
2000         }
2001
2002         // try to find an inset that knows better then we,
2003         if (inset().idxUpDown(*this, up)) {
2004                 //lyxerr << "idxUpDown triggered" << endl;
2005                 // try to find best position within this inset
2006                 if (!selection())
2007                         setCursor(bruteFind(*this, xo, yo));
2008                 // FIXME : this is actually only needed for InsetMathMacro (bug #12952).
2009                 screenUpdateFlags(Update::SinglePar);
2010                 return true;
2011         }
2012
2013         // any improvement going just out of inset?
2014         if (popBackward() && inMathed()) {
2015                 //lyxerr << "updown: popBackward succeeded" << endl;
2016                 int xnew;
2017                 int ynew;
2018                 int yold = beforeDispatchPosY_;
2019                 getPos(xnew, ynew);
2020                 if (up ? ynew < yold : ynew > yold)
2021                         return true;
2022         }
2023
2024         // no success, we are probably at the document top or bottom
2025         operator=(old);
2026         return false;
2027 }
2028
2029
2030 bool Cursor::mathForward(bool word)
2031 {
2032         LASSERT(inMathed(), return false);
2033         if (pos() < lastpos()) {
2034                 if (word) {
2035                         // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2036                         // match) where X is any math class, B is mathbin, R is mathrel, and
2037                         // P is mathpunct. Make sure that the following remains true:
2038                         //   mathForward(true); mathBackward(true); mathForward(true)
2039                         // is the same as mathForward(true) and
2040                         //   mathBackward(true); mathForward(true); mathBackward(true)
2041                         // is the same as mathBackward(true).
2042                         MathClass mc = nextMath().mathClass();
2043                         do
2044                                 posForward();
2045                         while (pos() < lastpos() && mc == nextMath().mathClass());
2046                         if (pos() < lastpos() &&
2047                             ((mc = nextMath().mathClass()) == MC_BIN ||
2048                              mc == MC_REL || mc == MC_PUNCT))
2049                                 do
2050                                         posForward();
2051                                 while (pos() < lastpos() && mc == nextMath().mathClass());
2052                 } else if (openable(nextAtom())) {
2053                         InsetMathScript const * n = nextMath().asScriptInset();
2054                         bool to_brace_deco = n && !n->nuc().empty()
2055                                 && n->nuc().back()->lyxCode() == MATH_DECORATION_CODE
2056                                 && n->nuc().back()->mathClass() == MC_OP;
2057                         // single step: try to enter the next inset
2058                         pushBackward(nextMath());
2059                         inset().idxFirst(*this);
2060                         // Make sure the cursor moves directly to an
2061                         // \overbrace or \underbrace inset (bug 2264)
2062                         if (to_brace_deco) {
2063                                 pushBackward(nextMath());
2064                                 inset().idxFirst(*this);
2065                         }
2066                 } else
2067                         posForward();
2068                 return true;
2069         }
2070         if (inset().idxForward(*this))
2071                 return true;
2072         InsetMath const * m = inset().asInsetMath();
2073         bool from_brace_deco = m
2074                 && m->lyxCode() == MATH_DECORATION_CODE
2075                 && m->mathClass() == MC_OP;
2076         // try to pop forwards --- but don't pop out of math! leave that to
2077         // the FINISH lfuns
2078         int s = depth() - 2;
2079         if (s >= 0 && operator[](s).inset().asInsetMath() && popForward()) {
2080                 // Make sure the cursor moves directly to an
2081                 // \overbrace or \underbrace inset (bug 2264)
2082                 bool to_script = inset().asInsetMath()
2083                         && inset().asInsetMath()->asScriptInset();
2084                 return from_brace_deco && to_script ? mathForward(word) : true;
2085         }
2086         return false;
2087 }
2088
2089
2090 bool Cursor::mathBackward(bool word)
2091 {
2092         LASSERT(inMathed(), return false);
2093         if (pos() > 0) {
2094                 if (word) {
2095                         // word: skip a group of insets. See the comment in mathForward.
2096                         MathClass mc = prevMath().mathClass();
2097                         do
2098                                 posBackward();
2099                         while (pos() > 0 && mc == prevMath().mathClass());
2100                         if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2101                                 mc = prevMath().mathClass();
2102                                 do
2103                                         posBackward();
2104                                 while (pos() > 0 && mc == prevMath().mathClass());
2105                         }
2106                 } else if (openable(prevAtom())) {
2107                         InsetMathScript const * p = prevMath().asScriptInset();
2108                         bool to_brace_deco = p && !p->nuc().empty()
2109                                 && p->nuc().back()->lyxCode() == MATH_DECORATION_CODE
2110                                 && p->nuc().back()->mathClass() == MC_OP;
2111                         // single step: try to enter the preceding inset
2112                         posBackward();
2113                         push(nextMath());
2114                         inset().idxLast(*this);
2115                         // Make sure the cursor moves directly to an
2116                         // \overbrace or \underbrace inset (bug 2264)
2117                         if (to_brace_deco) {
2118                                 posBackward();
2119                                 push(nextMath());
2120                                 inset().idxLast(*this);
2121                         }
2122                 } else
2123                         posBackward();
2124                 return true;
2125         }
2126         if (inset().idxBackward(*this))
2127                 return true;
2128         InsetMath const * m = inset().asInsetMath();
2129         bool from_brace_deco = m
2130                 && m->lyxCode() == MATH_DECORATION_CODE
2131                 && m->mathClass() == MC_OP;
2132         // try to pop backwards --- but don't pop out of math! leave that to
2133         // the FINISH lfuns
2134         int s = depth() - 2;
2135         if (s >= 0 && operator[](s).inset().asInsetMath() && popBackward()) {
2136                 // Make sure the cursor moves directly to an
2137                 // \overbrace or \underbrace inset (bug 2264)
2138                 bool to_script = inset().asInsetMath()
2139                         && inset().asInsetMath()->asScriptInset();
2140                 return from_brace_deco && to_script ? mathBackward(word) : true;
2141         }
2142         return false;
2143 }
2144
2145
2146 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2147 {
2148         LASSERT(text(), return false);
2149
2150         // where are we?
2151         int xo = 0;
2152         int yo = 0;
2153         getPos(xo, yo);
2154         xo = beforeDispatchPosX_;
2155
2156         // update the targetX - this is here before the "return false"
2157         // to set a new target which can be used by InsetTexts above
2158         // if we cannot move up/down inside this inset anymore
2159         if (x_target_ == -1)
2160                 setTargetX(xo);
2161         else if (xo - textTargetOffset() != x_target() &&
2162                                          depth() == beforeDispatchCursor_.depth()) {
2163                 // In text mode inside the line (not left or right)
2164                 // possibly set a new target_x, but only if we are
2165                 // somewhere else than the previous target-offset.
2166
2167                 // We want to keep the x-target on subsequent up/down
2168                 // movements that cross beyond the end of short lines.
2169                 // Thus a special handling when the cursor is at the
2170                 // end of line: Use the new x-target only if the old
2171                 // one was before the end of line or the old one was
2172                 // after the beginning of the line
2173                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2174                 bool left;
2175                 bool right;
2176                 if (inRTL) {
2177                         left = pos() == textRow().endpos();
2178                         right = pos() == textRow().pos();
2179                 } else {
2180                         left = pos() == textRow().pos();
2181                         right = pos() == textRow().endpos();
2182                 }
2183                 if ((!left && !right) ||
2184                                 (left && !right && xo < x_target_) ||
2185                                 (!left && right && x_target_ < xo))
2186                         setTargetX(xo);
2187                 else
2188                         xo = targetX();
2189         } else
2190                 xo = targetX();
2191
2192         // first get the current line
2193         TextMetrics & tm = bv_->textMetrics(text());
2194         ParagraphMetrics const & pm = tm.parMetrics(pit());
2195         int row;
2196         if (pos() && boundary())
2197                 row = pm.pos2row(pos() - 1);
2198         else
2199                 row = pm.pos2row(pos());
2200
2201         if (atFirstOrLastRow(up)) {
2202                 // Is there a place for the cursor to go ? If yes, we
2203                 // can execute the DEPM, otherwise we should keep the
2204                 // paragraph to host the cursor.
2205                 Cursor dummy = *this;
2206                 bool valid_destination = false;
2207                 for(; dummy.depth(); dummy.pop())
2208                         if (!dummy.atFirstOrLastRow(up)) {
2209                                 valid_destination = true;
2210                                 break;
2211                         }
2212
2213                 // will a next dispatch follow and if there is a new
2214                 // dispatch will it move the cursor out ?
2215                 if (depth() > 1 && valid_destination) {
2216                         // The cursor hasn't changed yet. This happens when
2217                         // you e.g. move out of an inset. And to give the
2218                         // DEPM the possibility of doing something we must
2219                         // provide it with two different cursors. (Lgb, vfr)
2220                         dummy = *this;
2221                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2222                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2223
2224                         updateNeeded |= bv().checkDepm(dummy, *this);
2225                         updateTextTargetOffset();
2226                         if (updateNeeded)
2227                                 forceBufferUpdate();
2228                 }
2229                 return false;
2230         }
2231
2232         // with and without selection are handled differently
2233         if (!selection()) {
2234                 int yo1 = bv().getPos(*this).y_;
2235                 Cursor old = *this;
2236                 // To next/previous row
2237                 // FIXME: the y position is often guessed wrongly across styles and
2238                 // insets, which leads to weird behaviour.
2239                 if (up)
2240                         tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2241                 else
2242                         tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2243                 x_target_ = old.x_target_;
2244                 clearSelection();
2245
2246                 // This happens when you move out of an inset.
2247                 // And to give the DEPM the possibility of doing
2248                 // something we must provide it with two different
2249                 // cursors. (Lgb)
2250                 Cursor dummy = *this;
2251                 if (dummy == old)
2252                         ++dummy.pos();
2253                 if (bv().checkDepm(dummy, old)) {
2254                         updateNeeded = true;
2255                         // Make sure that cur gets back whatever happened to dummy (Lgb)
2256                         operator=(dummy);
2257                 }
2258                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2259                         posBackward();
2260         } else {
2261                 // if there is a selection, we stay out of any inset,
2262                 // and just jump to the right position:
2263                 Cursor old = *this;
2264                 int next_row = row;
2265                 if (up) {
2266                         if (row > 0) {
2267                                 --next_row;
2268                         } else if (pit() > 0) {
2269                                 --pit();
2270                                 TextMetrics & tm2 = bv_->textMetrics(text());
2271                                 if (!tm2.contains(pit()))
2272                                         tm2.newParMetricsUp();
2273                                 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2274                                 next_row = pmcur.rows().size() - 1;
2275                         }
2276                 } else {
2277                         if (row + 1 < int(pm.rows().size())) {
2278                                 ++next_row;
2279                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
2280                                 ++pit();
2281                                 TextMetrics & tm2 = bv_->textMetrics(text());
2282                                 if (!tm2.contains(pit()))
2283                                         tm2.newParMetricsDown();
2284                                 next_row = 0;
2285                         }
2286                 }
2287
2288                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2289                 bool bound = false;
2290                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2291                 boundary(bound);
2292                 // When selection==false, this is done by TextMetrics::editXY
2293                 setCurrentFont();
2294
2295                 updateNeeded |= bv().checkDepm(*this, old);
2296         }
2297
2298         if (updateNeeded)
2299                 forceBufferUpdate();
2300         updateTextTargetOffset();
2301         return true;
2302 }
2303
2304
2305 void Cursor::handleFont(string const & font)
2306 {
2307         LYXERR(Debug::DEBUG, font);
2308         docstring safe;
2309         if (selection()) {
2310                 macroModeClose();
2311                 safe = cap::grabAndEraseSelection(*this);
2312         }
2313
2314         recordUndoInset();
2315
2316         if (lastpos() != 0) {
2317                 // something left in the cell
2318                 if (pos() == 0) {
2319                         // cursor in first position
2320                         popBackward();
2321                 } else if (pos() == lastpos()) {
2322                         // cursor in last position
2323                         popForward();
2324                 } else {
2325                         // cursor in between. split cell
2326                         MathData::iterator bt = cell().begin();
2327                         MathAtom at = createInsetMath(from_utf8(font), buffer());
2328                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2329                         cell().erase(bt, bt + pos());
2330                         popBackward();
2331                         plainInsert(at);
2332                 }
2333         } else {
2334                 // nothing left in the cell
2335                 popBackward();
2336                 plainErase();
2337                 resetAnchor();
2338         }
2339         insert(safe);
2340 }
2341
2342
2343 void Cursor::undispatched() const
2344 {
2345         disp_.dispatched(false);
2346 }
2347
2348
2349 void Cursor::dispatched() const
2350 {
2351         disp_.dispatched(true);
2352 }
2353
2354
2355 void Cursor::screenUpdateFlags(Update::flags f) const
2356 {
2357         disp_.screenUpdate(f);
2358 }
2359
2360
2361 void Cursor::noScreenUpdate() const
2362 {
2363         disp_.screenUpdate(Update::None);
2364 }
2365
2366
2367 void Cursor::forceBufferUpdate() const
2368 {
2369         disp_.forceBufferUpdate();
2370 }
2371
2372
2373 void Cursor::clearBufferUpdate() const
2374 {
2375         disp_.clearBufferUpdate();
2376 }
2377
2378
2379 bool Cursor::needBufferUpdate() const
2380 {
2381         return disp_.needBufferUpdate();
2382 }
2383
2384
2385 Font Cursor::getFont() const
2386 {
2387         // The logic here should more or less match to the
2388         // Cursor::setCurrentFont logic, i.e. the cursor height should
2389         // give a hint what will happen if a character is entered.
2390         // FIXME: this is not the case, what about removing this method ? (see #10478).
2391
2392         // HACK. far from being perfect...
2393
2394         CursorSlice const & sl = innerTextSlice();
2395         Text const & text = *sl.text();
2396         Paragraph const & par = text.getPar(sl.pit());
2397
2398         // on boundary, so we are really at the character before
2399         pos_type pos = sl.pos();
2400         if (pos > 0 && boundary())
2401                 --pos;
2402
2403         // on space? Take the font before (only for RTL boundary stay)
2404         if (pos > 0) {
2405                 TextMetrics const & tm = bv().textMetrics(&text);
2406                 if (pos == sl.lastpos()
2407                         || (par.isSeparator(pos)
2408                         && !tm.isRTLBoundary(sl.pit(), pos)))
2409                         --pos;
2410         }
2411
2412         // get font at the position
2413         Font font = par.getFont(buffer()->params(), pos,
2414                 text.outerFont(sl.pit()));
2415
2416         return font;
2417 }
2418
2419
2420 void Cursor::sanitize()
2421 {
2422         setBuffer(&bv_->buffer());
2423         CursorData::sanitize();
2424 }
2425
2426
2427 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2428 {
2429         // find inset in common
2430         size_type i;
2431         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2432                 if (&old[i].inset() != &cur[i].inset())
2433                         break;
2434         }
2435
2436         // update words if we just moved to another paragraph
2437         if (i == old.depth() && i == cur.depth()
2438             && !cur.buffer()->isClean()
2439             && cur.inTexted() && old.inTexted()
2440             && cur.pit() != old.pit()) {
2441                 old.paragraph().updateWords();
2442         }
2443
2444         // notify everything on top of the common part in old cursor,
2445         // but stop if the inset claims the cursor to be invalid now
2446         for (size_type j = i; j < old.depth(); ++j) {
2447                 Cursor inset_pos = old;
2448                 inset_pos.cutOff(j);
2449                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2450                         return true;
2451         }
2452
2453         // notify everything on top of the common part in new cursor,
2454         // but stop if the inset claims the cursor to be invalid now
2455         for (; i < cur.depth(); ++i) {
2456                 if (cur[i].inset().notifyCursorEnters(cur))
2457                         return true;
2458         }
2459
2460         return false;
2461 }
2462
2463
2464 void Cursor::setLanguageFromInput()
2465 {
2466         if (!lyxrc.respect_os_kbd_language
2467             || !inTexted()
2468             || paragraph().isPassThru())
2469                 return;
2470         string const & code = theApp()->inputLanguageCode();
2471         Language const * lang = languages.getFromCode(code, buffer()->getLanguages());
2472         if (lang) {
2473                 current_font.setLanguage(lang);
2474                 real_current_font.setLanguage(lang);
2475         } else
2476                 LYXERR0("setLanguageFromCode: unknown language code " << code);
2477 }
2478
2479
2480 void Cursor::setCurrentFont()
2481 {
2482         CursorSlice const & cs = innerTextSlice();
2483         Paragraph const & par = cs.paragraph();
2484         pos_type cpit = cs.pit();
2485         pos_type cpos = cs.pos();
2486         Text const & ctext = *cs.text();
2487         TextMetrics const & tm = bv().textMetrics(&ctext);
2488
2489         // are we behind previous char in fact? -> go to that char
2490         if (cpos > 0 && boundary())
2491                 --cpos;
2492
2493         // find position to take the font from
2494         if (cpos != 0) {
2495                 // paragraph end? -> font of last char
2496                 if (cpos == lastpos())
2497                         --cpos;
2498                 // on space? -> look at the words in front of space
2499                 else if (cpos > 0 && par.isSeparator(cpos))     {
2500                         // abc| def -> font of c
2501                         // abc |[WERBEH], i.e. boundary==true -> font of c
2502                         // abc [WERBEH]| def, font of the space
2503                         if (!tm.isRTLBoundary(cpit, cpos))
2504                                 --cpos;
2505                 }
2506         }
2507
2508         // get font
2509         BufferParams const & bufparams = buffer()->params();
2510         current_font = par.getFontSettings(bufparams, cpos);
2511         real_current_font = tm.displayFont(cpit, cpos);
2512
2513         // set language to input language
2514         setLanguageFromInput();
2515
2516         // special case for paragraph end
2517         if (cs.pos() == lastpos()
2518             && tm.isRTLBoundary(cpit, cs.pos())
2519             && !boundary()) {
2520                 Language const * lang = par.getParLanguage(bufparams);
2521                 current_font.setLanguage(lang);
2522                 current_font.fontInfo().setNumber(FONT_OFF);
2523                 real_current_font.setLanguage(lang);
2524                 real_current_font.fontInfo().setNumber(FONT_OFF);
2525         }
2526
2527         // No language in pass thru situations
2528         if (cs.paragraph().isPassThru()) {
2529                 current_font.setLanguage(latex_language);
2530                 real_current_font.setLanguage(latex_language);
2531         }
2532 }
2533
2534
2535 void Cursor::checkBufferStructure()
2536 {
2537         if (buffer()->isInternal())
2538                 return;
2539
2540         Buffer const * master = buffer()->masterBuffer();
2541         master->tocBackend().updateItem(*this);
2542         if (master != buffer() && !master->hasGuiDelegate())
2543                 // In case the master has no gui associated with it,
2544                 // the TocItem is not updated (part of bug 5699).
2545                 buffer()->tocBackend().updateItem(*this);
2546 }
2547
2548
2549 void Cursor::moveToClosestEdge(int const x, bool const edit)
2550 {
2551         if (Inset const * inset = nextInset()) {
2552                 // stay in front of insets for which we want to open the dialog
2553                 // (e.g. InsetMathSpace).
2554                 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2555                         return;
2556                 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2557                 if (!insetCache.has(inset))
2558                         return;
2559                 int const wid = insetCache.dim(inset).wid;
2560                 Point p = insetCache.xy(inset);
2561                 if (x > p.x_ + (wid + 1) / 2)
2562                         posForward();
2563         }
2564 }
2565
2566
2567 } // namespace lyx