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