]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Remove obsolete (and false) comment.
[lyx.git] / src / Cursor.cpp
1 /**
2  * \file Cursor.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author Dov Feldstern
9  * \author André Pönitz
10  * \author Stefan Schimanski
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "Buffer.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "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 "ParIterator.h"
31 #include "Row.h"
32 #include "texstream.h"
33 #include "Text.h"
34 #include "TextMetrics.h"
35 #include "TocBackend.h"
36
37 #include "support/debug.h"
38 #include "support/docstream.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/gettext.h"
41 #include "support/lassert.h"
42
43 #include "insets/InsetTabular.h"
44 #include "insets/InsetText.h"
45
46 #include "mathed/InsetMath.h"
47 #include "mathed/InsetMathBrace.h"
48 #include "mathed/InsetMathEnsureMath.h"
49 #include "mathed/InsetMathScript.h"
50 #include "mathed/MacroTable.h"
51 #include "mathed/MathData.h"
52 #include "mathed/MathFactory.h"
53 #include "mathed/InsetMathMacro.h"
54
55 #include "frontends/Application.h"
56
57 #include <sstream>
58 #include <limits>
59 #include <map>
60 #include <algorithm>
61
62 using namespace std;
63
64 namespace lyx {
65
66 namespace {
67
68 // Find position closest to (x, y) in cell given by iter.
69 // Used only in mathed
70 DocIterator bruteFind(Cursor const & c, int x, int y)
71 {
72         double best_dist = numeric_limits<double>::max();
73
74         DocIterator result;
75
76         DocIterator it = c;
77         it.pos() = 0;
78         DocIterator et = c;
79         et.pos() = et.lastpos();
80         for (size_t i = 0;; ++i) {
81                 int xo;
82                 int yo;
83                 Inset const * inset = &it.inset();
84                 CoordCache::Insets const & insetCache = c.bv().coordCache().getInsets();
85
86                 // FIXME: in the case where the inset is not in the cache, this
87                 // means that no part of it is visible on screen. In this case
88                 // we don't do elaborate search and we just return the forwarded
89                 // DocIterator at its beginning.
90                 if (!insetCache.has(inset)) {
91                         it.top().pos() = 0;
92                         return it;
93                 }
94
95                 Point const o = insetCache.xy(inset);
96                 inset->cursorPos(c.bv(), it.top(), c.boundary(), xo, yo);
97                 // Convert to absolute
98                 xo += o.x_;
99                 yo += o.y_;
100                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
101                 // '<=' in order to take the last possible position
102                 // this is important for clicking behind \sum in e.g. '\sum_i a'
103                 LYXERR(Debug::DEBUG, "i: " << i << " d: " << d
104                         << " best: " << best_dist);
105                 if (d <= best_dist) {
106                         best_dist = d;
107                         result = it;
108                 }
109                 if (it == et)
110                         break;
111                 it.forwardPos();
112         }
113         return result;
114 }
115
116
117 } // namespace
118
119
120 //
121 // CursorData
122 //
123
124
125 CursorData::CursorData()
126         : DocIterator(), anchor_(), selection_(false), mark_(false),
127           word_selection_(false), current_font(inherit_font)
128 {}
129
130
131 CursorData::CursorData(Buffer * buffer)
132         : DocIterator(buffer), anchor_(), selection_(false), mark_(false),
133           word_selection_(false), current_font(inherit_font)
134 {}
135
136
137 CursorData::CursorData(DocIterator const & dit)
138         : DocIterator(dit), anchor_(), selection_(false), mark_(false),
139           word_selection_(false), current_font(inherit_font)
140 {}
141
142
143
144
145 ostream & operator<<(ostream & os, CursorData const & cur)
146 {
147         os << "\n cursor:                                | anchor:\n";
148         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
149                 os << " " << cur[i] << " | ";
150                 if (i < cur.anchor_.depth())
151                         os << cur.anchor_[i];
152                 else
153                         os << "-------------------------------";
154                 os << "\n";
155         }
156         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
157                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
158         }
159         os << " selection: " << cur.selection_
160 //         << " x_target: " << cur.x_target_
161            << " boundary: " << cur.boundary() << endl;
162         return os;
163 }
164
165
166 LyXErr & operator<<(LyXErr & os, CursorData const & cur)
167 {
168         os.stream() << cur;
169         return os;
170 }
171
172
173 void CursorData::reset()
174 {
175         clear();
176         push_back(CursorSlice(buffer()->inset()));
177         anchor_ = doc_iterator_begin(buffer());
178         anchor_.clear();
179         new_word_ = doc_iterator_begin(buffer());
180         new_word_.clear();
181         selection_ = false;
182         mark_ = false;
183 }
184
185
186 void CursorData::setCursor(DocIterator const & cur)
187 {
188         DocIterator::operator=(cur);
189 }
190
191
192 void CursorData::setCursorSelectionTo(DocIterator dit)
193 {
194         size_t i = 0;
195         // normalise dit
196         while (i < dit.depth() && i < anchor_.depth() && dit[i] == anchor_[i])
197                 ++i;
198         if (i != dit.depth()) {
199                 // otherwise the cursor is already normal
200                 if (i == anchor_.depth())
201                         // dit is a proper extension of the anchor_
202                         dit.cutOff(i - 1);
203                 else if (i + 1 < dit.depth()) {
204                         // one has dit[i] != anchor_[i] but either dit[i-1] == anchor_[i-1]
205                         // or i == 0. Remove excess.
206                         dit.cutOff(i);
207                         if (dit[i] > anchor_[i])
208                                 // place dit after the inset it was in
209                                 ++dit.pos();
210                 }
211         }
212         setCursor(dit);
213         setSelection();
214 }
215
216
217 void CursorData::setCursorToAnchor()
218 {
219         if (selection()) {
220                 DocIterator normal = anchor_;
221                 while (depth() < normal.depth())
222                         normal.pop_back();
223                 if (depth() < anchor_.depth() && top() <= anchor_[depth() - 1])
224                         ++normal.pos();
225                 setCursor(normal);
226         }
227 }
228
229
230 CursorSlice CursorData::normalAnchor() const
231 {
232         if (!selection())
233                 return top();
234         // LASSERT: There have been several bugs around this code, that seem
235         // to involve failures to reset the anchor. We can at least not crash
236         // in release mode by resetting it ourselves.
237         if (anchor_.depth() < depth()) {
238                 LYXERR0("Cursor is deeper than anchor. PLEASE REPORT.\nCursor is"
239                         << *this);
240                 const_cast<DocIterator &>(anchor_) = *this;
241         }
242
243         CursorSlice normal = anchor_[depth() - 1];
244         if (depth() < anchor_.depth() && top() <= normal) {
245                 // anchor is behind cursor -> move anchor behind the inset
246                 ++normal.pos();
247         }
248         return normal;
249 }
250
251
252 void CursorData::setSelection()
253 {
254         selection(true);
255         if (idx() == normalAnchor().idx() &&
256             pit() == normalAnchor().pit() &&
257             pos() == normalAnchor().pos())
258                 selection(false);
259 }
260
261
262 void CursorData::setSelection(DocIterator const & where, int n)
263 {
264         setCursor(where);
265         selection(true);
266         anchor_ = where;
267         pos() += n;
268 }
269
270
271 void CursorData::resetAnchor()
272 {
273         anchor_ = *this;
274         checkNewWordPosition();
275 }
276
277
278 CursorSlice CursorData::selBegin() const
279 {
280         if (!selection())
281                 return top();
282         return normalAnchor() < top() ? normalAnchor() : top();
283 }
284
285
286 CursorSlice CursorData::selEnd() const
287 {
288         if (!selection())
289                 return top();
290         return normalAnchor() > top() ? normalAnchor() : top();
291 }
292
293
294 DocIterator CursorData::selectionBegin() const
295 {
296         if (!selection())
297                 return *this;
298
299         DocIterator di;
300         // FIXME: This is a work-around for the problem that
301         // CursorSlice doesn't keep track of the boundary.
302         if (normalAnchor() == top())
303                 di = anchor_.boundary() > boundary() ? anchor_ : *this;
304         else
305                 di = normalAnchor() < top() ? anchor_ : *this;
306         di.resize(depth());
307         return di;
308 }
309
310
311 DocIterator CursorData::selectionEnd() const
312 {
313         if (!selection())
314                 return *this;
315
316         DocIterator di;
317         // FIXME: This is a work-around for the problem that
318         // CursorSlice doesn't keep track of the boundary.
319         if (normalAnchor() == top())
320                 di = anchor_.boundary() < boundary() ? anchor_ : *this;
321         else
322                 di = normalAnchor() > top() ? anchor_ : *this;
323
324         if (di.depth() > depth()) {
325                 di.resize(depth());
326                 ++di.pos();
327         }
328         return di;
329 }
330
331
332 namespace {
333
334 docstring parbreak(CursorData const * cur)
335 {
336         if (cur->inset().getLayout().parbreakIgnored())
337                 return docstring();
338         odocstringstream os;
339         os << '\n';
340         // only add blank line if we're not in a ParbreakIsNewline situation
341         if (!cur->inset().getLayout().parbreakIsNewline()
342             && !cur->paragraph().layout().parbreak_is_newline)
343                 os << '\n';
344         return os.str();
345 }
346
347 }
348
349
350 docstring CursorData::selectionAsString(bool const with_label, bool const skipdelete) const
351 {
352         if (!selection())
353                 return docstring();
354
355         if (inMathed())
356                 return cap::grabSelection(*this);
357
358         int label = with_label
359                 ? AS_STR_LABEL | AS_STR_INSETS : AS_STR_INSETS;
360         if (skipdelete)
361                 label = with_label
362                                 ? AS_STR_LABEL | AS_STR_INSETS | AS_STR_SKIPDELETE
363                                 : AS_STR_INSETS | AS_STR_SKIPDELETE;
364
365         idx_type const startidx = selBegin().idx();
366         idx_type const endidx = selEnd().idx();
367         if (startidx != endidx) {
368                 // multicell selection
369                 InsetTabular * table = inset().asInsetTabular();
370                 LASSERT(table, return docstring());
371                 return table->asString(startidx, endidx);
372         }
373
374         ParagraphList const & pars = text()->paragraphs();
375
376         pit_type const startpit = selBegin().pit();
377         pit_type const endpit = selEnd().pit();
378         size_t const startpos = selBegin().pos();
379         size_t const endpos = selEnd().pos();
380
381         if (startpit == endpit)
382                 return pars[startpit].asString(startpos, endpos, label);
383
384         // First paragraph in selection
385         docstring result = pars[startpit].
386                 asString(startpos, pars[startpit].size(), label)
387                 + parbreak(this);
388
389         // The paragraphs in between (if any)
390         for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
391                 Paragraph const & par = pars[pit];
392                 result += par.asString(0, par.size(), label)
393                         + parbreak(this);
394         }
395
396         // Last paragraph in selection
397         result += pars[endpit].asString(0, endpos, label);
398
399         return result;
400 }
401
402
403 void CursorData::info(odocstream & os, bool devel_mode) const
404 {
405         for (int i = 1, n = depth(); i < n; ++i) {
406                 operator[](i).inset().infoize(os);
407                 os << "  ";
408         }
409         if (pos() != 0) {
410                 Inset const * inset = prevInset();
411                 // prevInset() can return 0 in certain case.
412                 if (inset)
413                         prevInset()->infoize2(os);
414         }
415         if (devel_mode) {
416                 InsetMath * math = inset().asInsetMath();
417                 if (math)
418                         os << _(", Inset: ") << math->id();
419                 os << _(", Cell: ") << idx();
420                 os << _(", Position: ") << pos();
421         }
422
423 }
424
425 docstring CursorData::currentState(bool devel_mode) const
426 {
427         if (inMathed()) {
428                 odocstringstream os;
429                 info(os, devel_mode);
430                 return os.str();
431         }
432
433         if (inTexted())
434                 return text()->currentState(*this, devel_mode);
435
436         return docstring();
437 }
438
439
440 void CursorData::markNewWordPosition()
441 {
442         if (lyxrc.spellcheck_continuously && inTexted() && new_word_.empty()) {
443                 FontSpan nw = locateWord(WHOLE_WORD);
444                 if (nw.size() == 1) {
445                         LYXERR(Debug::DEBUG, "start new word: "
446                                 << " par: " << pit()
447                                 << " pos: " << nw.first);
448                         new_word_ = *this;
449                 }
450         }
451 }
452
453
454 void CursorData::clearNewWordPosition()
455 {
456         if (!new_word_.empty()) {
457                 LYXERR(Debug::DEBUG, "clear new word: "
458                         << " par: " << pit()
459                         << " pos: " << pos());
460                 new_word_.resize(0);
461         }
462 }
463
464
465 void CursorData::checkNewWordPosition()
466 {
467         if (!lyxrc.spellcheck_continuously || new_word_.empty())
468                 return ;
469         // forget the position of the current new word if
470         // 1) or the remembered position was "broken"
471         // 2) or the count of nested insets changed
472         // 3) the top-level inset is not the same anymore
473         // 4) the cell index changed
474         // 5) or the paragraph changed
475         // 6) or the cursor pos is out of paragraph bound
476         if (new_word_.fixIfBroken()
477             || depth() != new_word_.depth()
478             || &inset() != &new_word_.inset()
479             || pit() != new_word_.pit()
480             || idx() != new_word_.idx()
481             || new_word_.pos() > new_word_.lastpos())
482                         clearNewWordPosition();
483         else {
484                 FontSpan nw = locateWord(WHOLE_WORD);
485                 if (!nw.empty()) {
486                         FontSpan ow = new_word_.locateWord(WHOLE_WORD);
487                         if (nw.intersect(ow).empty())
488                                 clearNewWordPosition();
489                         else
490                                 LYXERR(Debug::DEBUG, "new word: "
491                                            << " par: " << pit()
492                                            << " pos: " << nw.first << ".." << nw.last);
493                 } else
494                         clearNewWordPosition();
495         }
496 }
497
498
499 void CursorData::clearSelection()
500 {
501         selection(false);
502         setWordSelection(false);
503         setMark(false);
504         resetAnchor();
505 }
506
507
508 int CursorData::countInsetsInSelection(InsetCode const & inset_code)
509 {
510         if (!selection_)
511                 return 0;
512
513         DocIterator from, to;
514         from = selectionBegin();
515         to = selectionEnd();
516
517         int count = 0;
518
519         if (!from.nextInset())      //move to closest inset
520                 from.forwardInset();
521
522         while (!from.empty() && from < to) {
523                 Inset * inset = from.nextInset();
524                 if (!inset)
525                         break;
526                 if (inset->lyxCode() == inset_code)
527                         count ++;
528                 from.forwardInset();
529         }
530         return count;
531 }
532
533
534 bool CursorData::insetInSelection(InsetCode const & inset_code)
535 {
536         if (!selection_)
537                 return false;
538
539         DocIterator from, to;
540         from = selectionBegin();
541         to = selectionEnd();
542
543         if (!from.nextInset())      //move to closest inset
544                 from.forwardInset();
545
546         while (!from.empty() && from < to) {
547                 Inset * inset = from.nextInset();
548                 if (!inset)
549                         break;
550                 if (inset->lyxCode() == inset_code)
551                         return true;
552                 from.forwardInset();
553         }
554         return false;
555 }
556
557
558 bool CursorData::fixIfBroken()
559 {
560         bool const broken_cursor = DocIterator::fixIfBroken();
561         bool const broken_anchor = anchor_.fixIfBroken();
562
563         if (broken_cursor || broken_anchor) {
564                 clearNewWordPosition();
565                 clearSelection();
566                 return true;
567         }
568         return false;
569 }
570
571
572 void CursorData::sanitize()
573 {
574         DocIterator::sanitize();
575         new_word_.sanitize();
576         if (selection())
577                 anchor_.sanitize();
578         else
579                 resetAnchor();
580 }
581
582
583 bool CursorData::undoAction()
584 {
585         if (!buffer()->undo().undoAction(*this))
586                 return false;
587         sanitize();
588         return true;
589 }
590
591
592 bool CursorData::redoAction()
593 {
594         if (!buffer()->undo().redoAction(*this))
595                 return false;
596         sanitize();
597         return true;
598 }
599
600
601 void CursorData::finishUndo() const
602 {
603         buffer()->undo().finishUndo();
604 }
605
606
607 void CursorData::beginUndoGroup() const
608 {
609         buffer()->undo().beginUndoGroup(*this);
610 }
611
612
613 void CursorData::endUndoGroup() const
614 {
615         buffer()->undo().endUndoGroup(*this);
616 }
617
618
619 void CursorData::splitUndoGroup() const
620 {
621         buffer()->undo().splitUndoGroup(*this);
622 }
623
624
625 void CursorData::recordUndo(pit_type from, pit_type to) const
626 {
627         buffer()->undo().recordUndo(*this, from, to);
628 }
629
630
631 void CursorData::recordUndo(pit_type from) const
632 {
633         buffer()->undo().recordUndo(*this, from, pit());
634 }
635
636
637 void CursorData::recordUndo(UndoKind kind) const
638 {
639         buffer()->undo().recordUndo(*this, kind);
640 }
641
642
643 void CursorData::recordUndoInset(Inset const * in) const
644 {
645         buffer()->undo().recordUndoInset(*this, in);
646 }
647
648
649 void CursorData::recordUndoFullBuffer() const
650 {
651         buffer()->undo().recordUndoFullBuffer(*this);
652 }
653
654
655 void CursorData::recordUndoBufferParams() const
656 {
657         buffer()->undo().recordUndoBufferParams(*this);
658 }
659
660
661 void CursorData::recordUndoSelection() const
662 {
663         if (inMathed()) {
664                 if (cap::multipleCellsSelected(*this))
665                         recordUndoInset();
666                 else
667                         recordUndo();
668         } else {
669                 buffer()->undo().recordUndo(*this,
670                         selBegin().pit(), selEnd().pit());
671         }
672 }
673
674
675 int CursorData::currentMode()
676 {
677         LASSERT(!empty(), return Inset::UNDECIDED_MODE);
678         for (int i = depth() - 1; i >= 0; --i) {
679                 int res = operator[](i).inset().currentMode();
680                 bool locked_mode = operator[](i).inset().lockedMode();
681                 // Also return UNDECIDED_MODE when the mode is locked,
682                 // as in this case it is treated the same as TEXT_MODE
683                 if (res != Inset::UNDECIDED_MODE || locked_mode)
684                         return res;
685         }
686         return Inset::TEXT_MODE;
687 }
688
689
690 bool CursorData::confirmDeletion(bool const before) const
691 {
692         if (!selection()) {
693                 if (Inset const * inset = before ? prevInset() : nextInset())
694                         return inset->confirmDeletion();
695         } else {
696                 DocIterator dit = selectionBegin();
697                 CursorSlice const end = selectionEnd().top();
698                 for (; dit.top() < end; dit.top().forwardPos())
699                         if (Inset const * inset = dit.nextInset())
700                                 if (inset->confirmDeletion())
701                                         return true;
702         }
703         return false;
704 }
705
706
707
708 //
709 // Cursor
710 //
711
712
713 // be careful: this is called from the bv's constructor, too, so
714 // bv functions are not yet available!
715 Cursor::Cursor(BufferView & bv)
716         : CursorData(&bv.buffer()), bv_(&bv),
717           x_target_(-1), textTargetOffset_(0),
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         // Is this a function that acts on inset at point?
794         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
795             && nextInset()) {
796                 disp_.dispatched(true);
797                 disp_.screenUpdate(Update::FitCursor | Update::Force);
798                 FuncRequest tmpcmd = cmd;
799                 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
800                         << cmd0 << endl << *this);
801                 nextInset()->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::DEBUG, "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::DEBUG, "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 & p)
904 {
905         push_back(CursorSlice(p));
906         p.setBuffer(*buffer());
907 }
908
909
910 void Cursor::pushBackward(Inset & p)
911 {
912         LASSERT(!empty(), return);
913         //lyxerr << "Entering inset " << t << " front" << endl;
914         push(p);
915         p.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 bool Cursor::selHandle(bool sel)
1386 {
1387         //lyxerr << "Cursor::selHandle" << endl;
1388         if (mark())
1389                 sel = true;
1390         if (sel == selection())
1391                 return false;
1392
1393         if (!sel)
1394                 cap::saveSelection(*this);
1395
1396         resetAnchor();
1397         selection(sel);
1398         return true;
1399 }
1400
1401
1402 bool Cursor::atFirstOrLastRow(bool up)
1403 {
1404         TextMetrics const & tm = bv_->textMetrics(text());
1405         ParagraphMetrics const & pm = tm.parMetrics(pit());
1406
1407         int row;
1408         if (pos() && boundary())
1409                 row = pm.pos2row(pos() - 1);
1410         else
1411                 row = pm.pos2row(pos());
1412
1413         if (up) {
1414                 if (pit() == 0 && row == 0)
1415                         return true;
1416         } else {
1417                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1418                         row + 1 >= int(pm.rows().size()))
1419                         return true;
1420         }
1421         return false;
1422 }
1423
1424
1425 } // namespace lyx
1426
1427
1428 ///////////////////////////////////////////////////////////////////
1429 //
1430 // FIXME: Look here
1431 // The part below is the non-integrated rest of the original math
1432 // cursor. This should be either generalized for texted or moved
1433 // back to mathed (in most cases to InsetMathNest).
1434 //
1435 ///////////////////////////////////////////////////////////////////
1436
1437 #include "mathed/InsetMathChar.h"
1438 #include "mathed/InsetMathGrid.h"
1439 #include "mathed/InsetMathScript.h"
1440 #include "mathed/InsetMathUnknown.h"
1441 #include "mathed/MathFactory.h"
1442 #include "mathed/MathStream.h"
1443 #include "mathed/MathSupport.h"
1444
1445
1446 namespace lyx {
1447
1448 bool Cursor::openable(MathAtom const & t) const
1449 {
1450         if (!t->isActive())
1451                 return false;
1452
1453         if (t->lock())
1454                 return false;
1455
1456         if (!selection())
1457                 return true;
1458
1459         // we can't move into anything new during selection
1460         if (depth() >= realAnchor().depth())
1461                 return false;
1462         if (t.nucleus() != &realAnchor()[depth()].inset())
1463                 return false;
1464
1465         return true;
1466 }
1467
1468
1469 void Cursor::plainErase()
1470 {
1471         cell().erase(pos());
1472 }
1473
1474
1475 void Cursor::plainInsert(MathAtom const & t)
1476 {
1477         cell().insert(pos(), t);
1478         ++pos();
1479         inset().setBuffer(bv_->buffer());
1480         inset().initView();
1481         checkBufferStructure();
1482 }
1483
1484
1485 void Cursor::insert(char_type c)
1486 {
1487         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1488         LASSERT(!empty(), return);
1489         if (inMathed()) {
1490                 cap::selClearOrDel(*this);
1491                 insert(new InsetMathChar(c));
1492         } else {
1493                 text()->insertChar(*this, c);
1494         }
1495 }
1496
1497
1498 void Cursor::insert(docstring const & str)
1499 {
1500         for (char_type c : str)
1501                 insert(c);
1502 }
1503
1504
1505 void Cursor::insert(Inset * inset0)
1506 {
1507         LASSERT(inset0, return);
1508         if (inMathed())
1509                 insert(MathAtom(inset0->asInsetMath()));
1510         else {
1511                 text()->insertInset(*this, inset0);
1512                 inset0->setBuffer(bv_->buffer());
1513                 inset0->initView();
1514                 if (inset0->isLabeled())
1515                         forceBufferUpdate();
1516         }
1517 }
1518
1519
1520 void Cursor::insert(MathAtom const & t)
1521 {
1522         LATTEST(inMathed());
1523         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1524         macroModeClose();
1525         cap::selClearOrDel(*this);
1526         plainInsert(t);
1527 }
1528
1529
1530 void Cursor::insert(MathData const & ar)
1531 {
1532         LATTEST(inMathed());
1533         macroModeClose();
1534         if (selection())
1535                 cap::eraseSelection(*this);
1536         cell().insert(pos(), ar);
1537         pos() += ar.size();
1538         // FIXME audit setBuffer calls
1539         inset().setBuffer(bv_->buffer());
1540 }
1541
1542
1543 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1544 {
1545         LATTEST(inMathed());
1546         MathData ar(buffer());
1547         asArray(t, ar, f);
1548         if (ar.size() == 1 && (enter || selection()))
1549                 niceInsert(ar[0]);
1550         else
1551                 insert(ar);
1552         return ar.size();
1553 }
1554
1555
1556 void Cursor::niceInsert(MathAtom const & t)
1557 {
1558         LATTEST(inMathed());
1559         macroModeClose();
1560         docstring const safe = cap::grabAndEraseSelection(*this);
1561         plainInsert(t);
1562         // If possible, enter the new inset and move the contents of the selection
1563         if (t->isActive()) {
1564                 idx_type const idx = prevMath().asNestInset()->firstIdx();
1565                 MathData ar(buffer());
1566                 asArray(safe, ar);
1567                 prevMath().cell(idx).insert(0, ar);
1568                 editInsertedInset();
1569         } else if (t->asMacro() && !safe.empty()) {
1570                 MathData ar(buffer());
1571                 asArray(safe, ar);
1572                 docstring const name = t->asMacro()->name();
1573                 MacroData const * data = buffer()->getMacro(name);
1574                 if (data && data->numargs() - data->optionals() > 0) {
1575                         plainInsert(MathAtom(new InsetMathBrace(ar)));
1576                         posBackward();
1577                 }
1578         }
1579 }
1580
1581
1582 bool Cursor::backspace(bool const force)
1583 {
1584         if (selection()) {
1585                 cap::eraseSelection(*this);
1586                 return true;
1587         }
1588
1589         if (pos() == 0) {
1590                 // If empty cell, and not part of a big cell
1591                 if (lastpos() == 0 && inset().nargs() == 1) {
1592                         popBackward();
1593                         // Directly delete empty cell: [|[]] => [|]
1594                         if (inMathed()) {
1595                                 plainErase();
1596                                 resetAnchor();
1597                                 return true;
1598                         }
1599                         // [|], can not delete from inside
1600                         return false;
1601                 } else {
1602                         if (inMathed())
1603                                 pullArg();
1604                         else
1605                                 popBackward();
1606                         return true;
1607                 }
1608         }
1609
1610         if (inMacroMode()) {
1611                 InsetMathUnknown * p = activeMacro();
1612                 if (p->name().size() > 1) {
1613                         p->setName(p->name().substr(0, p->name().size() - 1));
1614                         return true;
1615                 }
1616         }
1617
1618         if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1619                 // let's require two backspaces for 'big stuff' and
1620                 // highlight on the first
1621                 resetAnchor();
1622                 selection(true);
1623                 --pos();
1624         } else {
1625                 --pos();
1626                 plainErase();
1627         }
1628         return true;
1629 }
1630
1631
1632 bool Cursor::erase(bool const force)
1633 {
1634         if (inMacroMode())
1635                 return true;
1636
1637         if (selection()) {
1638                 cap::eraseSelection(*this);
1639                 return true;
1640         }
1641
1642         // delete empty cells if possible
1643         if (pos() == lastpos() && inset().idxDelete(idx()))
1644                 return true;
1645
1646         // special behaviour when in last position of cell
1647         if (pos() == lastpos()) {
1648                 bool one_cell = inset().nargs() == 1;
1649                 if (one_cell && lastpos() == 0) {
1650                         popBackward();
1651                         // Directly delete empty cell: [|[]] => [|]
1652                         if (inMathed()) {
1653                                 plainErase();
1654                                 resetAnchor();
1655                                 return true;
1656                         }
1657                         // [|], can not delete from inside
1658                         return false;
1659                 }
1660                 // remove markup
1661                 if (!one_cell)
1662                         inset().idxGlue(idx());
1663                 return true;
1664         }
1665
1666         // 'clever' UI hack: only erase large items if previously slected
1667         if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1668                 resetAnchor();
1669                 selection(true);
1670                 ++pos();
1671         } else {
1672                 plainErase();
1673         }
1674
1675         return true;
1676 }
1677
1678
1679 bool Cursor::up()
1680 {
1681         macroModeClose();
1682         DocIterator save = *this;
1683         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1684         this->dispatch(cmd);
1685         if (disp_.dispatched())
1686                 return true;
1687         setCursor(save);
1688         return false;
1689 }
1690
1691
1692 bool Cursor::down()
1693 {
1694         macroModeClose();
1695         DocIterator save = *this;
1696         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1697         this->dispatch(cmd);
1698         if (disp_.dispatched())
1699                 return true;
1700         setCursor(save);
1701         return false;
1702 }
1703
1704
1705 void Cursor::handleNest(MathAtom const & a)
1706 {
1707         idx_type const idx = a.nucleus()->asNestInset()->firstIdx();
1708         //lyxerr << "Cursor::handleNest: " << idx << endl;
1709         MathAtom t = a;
1710         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(idx));
1711         insert(t);
1712         editInsertedInset();
1713 }
1714
1715
1716 int Cursor::targetX() const
1717 {
1718         if (x_target() != -1)
1719                 return x_target();
1720         int x = 0;
1721         int y = 0;
1722         getPos(x, y);
1723         return x;
1724 }
1725
1726
1727 int Cursor::textTargetOffset() const
1728 {
1729         return textTargetOffset_;
1730 }
1731
1732
1733 void Cursor::setTargetX()
1734 {
1735         int x;
1736         int y;
1737         getPos(x, y);
1738         setTargetX(x);
1739 }
1740
1741
1742 bool Cursor::macroModeClose(bool cancel)
1743 {
1744         if (!inMacroMode())
1745                 return false;
1746         InsetMathUnknown * p = activeMacro();
1747         p->finalize();
1748         MathData selection(buffer());
1749         asArray(p->selection(), selection);
1750         docstring const s = p->name();
1751         --pos();
1752         cell().erase(pos());
1753
1754         // trigger updates of macros, at least, if no full
1755         // updates take place anyway
1756         screenUpdateFlags(Update::Force);
1757
1758         // do nothing if the macro name is empty
1759         if (s == "\\" || cancel) {
1760                 return false;
1761         }
1762
1763         docstring const name = s.substr(1);
1764         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1765         if (in && in->interpretString(*this, s))
1766                 return true;
1767         bool const user_macro = buffer()->getMacro(name, *this, false);
1768         MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1769                                    : createInsetMath(name, buffer());
1770
1771         // try to put argument into macro, if we just inserted a macro
1772         bool macroArg = false;
1773         InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1774         InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1775         if (atomAsMacro) {
1776                 // macros here are still unfolded (in init mode in fact). So
1777                 // we have to resolve the macro here manually and check its arity
1778                 // to put the selection behind it if arity > 0.
1779                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1780                 if (!selection.empty() && data && data->numargs()) {
1781                         macroArg = true;
1782                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1783                 } else
1784                         // non-greedy case. Do not touch the arguments behind
1785                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1786         }
1787
1788         // insert remembered selection into first argument of a non-macro
1789         else if (atomAsNest && atomAsNest->nargs() > 0)
1790                 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1791
1792         MathWordList const & words = mathedWordList();
1793         MathWordList::const_iterator it = words.find(name);
1794         bool keep_mathmode = user_macro
1795                 || (it != words.end() && (it->second.inset == "font"
1796                                           || it->second.inset == "oldfont"
1797                                           || it->second.inset == "mbox"));
1798         bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1799
1800         if (in && in->currentMode() == Inset::TEXT_MODE
1801             && atom.nucleus()->currentMode() == Inset::MATH_MODE
1802             && name != from_ascii("ensuremath") && !ert_macro) {
1803                 MathAtom at(new InsetMathEnsureMath(buffer()));
1804                 at.nucleus()->cell(0).push_back(atom);
1805                 niceInsert(at);
1806                 posForward();
1807         } else if (in && in->currentMode() == Inset::MATH_MODE
1808                    && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1809                    && !keep_mathmode) {
1810                 MathAtom at = createInsetMath("text", buffer());
1811                 at.nucleus()->cell(0).push_back(atom);
1812                 niceInsert(at);
1813                 posForward();
1814         } else
1815                 plainInsert(atom);
1816
1817         // finally put the macro argument behind, if needed
1818         if (macroArg) {
1819                 if (selection.size() > 1 || selection[0]->asScriptInset())
1820                         plainInsert(MathAtom(new InsetMathBrace(selection)));
1821                 else
1822                         insert(selection);
1823         }
1824
1825         return true;
1826 }
1827
1828
1829 bool Cursor::inMacroMode() const
1830 {
1831         if (!inMathed())
1832                 return false;
1833         if (pos() == 0 || cell().empty())
1834                 return false;
1835         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1836         return p && !p->final();
1837 }
1838
1839
1840 InsetMathUnknown * Cursor::activeMacro()
1841 {
1842         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : nullptr;
1843 }
1844
1845
1846 InsetMathUnknown const * Cursor::activeMacro() const
1847 {
1848         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : nullptr;
1849 }
1850
1851
1852 docstring Cursor::macroName()
1853 {
1854         return inMacroMode() ? activeMacro()->name() : docstring();
1855 }
1856
1857
1858 void Cursor::pullArg()
1859 {
1860         // FIXME: Look here
1861         MathData ar = cell();
1862         if (popBackward() && inMathed()) {
1863                 plainErase();
1864                 cell().insert(pos(), ar);
1865                 resetAnchor();
1866         } else {
1867                 //formula()->mutateToText();
1868         }
1869 }
1870
1871
1872 void Cursor::normalize()
1873 {
1874         if (idx() > lastidx()) {
1875                 lyxerr << "this should not really happen - 1: "
1876                        << idx() << ' ' << nargs()
1877                        << " in: " << &inset() << endl;
1878                 idx() = lastidx();
1879         }
1880
1881         if (pos() > lastpos()) {
1882                 lyxerr << "this should not really happen - 2: "
1883                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1884                        << " in atom: '";
1885                 odocstringstream os;
1886                 otexrowstream ots(os);
1887                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1888                 inset().asInsetMath()->write(wi);
1889                 lyxerr << to_utf8(os.str()) << endl;
1890                 pos() = lastpos();
1891         }
1892 }
1893
1894
1895 bool Cursor::upDownInMath(bool up)
1896 {
1897         // Be warned: The 'logic' implemented in this function is highly
1898         // fragile. A distance of one pixel or a '<' vs '<=' _really
1899         // matters. So fiddle around with it only if you think you know
1900         // what you are doing!
1901         int xo = 0;
1902         int yo = 0;
1903         getPos(xo, yo);
1904         xo = beforeDispatchPosX_;
1905
1906         // check if we had something else in mind, if not, this is the future
1907         // target
1908         if (x_target_ == -1)
1909                 setTargetX(xo);
1910         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1911                 // In text mode inside the line (not left or right) possibly set a new target_x,
1912                 // but only if we are somewhere else than the previous target-offset.
1913
1914                 // We want to keep the x-target on subsequent up/down movements
1915                 // that cross beyond the end of short lines. Thus a special
1916                 // handling when the cursor is at the end of line: Use the new
1917                 // x-target only if the old one was before the end of line
1918                 // or the old one was after the beginning of the line
1919                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1920                 bool left;
1921                 bool right;
1922                 if (inRTL) {
1923                         left = pos() == textRow().endpos();
1924                         right = pos() == textRow().pos();
1925                 } else {
1926                         left = pos() == textRow().pos();
1927                         right = pos() == textRow().endpos();
1928                 }
1929                 if ((!left && !right) ||
1930                                 (left && !right && xo < x_target_) ||
1931                                 (!left && right && x_target_ < xo))
1932                         setTargetX(xo);
1933                 else
1934                         xo = targetX();
1935         } else
1936                 xo = targetX();
1937
1938         // try neigbouring script insets
1939         Cursor old = *this;
1940         if (inMathed() && !selection()) {
1941                 // try left
1942                 if (pos() != 0) {
1943                         InsetMathScript const * p = prevAtom()->asScriptInset();
1944                         if (p && p->has(up)) {
1945                                 --pos();
1946                                 push(*const_cast<InsetMathScript*>(p));
1947                                 idx() = p->idxOfScript(up);
1948                                 pos() = lastpos();
1949
1950                                 // we went in the right direction? Otherwise don't jump into the script
1951                                 int x;
1952                                 int y;
1953                                 getPos(x, y);
1954                                 int oy = beforeDispatchPosY_;
1955                                 if ((!up && y <= oy) ||
1956                                                 (up && y >= oy))
1957                                         operator=(old);
1958                                 else
1959                                         return true;
1960                         }
1961                 }
1962
1963                 // try right
1964                 if (pos() != lastpos()) {
1965                         InsetMathScript const * p = nextAtom()->asScriptInset();
1966                         if (p && p->has(up)) {
1967                                 push(*const_cast<InsetMathScript*>(p));
1968                                 idx() = p->idxOfScript(up);
1969                                 pos() = 0;
1970
1971                                 // we went in the right direction? Otherwise don't jump into the script
1972                                 int x;
1973                                 int y;
1974                                 getPos(x, y);
1975                                 int oy = beforeDispatchPosY_;
1976                                 if ((!up && y <= oy) ||
1977                                                 (up && y >= oy))
1978                                         operator=(old);
1979                                 else
1980                                         return true;
1981                         }
1982                 }
1983         }
1984
1985         // try to find an inset that knows better then we,
1986         if (inset().idxUpDown(*this, up)) {
1987                 //lyxerr << "idxUpDown triggered" << endl;
1988                 // try to find best position within this inset
1989                 if (!selection())
1990                         setCursor(bruteFind(*this, xo, yo));
1991                 return true;
1992         }
1993
1994         // any improvement going just out of inset?
1995         if (popBackward() && inMathed()) {
1996                 //lyxerr << "updown: popBackward succeeded" << endl;
1997                 int xnew;
1998                 int ynew;
1999                 int yold = beforeDispatchPosY_;
2000                 getPos(xnew, ynew);
2001                 if (up ? ynew < yold : ynew > yold)
2002                         return true;
2003         }
2004
2005         // no success, we are probably at the document top or bottom
2006         operator=(old);
2007         return false;
2008 }
2009
2010
2011 bool Cursor::mathForward(bool word)
2012 {
2013         LASSERT(inMathed(), return false);
2014         if (pos() < lastpos()) {
2015                 if (word) {
2016                         // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2017                         // match) where X is any math class, B is mathbin, R is mathrel, and
2018                         // P is mathpunct. Make sure that the following remains true:
2019                         //   mathForward(true); mathBackward(true); mathForward(true)
2020                         // is the same as mathForward(true) and
2021                         //   mathBackward(true); mathForward(true); mathBackward(true)
2022                         // is the same as mathBackward(true).
2023                         MathClass mc = nextMath().mathClass();
2024                         do
2025                                 posForward();
2026                         while (pos() < lastpos() && mc == nextMath().mathClass());
2027                         if (pos() < lastpos() &&
2028                             ((mc = nextMath().mathClass()) == MC_BIN ||
2029                              mc == MC_REL || mc == MC_PUNCT))
2030                                 do
2031                                         posForward();
2032                                 while (pos() < lastpos() && mc == nextMath().mathClass());
2033                 } else if (openable(nextAtom())) {
2034                         // single step: try to enter the next inset
2035                         pushBackward(nextMath());
2036                         inset().idxFirst(*this);
2037                 } else
2038                         posForward();
2039                 return true;
2040         }
2041         if (inset().idxForward(*this))
2042                 return true;
2043         // try to pop forwards --- but don't pop out of math! leave that to
2044         // the FINISH lfuns
2045         int s = depth() - 2;
2046         if (s >= 0 && operator[](s).inset().asInsetMath())
2047                 return popForward();
2048         return false;
2049 }
2050
2051
2052 bool Cursor::mathBackward(bool word)
2053 {
2054         LASSERT(inMathed(), return false);
2055         if (pos() > 0) {
2056                 if (word) {
2057                         // word: skip a group of insets. See the comment in mathForward.
2058                         MathClass mc = prevMath().mathClass();
2059                         do
2060                                 posBackward();
2061                         while (pos() > 0 && mc == prevMath().mathClass());
2062                         if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2063                                 mc = prevMath().mathClass();
2064                                 do
2065                                         posBackward();
2066                                 while (pos() > 0 && mc == prevMath().mathClass());
2067                         }
2068                 } else if (openable(prevAtom())) {
2069                         // single step: try to enter the preceding inset
2070                         posBackward();
2071                         push(nextMath());
2072                         inset().idxLast(*this);
2073                 } else
2074                         posBackward();
2075                 return true;
2076         }
2077         if (inset().idxBackward(*this))
2078                 return true;
2079         // try to pop backwards --- but don't pop out of math! leave that to
2080         // the FINISH lfuns
2081         int s = depth() - 2;
2082         if (s >= 0 && operator[](s).inset().asInsetMath())
2083                 return popBackward();
2084         return false;
2085 }
2086
2087
2088 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2089 {
2090         LASSERT(text(), return false);
2091
2092         // where are we?
2093         int xo = 0;
2094         int yo = 0;
2095         getPos(xo, yo);
2096         xo = beforeDispatchPosX_;
2097
2098         // update the targetX - this is here before the "return false"
2099         // to set a new target which can be used by InsetTexts above
2100         // if we cannot move up/down inside this inset anymore
2101         if (x_target_ == -1)
2102                 setTargetX(xo);
2103         else if (xo - textTargetOffset() != x_target() &&
2104                                          depth() == beforeDispatchCursor_.depth()) {
2105                 // In text mode inside the line (not left or right)
2106                 // possibly set a new target_x, but only if we are
2107                 // somewhere else than the previous target-offset.
2108
2109                 // We want to keep the x-target on subsequent up/down
2110                 // movements that cross beyond the end of short lines.
2111                 // Thus a special handling when the cursor is at the
2112                 // end of line: Use the new x-target only if the old
2113                 // one was before the end of line or the old one was
2114                 // after the beginning of the line
2115                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2116                 bool left;
2117                 bool right;
2118                 if (inRTL) {
2119                         left = pos() == textRow().endpos();
2120                         right = pos() == textRow().pos();
2121                 } else {
2122                         left = pos() == textRow().pos();
2123                         right = pos() == textRow().endpos();
2124                 }
2125                 if ((!left && !right) ||
2126                                 (left && !right && xo < x_target_) ||
2127                                 (!left && right && x_target_ < xo))
2128                         setTargetX(xo);
2129                 else
2130                         xo = targetX();
2131         } else
2132                 xo = targetX();
2133
2134         // first get the current line
2135         TextMetrics & tm = bv_->textMetrics(text());
2136         ParagraphMetrics const & pm = tm.parMetrics(pit());
2137         int row;
2138         if (pos() && boundary())
2139                 row = pm.pos2row(pos() - 1);
2140         else
2141                 row = pm.pos2row(pos());
2142
2143         if (atFirstOrLastRow(up)) {
2144                 // Is there a place for the cursor to go ? If yes, we
2145                 // can execute the DEPM, otherwise we should keep the
2146                 // paragraph to host the cursor.
2147                 Cursor dummy = *this;
2148                 bool valid_destination = false;
2149                 for(; dummy.depth(); dummy.pop())
2150                         if (!dummy.atFirstOrLastRow(up)) {
2151                                 valid_destination = true;
2152                                 break;
2153                         }
2154
2155                 // will a next dispatch follow and if there is a new
2156                 // dispatch will it move the cursor out ?
2157                 if (depth() > 1 && valid_destination) {
2158                         // The cursor hasn't changed yet. This happens when
2159                         // you e.g. move out of an inset. And to give the
2160                         // DEPM the possibility of doing something we must
2161                         // provide it with two different cursors. (Lgb, vfr)
2162                         dummy = *this;
2163                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2164                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2165
2166                         updateNeeded |= bv().checkDepm(dummy, *this);
2167                         updateTextTargetOffset();
2168                         if (updateNeeded)
2169                                 forceBufferUpdate();
2170                 }
2171                 return false;
2172         }
2173
2174         // with and without selection are handled differently
2175         if (!selection()) {
2176                 int yo1 = bv().getPos(*this).y_;
2177                 Cursor old = *this;
2178                 // To next/previous row
2179                 // FIXME: the y position is often guessed wrongly across styles and
2180                 // insets, which leads to weird behaviour.
2181                 if (up)
2182                         tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2183                 else
2184                         tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2185                 x_target_ = old.x_target_;
2186                 clearSelection();
2187
2188                 // This happens when you move out of an inset.
2189                 // And to give the DEPM the possibility of doing
2190                 // something we must provide it with two different
2191                 // cursors. (Lgb)
2192                 Cursor dummy = *this;
2193                 if (dummy == old)
2194                         ++dummy.pos();
2195                 if (bv().checkDepm(dummy, old)) {
2196                         updateNeeded = true;
2197                         // Make sure that cur gets back whatever happened to dummy (Lgb)
2198                         operator=(dummy);
2199                 }
2200                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2201                         posBackward();
2202         } else {
2203                 // if there is a selection, we stay out of any inset,
2204                 // and just jump to the right position:
2205                 Cursor old = *this;
2206                 int next_row = row;
2207                 if (up) {
2208                         if (row > 0) {
2209                                 --next_row;
2210                         } else if (pit() > 0) {
2211                                 --pit();
2212                                 TextMetrics & tm2 = bv_->textMetrics(text());
2213                                 if (!tm2.contains(pit()))
2214                                         tm2.newParMetricsUp();
2215                                 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2216                                 next_row = pmcur.rows().size() - 1;
2217                         }
2218                 } else {
2219                         if (row + 1 < int(pm.rows().size())) {
2220                                 ++next_row;
2221                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
2222                                 ++pit();
2223                                 TextMetrics & tm2 = bv_->textMetrics(text());
2224                                 if (!tm2.contains(pit()))
2225                                         tm2.newParMetricsDown();
2226                                 next_row = 0;
2227                         }
2228                 }
2229
2230                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2231                 bool bound = false;
2232                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2233                 boundary(bound);
2234                 // When selection==false, this is done by TextMetrics::editXY
2235                 setCurrentFont();
2236
2237                 updateNeeded |= bv().checkDepm(*this, old);
2238         }
2239
2240         if (updateNeeded)
2241                 forceBufferUpdate();
2242         updateTextTargetOffset();
2243         return true;
2244 }
2245
2246
2247 void Cursor::handleFont(string const & font)
2248 {
2249         LYXERR(Debug::DEBUG, font);
2250         docstring safe;
2251         if (selection()) {
2252                 macroModeClose();
2253                 safe = cap::grabAndEraseSelection(*this);
2254         }
2255
2256         recordUndoInset();
2257
2258         if (lastpos() != 0) {
2259                 // something left in the cell
2260                 if (pos() == 0) {
2261                         // cursor in first position
2262                         popBackward();
2263                 } else if (pos() == lastpos()) {
2264                         // cursor in last position
2265                         popForward();
2266                 } else {
2267                         // cursor in between. split cell
2268                         MathData::iterator bt = cell().begin();
2269                         MathAtom at = createInsetMath(from_utf8(font), buffer());
2270                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2271                         cell().erase(bt, bt + pos());
2272                         popBackward();
2273                         plainInsert(at);
2274                 }
2275         } else {
2276                 // nothing left in the cell
2277                 popBackward();
2278                 plainErase();
2279                 resetAnchor();
2280         }
2281         insert(safe);
2282 }
2283
2284
2285 void Cursor::undispatched() const
2286 {
2287         disp_.dispatched(false);
2288 }
2289
2290
2291 void Cursor::dispatched() const
2292 {
2293         disp_.dispatched(true);
2294 }
2295
2296
2297 void Cursor::screenUpdateFlags(Update::flags f) const
2298 {
2299         disp_.screenUpdate(f);
2300 }
2301
2302
2303 void Cursor::noScreenUpdate() const
2304 {
2305         disp_.screenUpdate(Update::None);
2306 }
2307
2308
2309 void Cursor::forceBufferUpdate() const
2310 {
2311         disp_.forceBufferUpdate();
2312 }
2313
2314
2315 void Cursor::clearBufferUpdate() const
2316 {
2317         disp_.clearBufferUpdate();
2318 }
2319
2320
2321 bool Cursor::needBufferUpdate() const
2322 {
2323         return disp_.needBufferUpdate();
2324 }
2325
2326
2327 Font Cursor::getFont() const
2328 {
2329         // The logic here should more or less match to the
2330         // Cursor::setCurrentFont logic, i.e. the cursor height should
2331         // give a hint what will happen if a character is entered.
2332         // FIXME: this is not the case, what about removing this method ? (see #10478).
2333
2334         // HACK. far from being perfect...
2335
2336         CursorSlice const & sl = innerTextSlice();
2337         Text const & text = *sl.text();
2338         Paragraph const & par = text.getPar(sl.pit());
2339
2340         // on boundary, so we are really at the character before
2341         pos_type pos = sl.pos();
2342         if (pos > 0 && boundary())
2343                 --pos;
2344
2345         // on space? Take the font before (only for RTL boundary stay)
2346         if (pos > 0) {
2347                 TextMetrics const & tm = bv().textMetrics(&text);
2348                 if (pos == sl.lastpos()
2349                         || (par.isSeparator(pos)
2350                         && !tm.isRTLBoundary(sl.pit(), pos)))
2351                         --pos;
2352         }
2353
2354         // get font at the position
2355         Font font = par.getFont(buffer()->params(), pos,
2356                 text.outerFont(sl.pit()));
2357
2358         return font;
2359 }
2360
2361
2362 void Cursor::sanitize()
2363 {
2364         setBuffer(&bv_->buffer());
2365         CursorData::sanitize();
2366 }
2367
2368
2369 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2370 {
2371         // find inset in common
2372         size_type i;
2373         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2374                 if (&old[i].inset() != &cur[i].inset())
2375                         break;
2376         }
2377
2378         // update words if we just moved to another paragraph
2379         if (i == old.depth() && i == cur.depth()
2380             && !cur.buffer()->isClean()
2381             && cur.inTexted() && old.inTexted()
2382             && cur.pit() != old.pit()) {
2383                 old.paragraph().updateWords();
2384         }
2385
2386         // notify everything on top of the common part in old cursor,
2387         // but stop if the inset claims the cursor to be invalid now
2388         for (size_type j = i; j < old.depth(); ++j) {
2389                 Cursor inset_pos = old;
2390                 inset_pos.cutOff(j);
2391                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2392                         return true;
2393         }
2394
2395         // notify everything on top of the common part in new cursor,
2396         // but stop if the inset claims the cursor to be invalid now
2397         for (; i < cur.depth(); ++i) {
2398                 if (cur[i].inset().notifyCursorEnters(cur))
2399                         return true;
2400         }
2401
2402         return false;
2403 }
2404
2405
2406 void Cursor::setLanguageFromInput()
2407 {
2408         if (!lyxrc.respect_os_kbd_language)
2409                 return;
2410         string const & code = theApp()->inputLanguageCode();
2411         Language const * lang = languages.getFromCode(code, buffer()->getLanguages());
2412         if (lang) {
2413                 current_font.setLanguage(lang);
2414                 real_current_font.setLanguage(lang);
2415         } else
2416                 LYXERR0("setLanguageFromCode: unknown language code " << code);
2417 }
2418
2419
2420 void Cursor::setCurrentFont()
2421 {
2422         CursorSlice const & cs = innerTextSlice();
2423         Paragraph const & par = cs.paragraph();
2424         pos_type cpit = cs.pit();
2425         pos_type cpos = cs.pos();
2426         Text const & ctext = *cs.text();
2427         TextMetrics const & tm = bv().textMetrics(&ctext);
2428
2429         // are we behind previous char in fact? -> go to that char
2430         if (cpos > 0 && boundary())
2431                 --cpos;
2432
2433         // find position to take the font from
2434         if (cpos != 0) {
2435                 // paragraph end? -> font of last char
2436                 if (cpos == lastpos())
2437                         --cpos;
2438                 // on space? -> look at the words in front of space
2439                 else if (cpos > 0 && par.isSeparator(cpos))     {
2440                         // abc| def -> font of c
2441                         // abc |[WERBEH], i.e. boundary==true -> font of c
2442                         // abc [WERBEH]| def, font of the space
2443                         if (!tm.isRTLBoundary(cpit, cpos))
2444                                 --cpos;
2445                 }
2446         }
2447
2448         // get font
2449         BufferParams const & bufparams = buffer()->params();
2450         current_font = par.getFontSettings(bufparams, cpos);
2451         real_current_font = tm.displayFont(cpit, cpos);
2452
2453         // set language to input language
2454         setLanguageFromInput();
2455
2456         // special case for paragraph end
2457         if (cs.pos() == lastpos()
2458             && tm.isRTLBoundary(cpit, cs.pos())
2459             && !boundary()) {
2460                 Language const * lang = par.getParLanguage(bufparams);
2461                 current_font.setLanguage(lang);
2462                 current_font.fontInfo().setNumber(FONT_OFF);
2463                 real_current_font.setLanguage(lang);
2464                 real_current_font.fontInfo().setNumber(FONT_OFF);
2465         }
2466 }
2467
2468
2469 void Cursor::checkBufferStructure()
2470 {
2471         Buffer const * master = buffer()->masterBuffer();
2472         master->tocBackend().updateItem(*this);
2473         if (master != buffer() && !master->hasGuiDelegate())
2474                 // In case the master has no gui associated with it,
2475                 // the TocItem is not updated (part of bug 5699).
2476                 buffer()->tocBackend().updateItem(*this);
2477 }
2478
2479
2480 void Cursor::moveToClosestEdge(int const x, bool const edit)
2481 {
2482         if (Inset const * inset = nextInset()) {
2483                 // stay in front of insets for which we want to open the dialog
2484                 // (e.g. InsetMathSpace).
2485                 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2486                         return;
2487                 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2488                 if (!insetCache.has(inset))
2489                         return;
2490                 int const wid = insetCache.dim(inset).wid;
2491                 Point p = insetCache.xy(inset);
2492                 if (x > p.x_ + (wid + 1) / 2)
2493                         posForward();
2494         }
2495 }
2496
2497
2498 } // namespace lyx