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