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