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