]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Fix text direction issue for InsetInfo in RTL context
[lyx.git] / src / Cursor.cpp
1 /**
2  * \file Cursor.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Alfredo Braunstein
8  * \author Dov Feldstern
9  * \author André Pönitz
10  * \author Stefan Schimanski
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "Buffer.h"
18 #include "BufferView.h"
19 #include "CoordCache.h"
20 #include "Cursor.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "FuncCode.h"
24 #include "FuncRequest.h"
25 #include "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::isInside(Inset const * p) const
575 {
576         for (size_t i = 0; i != depth(); ++i)
577                 if (&operator[](i).inset() == p)
578                         return true;
579         return false;
580 }
581
582
583 void CursorData::leaveInset(Inset const & inset)
584 {
585         for (size_t i = 0; i != depth(); ++i) {
586                 if (&operator[](i).inset() == &inset) {
587                         resize(i);
588                         return;
589                 }
590         }
591 }
592
593
594 bool CursorData::textUndo()
595 {
596         if (!buffer()->undo().textUndo(*this))
597                 return false;
598         sanitize();
599         return true;
600 }
601
602
603 bool CursorData::textRedo()
604 {
605         if (!buffer()->undo().textRedo(*this))
606                 return false;
607         sanitize();
608         return true;
609 }
610
611
612 void CursorData::finishUndo() const
613 {
614         buffer()->undo().finishUndo();
615 }
616
617
618 void CursorData::beginUndoGroup() const
619 {
620         buffer()->undo().beginUndoGroup(*this);
621 }
622
623
624 void CursorData::endUndoGroup() const
625 {
626         buffer()->undo().endUndoGroup(*this);
627 }
628
629
630 void CursorData::recordUndo(pit_type from, pit_type to) const
631 {
632         buffer()->undo().recordUndo(*this, from, to);
633 }
634
635
636 void CursorData::recordUndo(pit_type from) const
637 {
638         buffer()->undo().recordUndo(*this, from, pit());
639 }
640
641
642 void CursorData::recordUndo(UndoKind kind) const
643 {
644         buffer()->undo().recordUndo(*this, kind);
645 }
646
647
648 void CursorData::recordUndoInset(Inset const * in) const
649 {
650         buffer()->undo().recordUndoInset(*this, in);
651 }
652
653
654 void CursorData::recordUndoFullBuffer() const
655 {
656         buffer()->undo().recordUndoFullBuffer(*this);
657 }
658
659
660 void CursorData::recordUndoBufferParams() const
661 {
662         buffer()->undo().recordUndoBufferParams(*this);
663 }
664
665
666 void CursorData::recordUndoSelection() const
667 {
668         if (inMathed()) {
669                 if (cap::multipleCellsSelected(*this))
670                         recordUndoInset();
671                 else
672                         recordUndo();
673         } else {
674                 buffer()->undo().recordUndo(*this,
675                         selBegin().pit(), selEnd().pit());
676         }
677 }
678
679
680 int CursorData::currentMode()
681 {
682         LASSERT(!empty(), return Inset::UNDECIDED_MODE);
683         for (int i = depth() - 1; i >= 0; --i) {
684                 int res = operator[](i).inset().currentMode();
685                 bool locked_mode = operator[](i).inset().lockedMode();
686                 // Also return UNDECIDED_MODE when the mode is locked,
687                 // as in this case it is treated the same as TEXT_MODE
688                 if (res != Inset::UNDECIDED_MODE || locked_mode)
689                         return res;
690         }
691         return Inset::TEXT_MODE;
692 }
693
694
695 bool CursorData::confirmDeletion(bool const before) const
696 {
697         if (!selection()) {
698                 if (Inset const * inset = before ? prevInset() : nextInset())
699                         return inset->confirmDeletion();
700         } else {
701                 DocIterator dit = selectionBegin();
702                 CursorSlice const end = selectionEnd().top();
703                 for (; dit.top() < end; dit.top().forwardPos())
704                         if (Inset const * inset = dit.nextInset())
705                                 if (inset->confirmDeletion())
706                                         return true;
707         }
708         return false;
709 }
710
711
712
713 //
714 // Cursor
715 //
716
717
718 // be careful: this is called from the bv's constructor, too, so
719 // bv functions are not yet available!
720 Cursor::Cursor(BufferView & bv)
721         : CursorData(&bv.buffer()), bv_(&bv),
722           x_target_(-1), textTargetOffset_(0),
723           beforeDispatchPosX_(0), beforeDispatchPosY_(0)
724 {}
725
726
727 void Cursor::reset()
728 {
729         CursorData::reset();
730         clearTargetX();
731 }
732
733
734 void Cursor::setCursorData(CursorData const & data)
735 {
736         CursorData::operator=(data);
737 }
738
739
740 bool Cursor::getStatus(FuncRequest const & cmd, FuncStatus & status) const
741 {
742         Cursor cur = *this;
743
744         // Try to fix cursor in case it is broken.
745         cur.fixIfBroken();
746
747         // Is this a function that acts on inset at point?
748         Inset * inset = cur.nextInset();
749         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
750             && inset && inset->getStatus(cur, cmd, status))
751                 return true;
752
753         // This is, of course, a mess. Better create a new doc iterator and use
754         // this in Inset::getStatus. This might require an additional
755         // BufferView * arg, though (which should be avoided)
756         //Cursor safe = *this;
757         bool res = false;
758         for ( ; cur.depth(); cur.pop()) {
759                 //lyxerr << "\nCursor::getStatus: cmd: " << cmd << endl << *this << endl;
760                 // LASSERT: Is it safe to continue here, or should we return?
761                 LASSERT(cur.idx() <= cur.lastidx(), /**/);
762                 LASSERT(cur.pit() <= cur.lastpit(), /**/);
763                 LASSERT(cur.pos() <= cur.lastpos(), /**/);
764
765                 // The inset's getStatus() will return 'true' if it made
766                 // a definitive decision on whether it want to handle the
767                 // request or not. The result of this decision is put into
768                 // the 'status' parameter.
769                 if (cur.inset().getStatus(cur, cmd, status)) {
770                         res = true;
771                         break;
772                 }
773         }
774         return res;
775 }
776
777
778 void Cursor::saveBeforeDispatchPosXY()
779 {
780         getPos(beforeDispatchPosX_, beforeDispatchPosY_);
781 }
782
783
784 void Cursor::dispatch(FuncRequest const & cmd0)
785 {
786         LYXERR(Debug::ACTION, "Cursor::dispatch: cmd: " << cmd0 << '\n' << *this);
787         if (empty())
788                 return;
789
790         fixIfBroken();
791         FuncRequest cmd = cmd0;
792         Cursor safe = *this;
793         Cursor old = *this;
794         disp_ = DispatchResult();
795
796         beginUndoGroup();
797
798         // Is this a function that acts on inset at point?
799         if (lyxaction.funcHasFlag(cmd.action(), LyXAction::AtPoint)
800             && nextInset()) {
801                 disp_.dispatched(true);
802                 disp_.screenUpdate(Update::FitCursor | Update::Force);
803                 FuncRequest tmpcmd = cmd;
804                 LYXERR(Debug::DEBUG, "Cursor::dispatch: (AtPoint) cmd: "
805                         << cmd0 << endl << *this);
806                 nextInset()->dispatch(*this, tmpcmd);
807                 if (disp_.dispatched()) {
808                         endUndoGroup();
809                         return;
810                 }
811         }
812
813         // store some values to be used inside of the handlers
814         beforeDispatchCursor_ = *this;
815         for (; depth(); pop(), boundary(false)) {
816                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
817                         << cmd0 << endl << *this);
818
819                 // In any of these cases, the cursor is invalid, and we should
820                 // try to save this document rather than crash.
821                 LBUFERR(pos() <= lastpos());
822                 LBUFERR(idx() <= lastidx());
823                 LBUFERR(pit() <= lastpit());
824
825                 // The common case is 'LFUN handled, need update', so make the
826                 // LFUN handler's life easier by assuming this as default value.
827                 // The handler can reset the update and val flags if necessary.
828                 disp_.screenUpdate(Update::FitCursor | Update::Force);
829                 disp_.dispatched(true);
830                 inset().dispatch(*this, cmd);
831                 if (disp_.dispatched())
832                         break;
833         }
834
835         // it completely to get a 'bomb early' behaviour in case this
836         // object will be used again.
837         if (!disp_.dispatched()) {
838                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
839                 // We might have invalidated the cursor when removing an empty
840                 // paragraph while the cursor could not be moved out the inset
841                 // while we initially thought we could. This might happen when
842                 // a multiline inset becomes an inline inset when the second
843                 // paragraph is removed.
844                 if (safe.pit() > safe.lastpit()) {
845                         safe.pit() = safe.lastpit();
846                         safe.pos() = safe.lastpos();
847                 }
848                 operator=(safe);
849                 disp_.screenUpdate(Update::None);
850                 disp_.dispatched(false);
851         } else {
852                 // restore the previous one because nested Cursor::dispatch calls
853                 // are possible which would change it
854                 beforeDispatchCursor_ = safe.beforeDispatchCursor_;
855         }
856         endUndoGroup();
857
858         // NOTE: The code below has been copied to BufferView::dispatch.
859         // If you need to modify this, please update the other one too.
860
861         // notify insets we just left
862         if (*this != old) {
863                 old.beginUndoGroup();
864                 old.fixIfBroken();
865                 bool badcursor = notifyCursorLeavesOrEnters(old, *this);
866                 if (badcursor) {
867                         fixIfBroken();
868                         bv().resetInlineCompletionPos();
869                 }
870                 old.endUndoGroup();
871         }
872 }
873
874
875 DispatchResult const & Cursor::result() const
876 {
877         return disp_;
878 }
879
880
881 void Cursor::message(docstring const & msg) const
882 {
883         disp_.setMessage(msg);
884 }
885
886
887 void Cursor::errorMessage(docstring const & msg) const
888 {
889         disp_.setMessage(msg);
890         disp_.setError(true);
891 }
892
893
894 BufferView & Cursor::bv() const
895 {
896         LBUFERR(bv_);
897         return *bv_;
898 }
899
900
901 void Cursor::pop()
902 {
903         LBUFERR(depth() >= 1);
904         pop_back();
905 }
906
907
908 void Cursor::push(Inset & p)
909 {
910         push_back(CursorSlice(p));
911         p.setBuffer(*buffer());
912 }
913
914
915 void Cursor::pushBackward(Inset & p)
916 {
917         LASSERT(!empty(), return);
918         //lyxerr << "Entering inset " << t << " front" << endl;
919         push(p);
920         p.idxFirst(*this);
921 }
922
923
924 bool Cursor::popBackward()
925 {
926         LASSERT(!empty(), return false);
927         if (depth() == 1)
928                 return false;
929         pop();
930         return true;
931 }
932
933
934 bool Cursor::popForward()
935 {
936         LASSERT(!empty(), return false);
937         //lyxerr << "Leaving inset from in back" << endl;
938         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
939         if (depth() == 1)
940                 return false;
941         pop();
942         pos() += lastpos() - lp + 1;
943         return true;
944 }
945
946
947 void Cursor::getPos(int & x, int & y) const
948 {
949         Point p = bv().getPos(*this);
950         x = p.x_;
951         y = p.y_;
952 }
953
954
955 Row const & Cursor::textRow() const
956 {
957         CursorSlice const & cs = innerTextSlice();
958         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
959         return pm.getRow(pos(), boundary());
960 }
961
962
963 bool Cursor::posVisRight(bool skip_inset)
964 {
965         Cursor new_cur = *this; // where we will move to
966         pos_type left_pos; // position visually left of current cursor
967         pos_type right_pos; // position visually right of current cursor
968
969         getSurroundingPos(left_pos, right_pos);
970
971         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
972
973         // Are we at an inset?
974         new_cur.pos() = right_pos;
975         new_cur.boundary(false);
976         if (!skip_inset &&
977                 text()->checkAndActivateInsetVisual(new_cur, right_pos >= pos(), false)) {
978                 // we actually move the cursor at the end of this
979                 // function, for now we just keep track of the new
980                 // position in new_cur...
981                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
982         }
983
984         // Are we already at rightmost pos in row?
985         else if (text()->empty() || right_pos == -1) {
986
987                 new_cur = *this;
988                 if (!new_cur.posVisToNewRow(false)) {
989                         LYXERR(Debug::RTL, "not moving!");
990                         return false;
991                 }
992
993                 // we actually move the cursor at the end of this
994                 // function, for now just keep track of the new
995                 // position in new_cur...
996                 LYXERR(Debug::RTL, "right edge, moving: " << int(new_cur.pit()) << ","
997                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
998
999         }
1000         // normal movement to the right
1001         else {
1002                 new_cur = *this;
1003                 // Recall, if the cursor is at position 'x', that
1004                 // means *before* the character at position 'x'. In
1005                 // RTL, "before" means "to the right of", in LTR, "to
1006                 // the left of". So currently our situation is this:
1007                 // the position to our right is 'right_pos' (i.e.,
1008                 // we're currently to the left of 'right_pos'). In
1009                 // order to move to the right, it depends whether or
1010                 // not the character at 'right_pos' is RTL.
1011                 bool const new_pos_is_RTL = paragraph().getFontSettings(
1012                         buffer()->params(), right_pos).isVisibleRightToLeft();
1013                 // If the character at 'right_pos' *is* LTR, then in
1014                 // order to move to the right of it, we need to be
1015                 // *after* 'right_pos', i.e., move to position
1016                 // 'right_pos' + 1.
1017                 if (!new_pos_is_RTL) {
1018                         new_cur.pos() = right_pos + 1;
1019                         // set the boundary to true in two situations:
1020                         if (
1021                         // 1. if new_pos is now lastpos, and we're in
1022                         // an RTL paragraph (this means that we're
1023                         // moving right to the end of an LTR chunk
1024                         // which is at the end of an RTL paragraph);
1025                                 (new_cur.pos() == lastpos()
1026                                  && paragraph().isRTL(buffer()->params()))
1027                         // 2. if the position *after* right_pos is RTL
1028                         // (we want to be *after* right_pos, not
1029                         // before right_pos + 1!)
1030                                 || paragraph().getFontSettings(buffer()->params(),
1031                                                 new_cur.pos()).isVisibleRightToLeft()
1032                         )
1033                                 new_cur.boundary(true);
1034                         else // set the boundary to false
1035                                 new_cur.boundary(false);
1036                 }
1037                 // Otherwise (if the character at position 'right_pos'
1038                 // is RTL), then moving to the right of it is as easy
1039                 // as setting the new position to 'right_pos'.
1040                 else {
1041                         new_cur.pos() = right_pos;
1042                         new_cur.boundary(false);
1043                 }
1044
1045         }
1046
1047         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1048
1049         if (moved) {
1050                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1051                         << (new_cur.boundary() ? " (boundary)" : ""));
1052                 *this = new_cur;
1053         }
1054
1055         return moved;
1056 }
1057
1058
1059 bool Cursor::posVisLeft(bool skip_inset)
1060 {
1061         Cursor new_cur = *this; // where we will move to
1062         pos_type left_pos; // position visually left of current cursor
1063         pos_type right_pos; // position visually right of current cursor
1064
1065         getSurroundingPos(left_pos, right_pos);
1066
1067         LYXERR(Debug::RTL, left_pos <<"|"<< right_pos << " (pos: "<< pos() <<")");
1068
1069         // Are we at an inset?
1070         new_cur.pos() = left_pos;
1071         new_cur.boundary(false);
1072         if (!skip_inset &&
1073                 text()->checkAndActivateInsetVisual(new_cur, left_pos >= pos(), true)) {
1074                 // we actually move the cursor at the end of this
1075                 // function, for now we just keep track of the new
1076                 // position in new_cur...
1077                 LYXERR(Debug::RTL, "entering inset at: " << new_cur.pos());
1078         }
1079
1080         // Are we already at leftmost pos in row?
1081         else if (text()->empty() || left_pos == -1) {
1082
1083                 new_cur = *this;
1084                 if (!new_cur.posVisToNewRow(true)) {
1085                         LYXERR(Debug::RTL, "not moving!");
1086                         return false;
1087                 }
1088
1089                 // we actually move the cursor at the end of this
1090                 // function, for now just keep track of the new
1091                 // position in new_cur...
1092                 LYXERR(Debug::RTL, "left edge, moving: " << int(new_cur.pit()) << ","
1093                         << int(new_cur.pos()) << "," << (new_cur.boundary() ? 1 : 0));
1094
1095         }
1096         // normal movement to the left
1097         else {
1098                 new_cur = *this;
1099                 // Recall, if the cursor is at position 'x', that
1100                 // means *before* the character at position 'x'. In
1101                 // RTL, "before" means "to the right of", in LTR, "to
1102                 // the left of". So currently our situation is this:
1103                 // the position to our left is 'left_pos' (i.e., we're
1104                 // currently to the right of 'left_pos'). In order to
1105                 // move to the left, it depends whether or not the
1106                 // character at 'left_pos' is RTL.
1107                 bool const new_pos_is_RTL = paragraph().getFontSettings(
1108                         buffer()->params(), left_pos).isVisibleRightToLeft();
1109                 // If the character at 'left_pos' *is* RTL, then in
1110                 // order to move to the left of it, we need to be
1111                 // *after* 'left_pos', i.e., move to position
1112                 // 'left_pos' + 1.
1113                 if (new_pos_is_RTL) {
1114                         new_cur.pos() = left_pos + 1;
1115                         // set the boundary to true in two situations:
1116                         if (
1117                         // 1. if new_pos is now lastpos and we're in
1118                         // an LTR paragraph (this means that we're
1119                         // moving left to the end of an RTL chunk
1120                         // which is at the end of an LTR paragraph);
1121                                 (new_cur.pos() == lastpos()
1122                                  && !paragraph().isRTL(buffer()->params()))
1123                         // 2. if the position *after* left_pos is not
1124                         // RTL (we want to be *after* left_pos, not
1125                         // before left_pos + 1!)
1126                                 || !paragraph().getFontSettings(buffer()->params(),
1127                                                 new_cur.pos()).isVisibleRightToLeft()
1128                         )
1129                                 new_cur.boundary(true);
1130                         else // set the boundary to false
1131                                 new_cur.boundary(false);
1132                 }
1133                 // Otherwise (if the character at position 'left_pos'
1134                 // is LTR), then moving to the left of it is as easy
1135                 // as setting the new position to 'left_pos'.
1136                 else {
1137                         new_cur.pos() = left_pos;
1138                         new_cur.boundary(false);
1139                 }
1140
1141         }
1142
1143         bool const moved = new_cur != *this || new_cur.boundary() != boundary();
1144
1145         if (moved) {
1146                 LYXERR(Debug::RTL, "moving to: " << new_cur.pos()
1147                         << (new_cur.boundary() ? " (boundary)" : ""));
1148                 *this = new_cur;
1149         }
1150
1151         return moved;
1152 }
1153
1154
1155 namespace {
1156
1157 // Return true on success
1158 bool findNonVirtual(Row const & row, Row::const_iterator & cit, bool onleft)
1159 {
1160         if (onleft) {
1161                 while (cit != row.begin() && cit->isVirtual())
1162                         --cit;
1163         } else {
1164                 while (cit != row.end() && cit->isVirtual())
1165                         ++cit;
1166         }
1167         return cit != row.end() && !cit->isVirtual();
1168 }
1169
1170 } // namespace
1171
1172 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos) const
1173 {
1174         // by default, we know nothing.
1175         left_pos = -1;
1176         right_pos = -1;
1177
1178         Row const & row = textRow();
1179         double dummy = 0;
1180         Row::const_iterator cit = row.findElement(pos(), boundary(), dummy);
1181         // Handle the case of empty row
1182         if (cit == row.end()) {
1183                 if (row.isRTL())
1184                         right_pos = row.pos();
1185                 else
1186                         left_pos = row.pos() - 1;
1187                 return;
1188         }
1189
1190         // skip virtual elements and exit if no non-virtual one exists
1191         if (!findNonVirtual(row, cit, !cit->isRTL()))
1192                 return;
1193
1194         // if the position is at the left side of the element, we have to
1195         // look at the previous element
1196         if (pos() == cit->left_pos()) {
1197                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1198                            << "), AT LEFT of *cit=" << *cit);
1199                 // this one is easy (see common case below)
1200                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1201                 // at the left of the row
1202                 if (cit == row.begin())
1203                         return;
1204                 --cit;
1205                 if (!findNonVirtual(row, cit, true))
1206                         return;
1207                 // [...[ is the row element, | is cursor position (! with boundary)
1208                 // [ 1 2 [ is a ltr row element with pos=1 and endpos=3
1209                 // ] 2 1] is an rtl row element with pos=1 and endpos=3
1210                 //    [ 1 2 [  [|3 4 [ => (2, 3)
1211                 // or [ 1 2 [  ]!4 3 ] => (2, 4)
1212                 // or ] 2 1 ]  [|3 4 [ => (1, 3)
1213                 // or ] 4 3 ]  ]!2 1 ] => (3, 2)
1214                 left_pos = cit->right_pos() - (cit->isRTL() ? 0 : 1);
1215                 // happens with consecutive row of same direction
1216                 if (left_pos == right_pos) {
1217                         left_pos += cit->isRTL() ? 1 : -1;
1218                 }
1219         }
1220         // same code but with the element at the right
1221         else if (pos() == cit->right_pos()) {
1222                 LYXERR(Debug::RTL, "getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1223                            << "), AT RIGHT of *cit=" << *cit);
1224                 // this one is easy (see common case below)
1225                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1226                 // at the right of the row
1227                 if (cit + 1 == row.end())
1228                         return;
1229                 ++cit;
1230                 if (!findNonVirtual(row, cit, false))
1231                         return;
1232                 //    [ 1 2![  [ 3 4 [ => (2, 3)
1233                 // or [ 1 2![  ] 4 3 ] => (2, 4)
1234                 // or ] 2 1|]  [ 3 4 [ => (1, 3)
1235                 // or ] 4 3|]  ] 2 1 ] => (3, 2)
1236                 right_pos = cit->left_pos() - (cit->isRTL() ? 1 : 0);
1237                 // happens with consecutive row of same direction
1238                 if (right_pos == left_pos)
1239                         right_pos += cit->isRTL() ? -1 : 1;
1240         }
1241         // common case: both positions are inside the row element
1242         else {
1243                 //    [ 1 2|3 [ => (2, 3)
1244                 // or ] 3|2 1 ] => (3, 2)
1245                 left_pos = pos() - (cit->isRTL() ? 0 : 1);
1246                 right_pos = pos() - (cit->isRTL() ? 1 : 0);
1247         }
1248
1249         // Note that debug message does not catch all early returns above
1250         LYXERR(Debug::RTL,"getSurroundingPos(" << pos() << (boundary() ? "b" : "")
1251                    << ") => (" << left_pos << ", " << right_pos <<")");
1252 }
1253
1254
1255 bool Cursor::posVisToNewRow(bool movingLeft)
1256 {
1257         Row const & row = textRow();
1258         bool par_is_LTR = !row.isRTL();
1259
1260         // Inside a table, determining whether to move to the next or
1261         // previous row should be done based on the table's direction.
1262         if (inset().asInsetTabular()) {
1263                 par_is_LTR = !inset().asInsetTabular()->isRightToLeft(*this);
1264                 LYXERR(Debug::RTL, "Inside table! par_is_LTR=" << (par_is_LTR ? 1 : 0));
1265         }
1266
1267         // if moving left in an LTR paragraph or moving right in an
1268         // RTL one, move to previous row
1269         if (par_is_LTR == movingLeft) {
1270                 if (row.pos() == 0) { // we're at first row in paragraph
1271                         if (pit() == 0) // no previous paragraph! don't move
1272                                 return false;
1273                         // move to last pos in previous par
1274                         --pit();
1275                         pos() = lastpos();
1276                         boundary(false);
1277                 } else { // move to previous row in this par
1278                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
1279                         boundary(false);
1280                 }
1281         }
1282         // if moving left in an RTL paragraph or moving right in an
1283         // LTR one, move to next row
1284         else {
1285                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
1286                         if (pit() == lastpit()) // last paragraph! don't move
1287                                 return false;
1288                         // move to first row in next par
1289                         ++pit();
1290                         pos() = 0;
1291                         boundary(false);
1292                 } else { // move to next row in this par
1293                         pos() = row.endpos();
1294                         boundary(false);
1295                 }
1296         }
1297
1298         // make sure we're at left-/right-most pos in new row
1299         posVisToRowExtremity(!movingLeft);
1300
1301         return true;
1302 }
1303
1304
1305 void Cursor::posVisToRowExtremity(bool left)
1306 {
1307         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
1308                 << (boundary() ? 1 : 0));
1309
1310         TextMetrics const & tm = bv_->textMetrics(text());
1311         // Looking for extremities is like clicking on the left or the
1312         // right of the row.
1313         int x = tm.origin().x_ + (left ? 0 : textRow().width());
1314         bool b = false;
1315         pos() = tm.getPosNearX(textRow(), x, b);
1316         boundary(b);
1317
1318         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
1319                 << (boundary() ? 1 : 0));
1320 }
1321
1322
1323 bool Cursor::reverseDirectionNeeded() const
1324 {
1325         /*
1326          * We determine the directions based on the direction of the
1327          * bottom() --- i.e., outermost --- paragraph, because that is
1328          * the only way to achieve consistency of the arrow's movements
1329          * within a paragraph, and thus avoid situations in which the
1330          * cursor gets stuck.
1331          */
1332         return bottom().paragraph().isRTL(bv().buffer().params());
1333 }
1334
1335
1336 void Cursor::setTargetX(int x)
1337 {
1338         x_target_ = x;
1339         textTargetOffset_ = 0;
1340 }
1341
1342
1343 int Cursor::x_target() const
1344 {
1345         return x_target_;
1346 }
1347
1348
1349 void Cursor::clearTargetX()
1350 {
1351         x_target_ = -1;
1352         textTargetOffset_ = 0;
1353 }
1354
1355
1356 void Cursor::updateTextTargetOffset()
1357 {
1358         int x;
1359         int y;
1360         getPos(x, y);
1361         textTargetOffset_ = x - x_target_;
1362 }
1363
1364
1365 bool Cursor::selHandle(bool sel)
1366 {
1367         //lyxerr << "Cursor::selHandle" << endl;
1368         if (mark())
1369                 sel = true;
1370         if (sel == selection())
1371                 return false;
1372
1373         if (!sel)
1374                 cap::saveSelection(*this);
1375
1376         resetAnchor();
1377         selection(sel);
1378         return true;
1379 }
1380
1381
1382 bool Cursor::atFirstOrLastRow(bool up)
1383 {
1384         TextMetrics const & tm = bv_->textMetrics(text());
1385         ParagraphMetrics const & pm = tm.parMetrics(pit());
1386
1387         int row;
1388         if (pos() && boundary())
1389                 row = pm.pos2row(pos() - 1);
1390         else
1391                 row = pm.pos2row(pos());
1392
1393         if (up) {
1394                 if (pit() == 0 && row == 0)
1395                         return true;
1396         } else {
1397                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1398                         row + 1 >= int(pm.rows().size()))
1399                         return true;
1400         }
1401         return false;
1402 }
1403
1404
1405 } // namespace lyx
1406
1407
1408 ///////////////////////////////////////////////////////////////////
1409 //
1410 // FIXME: Look here
1411 // The part below is the non-integrated rest of the original math
1412 // cursor. This should be either generalized for texted or moved
1413 // back to mathed (in most cases to InsetMathNest).
1414 //
1415 ///////////////////////////////////////////////////////////////////
1416
1417 #include "mathed/InsetMathChar.h"
1418 #include "mathed/InsetMathGrid.h"
1419 #include "mathed/InsetMathScript.h"
1420 #include "mathed/InsetMathUnknown.h"
1421 #include "mathed/MathFactory.h"
1422 #include "mathed/MathStream.h"
1423 #include "mathed/MathSupport.h"
1424
1425
1426 namespace lyx {
1427
1428 bool Cursor::openable(MathAtom const & t) const
1429 {
1430         if (!t->isActive())
1431                 return false;
1432
1433         if (t->lock())
1434                 return false;
1435
1436         if (!selection())
1437                 return true;
1438
1439         // we can't move into anything new during selection
1440         if (depth() >= realAnchor().depth())
1441                 return false;
1442         if (t.nucleus() != &realAnchor()[depth()].inset())
1443                 return false;
1444
1445         return true;
1446 }
1447
1448
1449 void Cursor::plainErase()
1450 {
1451         cell().erase(pos());
1452 }
1453
1454
1455 void Cursor::plainInsert(MathAtom const & t)
1456 {
1457         cell().insert(pos(), t);
1458         ++pos();
1459         inset().setBuffer(bv_->buffer());
1460         inset().initView();
1461         checkBufferStructure();
1462 }
1463
1464
1465 void Cursor::insert(char_type c)
1466 {
1467         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1468         LASSERT(!empty(), return);
1469         if (inMathed()) {
1470                 cap::selClearOrDel(*this);
1471                 insert(new InsetMathChar(c));
1472         } else {
1473                 text()->insertChar(*this, c);
1474         }
1475 }
1476
1477
1478 void Cursor::insert(docstring const & str)
1479 {
1480         for (char_type c : str)
1481                 insert(c);
1482 }
1483
1484
1485 void Cursor::insert(Inset * inset0)
1486 {
1487         LASSERT(inset0, return);
1488         if (inMathed())
1489                 insert(MathAtom(inset0->asInsetMath()));
1490         else {
1491                 text()->insertInset(*this, inset0);
1492                 inset0->setBuffer(bv_->buffer());
1493                 inset0->initView();
1494                 if (inset0->isLabeled())
1495                         forceBufferUpdate();
1496         }
1497 }
1498
1499
1500 void Cursor::insert(MathAtom const & t)
1501 {
1502         LATTEST(inMathed());
1503         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1504         macroModeClose();
1505         cap::selClearOrDel(*this);
1506         plainInsert(t);
1507 }
1508
1509
1510 void Cursor::insert(MathData const & ar)
1511 {
1512         LATTEST(inMathed());
1513         macroModeClose();
1514         if (selection())
1515                 cap::eraseSelection(*this);
1516         cell().insert(pos(), ar);
1517         pos() += ar.size();
1518         // FIXME audit setBuffer calls
1519         inset().setBuffer(bv_->buffer());
1520 }
1521
1522
1523 int Cursor::niceInsert(docstring const & t, Parse::flags f, bool enter)
1524 {
1525         LATTEST(inMathed());
1526         MathData ar(buffer());
1527         asArray(t, ar, f);
1528         if (ar.size() == 1 && (enter || selection()))
1529                 niceInsert(ar[0]);
1530         else
1531                 insert(ar);
1532         return ar.size();
1533 }
1534
1535
1536 void Cursor::niceInsert(MathAtom const & t)
1537 {
1538         LATTEST(inMathed());
1539         macroModeClose();
1540         docstring const safe = cap::grabAndEraseSelection(*this);
1541         plainInsert(t);
1542         // If possible, enter the new inset and move the contents of the selection
1543         if (t->isActive()) {
1544                 posBackward();
1545                 // be careful here: don't use 'pushBackward(t)' as this we need to
1546                 // push the clone, not the original
1547                 pushBackward(*nextInset());
1548                 // We may not use niceInsert here (recursion)
1549                 MathData ar(buffer());
1550                 asArray(safe, ar);
1551                 insert(ar);
1552         } else if (t->asMacro() && !safe.empty()) {
1553                 MathData ar(buffer());
1554                 asArray(safe, ar);
1555                 docstring const name = t->asMacro()->name();
1556                 MacroData const * data = buffer()->getMacro(name);
1557                 if (data && data->numargs() - data->optionals() > 0) {
1558                         plainInsert(MathAtom(new InsetMathBrace(ar)));
1559                         posBackward();
1560                 }
1561         }
1562 }
1563
1564
1565 bool Cursor::backspace(bool const force)
1566 {
1567         if (selection()) {
1568                 cap::eraseSelection(*this);
1569                 return true;
1570         }
1571
1572         if (pos() == 0) {
1573                 // If empty cell, and not part of a big cell
1574                 if (lastpos() == 0 && inset().nargs() == 1) {
1575                         popBackward();
1576                         // Directly delete empty cell: [|[]] => [|]
1577                         if (inMathed()) {
1578                                 plainErase();
1579                                 resetAnchor();
1580                                 return true;
1581                         }
1582                         // [|], can not delete from inside
1583                         return false;
1584                 } else {
1585                         if (inMathed())
1586                                 pullArg();
1587                         else
1588                                 popBackward();
1589                         return true;
1590                 }
1591         }
1592
1593         if (inMacroMode()) {
1594                 InsetMathUnknown * p = activeMacro();
1595                 if (p->name().size() > 1) {
1596                         p->setName(p->name().substr(0, p->name().size() - 1));
1597                         return true;
1598                 }
1599         }
1600
1601         if (pos() != 0 && !force && prevAtom()->confirmDeletion()) {
1602                 // let's require two backspaces for 'big stuff' and
1603                 // highlight on the first
1604                 resetAnchor();
1605                 selection(true);
1606                 --pos();
1607         } else {
1608                 --pos();
1609                 plainErase();
1610         }
1611         return true;
1612 }
1613
1614
1615 bool Cursor::erase(bool const force)
1616 {
1617         if (inMacroMode())
1618                 return true;
1619
1620         if (selection()) {
1621                 cap::eraseSelection(*this);
1622                 return true;
1623         }
1624
1625         // delete empty cells if possible
1626         if (pos() == lastpos() && inset().idxDelete(idx()))
1627                 return true;
1628
1629         // special behaviour when in last position of cell
1630         if (pos() == lastpos()) {
1631                 bool one_cell = inset().nargs() == 1;
1632                 if (one_cell && lastpos() == 0) {
1633                         popBackward();
1634                         // Directly delete empty cell: [|[]] => [|]
1635                         if (inMathed()) {
1636                                 plainErase();
1637                                 resetAnchor();
1638                                 return true;
1639                         }
1640                         // [|], can not delete from inside
1641                         return false;
1642                 }
1643                 // remove markup
1644                 if (!one_cell)
1645                         inset().idxGlue(idx());
1646                 return true;
1647         }
1648
1649         // 'clever' UI hack: only erase large items if previously slected
1650         if (pos() != lastpos() && !force && nextAtom()->confirmDeletion()) {
1651                 resetAnchor();
1652                 selection(true);
1653                 ++pos();
1654         } else {
1655                 plainErase();
1656         }
1657
1658         return true;
1659 }
1660
1661
1662 bool Cursor::up()
1663 {
1664         macroModeClose();
1665         DocIterator save = *this;
1666         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1667         this->dispatch(cmd);
1668         if (disp_.dispatched())
1669                 return true;
1670         setCursor(save);
1671         return false;
1672 }
1673
1674
1675 bool Cursor::down()
1676 {
1677         macroModeClose();
1678         DocIterator save = *this;
1679         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1680         this->dispatch(cmd);
1681         if (disp_.dispatched())
1682                 return true;
1683         setCursor(save);
1684         return false;
1685 }
1686
1687
1688 void Cursor::handleNest(MathAtom const & a, int c)
1689 {
1690         //lyxerr << "Cursor::handleNest: " << c << endl;
1691         MathAtom t = a;
1692         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1693         insert(t);
1694         posBackward();
1695         pushBackward(*nextInset());
1696 }
1697
1698
1699 void Cursor::handleNest(MathAtom const & a)
1700 {
1701         handleNest(a, a.nucleus()->asNestInset()->firstIdx());
1702 }
1703
1704
1705 int Cursor::targetX() const
1706 {
1707         if (x_target() != -1)
1708                 return x_target();
1709         int x = 0;
1710         int y = 0;
1711         getPos(x, y);
1712         return x;
1713 }
1714
1715
1716 int Cursor::textTargetOffset() const
1717 {
1718         return textTargetOffset_;
1719 }
1720
1721
1722 void Cursor::setTargetX()
1723 {
1724         int x;
1725         int y;
1726         getPos(x, y);
1727         setTargetX(x);
1728 }
1729
1730
1731 bool Cursor::macroModeClose(bool cancel)
1732 {
1733         if (!inMacroMode())
1734                 return false;
1735         InsetMathUnknown * p = activeMacro();
1736         p->finalize();
1737         MathData selection(buffer());
1738         asArray(p->selection(), selection);
1739         docstring const s = p->name();
1740         --pos();
1741         cell().erase(pos());
1742
1743         // trigger updates of macros, at least, if no full
1744         // updates take place anyway
1745         screenUpdateFlags(Update::Force);
1746
1747         // do nothing if the macro name is empty
1748         if (s == "\\" || cancel) {
1749                 return false;
1750         }
1751
1752         docstring const name = s.substr(1);
1753         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1754         if (in && in->interpretString(*this, s))
1755                 return true;
1756         bool const user_macro = buffer()->getMacro(name, *this, false);
1757         MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1758                                    : createInsetMath(name, buffer());
1759
1760         // try to put argument into macro, if we just inserted a macro
1761         bool macroArg = false;
1762         InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1763         InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1764         if (atomAsMacro) {
1765                 // macros here are still unfolded (in init mode in fact). So
1766                 // we have to resolve the macro here manually and check its arity
1767                 // to put the selection behind it if arity > 0.
1768                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1769                 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1770                         macroArg = true;
1771                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1772                 } else
1773                         // non-greedy case. Do not touch the arguments behind
1774                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1775         }
1776
1777         // insert remembered selection into first argument of a non-macro
1778         else if (atomAsNest && atomAsNest->nargs() > 0)
1779                 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1780
1781         MathWordList const & words = mathedWordList();
1782         MathWordList::const_iterator it = words.find(name);
1783         bool keep_mathmode = user_macro
1784                 || (it != words.end() && (it->second.inset == "font"
1785                                           || it->second.inset == "oldfont"
1786                                           || it->second.inset == "mbox"));
1787         bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1788
1789         if (in && in->currentMode() == Inset::TEXT_MODE
1790             && atom.nucleus()->currentMode() == Inset::MATH_MODE
1791             && name != from_ascii("ensuremath") && !ert_macro) {
1792                 MathAtom at(new InsetMathEnsureMath(buffer()));
1793                 at.nucleus()->cell(0).push_back(atom);
1794                 niceInsert(at);
1795                 posForward();
1796         } else if (in && in->currentMode() == Inset::MATH_MODE
1797                    && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1798                    && !keep_mathmode) {
1799                 MathAtom at = createInsetMath("text", buffer());
1800                 at.nucleus()->cell(0).push_back(atom);
1801                 niceInsert(at);
1802                 posForward();
1803         } else
1804                 plainInsert(atom);
1805
1806         // finally put the macro argument behind, if needed
1807         if (macroArg) {
1808                 if (selection.size() > 1 || selection[0]->asScriptInset())
1809                         plainInsert(MathAtom(new InsetMathBrace(selection)));
1810                 else
1811                         insert(selection);
1812         }
1813
1814         return true;
1815 }
1816
1817
1818 bool Cursor::inMacroMode() const
1819 {
1820         if (!inMathed())
1821                 return false;
1822         if (pos() == 0 || cell().empty())
1823                 return false;
1824         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1825         return p && !p->final();
1826 }
1827
1828
1829 InsetMathUnknown * Cursor::activeMacro()
1830 {
1831         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1832 }
1833
1834
1835 InsetMathUnknown const * Cursor::activeMacro() const
1836 {
1837         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1838 }
1839
1840
1841 docstring Cursor::macroName()
1842 {
1843         return inMacroMode() ? activeMacro()->name() : docstring();
1844 }
1845
1846
1847 void Cursor::pullArg()
1848 {
1849         // FIXME: Look here
1850         MathData ar = cell();
1851         if (popBackward() && inMathed()) {
1852                 plainErase();
1853                 cell().insert(pos(), ar);
1854                 resetAnchor();
1855         } else {
1856                 //formula()->mutateToText();
1857         }
1858 }
1859
1860
1861 void Cursor::normalize()
1862 {
1863         if (idx() > lastidx()) {
1864                 lyxerr << "this should not really happen - 1: "
1865                        << idx() << ' ' << nargs()
1866                        << " in: " << &inset() << endl;
1867                 idx() = lastidx();
1868         }
1869
1870         if (pos() > lastpos()) {
1871                 lyxerr << "this should not really happen - 2: "
1872                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1873                        << " in atom: '";
1874                 odocstringstream os;
1875                 otexrowstream ots(os);
1876                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1877                 inset().asInsetMath()->write(wi);
1878                 lyxerr << to_utf8(os.str()) << endl;
1879                 pos() = lastpos();
1880         }
1881 }
1882
1883
1884 bool Cursor::upDownInMath(bool up)
1885 {
1886         // Be warned: The 'logic' implemented in this function is highly
1887         // fragile. A distance of one pixel or a '<' vs '<=' _really
1888         // matters. So fiddle around with it only if you think you know
1889         // what you are doing!
1890         int xo = 0;
1891         int yo = 0;
1892         getPos(xo, yo);
1893         xo = beforeDispatchPosX_;
1894
1895         // check if we had something else in mind, if not, this is the future
1896         // target
1897         if (x_target_ == -1)
1898                 setTargetX(xo);
1899         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1900                 // In text mode inside the line (not left or right) possibly set a new target_x,
1901                 // but only if we are somewhere else than the previous target-offset.
1902
1903                 // We want to keep the x-target on subsequent up/down movements
1904                 // that cross beyond the end of short lines. Thus a special
1905                 // handling when the cursor is at the end of line: Use the new
1906                 // x-target only if the old one was before the end of line
1907                 // or the old one was after the beginning of the line
1908                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1909                 bool left;
1910                 bool right;
1911                 if (inRTL) {
1912                         left = pos() == textRow().endpos();
1913                         right = pos() == textRow().pos();
1914                 } else {
1915                         left = pos() == textRow().pos();
1916                         right = pos() == textRow().endpos();
1917                 }
1918                 if ((!left && !right) ||
1919                                 (left && !right && xo < x_target_) ||
1920                                 (!left && right && x_target_ < xo))
1921                         setTargetX(xo);
1922                 else
1923                         xo = targetX();
1924         } else
1925                 xo = targetX();
1926
1927         // try neigbouring script insets
1928         Cursor old = *this;
1929         if (inMathed() && !selection()) {
1930                 // try left
1931                 if (pos() != 0) {
1932                         InsetMathScript const * p = prevAtom()->asScriptInset();
1933                         if (p && p->has(up)) {
1934                                 --pos();
1935                                 push(*const_cast<InsetMathScript*>(p));
1936                                 idx() = p->idxOfScript(up);
1937                                 pos() = lastpos();
1938
1939                                 // we went in the right direction? Otherwise don't jump into the script
1940                                 int x;
1941                                 int y;
1942                                 getPos(x, y);
1943                                 int oy = beforeDispatchPosY_;
1944                                 if ((!up && y <= oy) ||
1945                                                 (up && y >= oy))
1946                                         operator=(old);
1947                                 else
1948                                         return true;
1949                         }
1950                 }
1951
1952                 // try right
1953                 if (pos() != lastpos()) {
1954                         InsetMathScript const * p = nextAtom()->asScriptInset();
1955                         if (p && p->has(up)) {
1956                                 push(*const_cast<InsetMathScript*>(p));
1957                                 idx() = p->idxOfScript(up);
1958                                 pos() = 0;
1959
1960                                 // we went in the right direction? Otherwise don't jump into the script
1961                                 int x;
1962                                 int y;
1963                                 getPos(x, y);
1964                                 int oy = beforeDispatchPosY_;
1965                                 if ((!up && y <= oy) ||
1966                                                 (up && y >= oy))
1967                                         operator=(old);
1968                                 else
1969                                         return true;
1970                         }
1971                 }
1972         }
1973
1974         // try to find an inset that knows better then we,
1975         if (inset().idxUpDown(*this, up)) {
1976                 //lyxerr << "idxUpDown triggered" << endl;
1977                 // try to find best position within this inset
1978                 if (!selection())
1979                         setCursor(bruteFind(*this, xo, yo));
1980                 return true;
1981         }
1982
1983         // any improvement going just out of inset?
1984         if (popBackward() && inMathed()) {
1985                 //lyxerr << "updown: popBackward succeeded" << endl;
1986                 int xnew;
1987                 int ynew;
1988                 int yold = beforeDispatchPosY_;
1989                 getPos(xnew, ynew);
1990                 if (up ? ynew < yold : ynew > yold)
1991                         return true;
1992         }
1993
1994         // no success, we are probably at the document top or bottom
1995         operator=(old);
1996         return false;
1997 }
1998
1999
2000 bool Cursor::mathForward(bool word)
2001 {
2002         LASSERT(inMathed(), return false);
2003         if (pos() < lastpos()) {
2004                 if (word) {
2005                         // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
2006                         // match) where X is any math class, B is mathbin, R is mathrel, and
2007                         // P is mathpunct. Make sure that the following remains true:
2008                         //   mathForward(true); mathBackward(true); mathForward(true)
2009                         // is the same as mathForward(true) and
2010                         //   mathBackward(true); mathForward(true); mathBackward(true)
2011                         // is the same as mathBackward(true).
2012                         MathClass mc = nextMath().mathClass();
2013                         do
2014                                 posForward();
2015                         while (pos() < lastpos() && mc == nextMath().mathClass());
2016                         if (pos() < lastpos() &&
2017                             ((mc = nextMath().mathClass()) == MC_BIN ||
2018                              mc == MC_REL || mc == MC_PUNCT))
2019                                 do
2020                                         posForward();
2021                                 while (pos() < lastpos() && mc == nextMath().mathClass());
2022                 } else if (openable(nextAtom())) {
2023                         // single step: try to enter the next inset
2024                         pushBackward(nextMath());
2025                         inset().idxFirst(*this);
2026                 } else
2027                         posForward();
2028                 return true;
2029         }
2030         if (inset().idxForward(*this))
2031                 return true;
2032         // try to pop forwards --- but don't pop out of math! leave that to
2033         // the FINISH lfuns
2034         int s = depth() - 2;
2035         if (s >= 0 && operator[](s).inset().asInsetMath())
2036                 return popForward();
2037         return false;
2038 }
2039
2040
2041 bool Cursor::mathBackward(bool word)
2042 {
2043         LASSERT(inMathed(), return false);
2044         if (pos() > 0) {
2045                 if (word) {
2046                         // word: skip a group of insets. See the comment in mathForward.
2047                         MathClass mc = prevMath().mathClass();
2048                         do
2049                                 posBackward();
2050                         while (pos() > 0 && mc == prevMath().mathClass());
2051                         if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2052                                 mc = prevMath().mathClass();
2053                                 do
2054                                         posBackward();
2055                                 while (pos() > 0 && mc == prevMath().mathClass());
2056                         }
2057                 } else if (openable(prevAtom())) {
2058                         // single step: try to enter the preceding inset
2059                         posBackward();
2060                         push(nextMath());
2061                         inset().idxLast(*this);
2062                 } else
2063                         posBackward();
2064                 return true;
2065         }
2066         if (inset().idxBackward(*this))
2067                 return true;
2068         // try to pop backwards --- but don't pop out of math! leave that to
2069         // the FINISH lfuns
2070         int s = depth() - 2;
2071         if (s >= 0 && operator[](s).inset().asInsetMath())
2072                 return popBackward();
2073         return false;
2074 }
2075
2076
2077 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2078 {
2079         LASSERT(text(), return false);
2080
2081         // where are we?
2082         int xo = 0;
2083         int yo = 0;
2084         getPos(xo, yo);
2085         xo = beforeDispatchPosX_;
2086
2087         // update the targetX - this is here before the "return false"
2088         // to set a new target which can be used by InsetTexts above
2089         // if we cannot move up/down inside this inset anymore
2090         if (x_target_ == -1)
2091                 setTargetX(xo);
2092         else if (xo - textTargetOffset() != x_target() &&
2093                                          depth() == beforeDispatchCursor_.depth()) {
2094                 // In text mode inside the line (not left or right)
2095                 // possibly set a new target_x, but only if we are
2096                 // somewhere else than the previous target-offset.
2097
2098                 // We want to keep the x-target on subsequent up/down
2099                 // movements that cross beyond the end of short lines.
2100                 // Thus a special handling when the cursor is at the
2101                 // end of line: Use the new x-target only if the old
2102                 // one was before the end of line or the old one was
2103                 // after the beginning of the line
2104                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2105                 bool left;
2106                 bool right;
2107                 if (inRTL) {
2108                         left = pos() == textRow().endpos();
2109                         right = pos() == textRow().pos();
2110                 } else {
2111                         left = pos() == textRow().pos();
2112                         right = pos() == textRow().endpos();
2113                 }
2114                 if ((!left && !right) ||
2115                                 (left && !right && xo < x_target_) ||
2116                                 (!left && right && x_target_ < xo))
2117                         setTargetX(xo);
2118                 else
2119                         xo = targetX();
2120         } else
2121                 xo = targetX();
2122
2123         // first get the current line
2124         TextMetrics & tm = bv_->textMetrics(text());
2125         ParagraphMetrics const & pm = tm.parMetrics(pit());
2126         int row;
2127         if (pos() && boundary())
2128                 row = pm.pos2row(pos() - 1);
2129         else
2130                 row = pm.pos2row(pos());
2131
2132         if (atFirstOrLastRow(up)) {
2133                 // Is there a place for the cursor to go ? If yes, we
2134                 // can execute the DEPM, otherwise we should keep the
2135                 // paragraph to host the cursor.
2136                 Cursor dummy = *this;
2137                 bool valid_destination = false;
2138                 for(; dummy.depth(); dummy.pop())
2139                         if (!dummy.atFirstOrLastRow(up)) {
2140                                 valid_destination = true;
2141                                 break;
2142                         }
2143
2144                 // will a next dispatch follow and if there is a new
2145                 // dispatch will it move the cursor out ?
2146                 if (depth() > 1 && valid_destination) {
2147                         // The cursor hasn't changed yet. This happens when
2148                         // you e.g. move out of an inset. And to give the
2149                         // DEPM the possibility of doing something we must
2150                         // provide it with two different cursors. (Lgb, vfr)
2151                         dummy = *this;
2152                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2153                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2154
2155                         updateNeeded |= bv().checkDepm(dummy, *this);
2156                         updateTextTargetOffset();
2157                         if (updateNeeded)
2158                                 forceBufferUpdate();
2159                 }
2160                 return false;
2161         }
2162
2163         // with and without selection are handled differently
2164         if (!selection()) {
2165                 int yo1 = bv().getPos(*this).y_;
2166                 Cursor old = *this;
2167                 // To next/previous row
2168                 // FIXME: the y position is often guessed wrongly across styles and
2169                 // insets, which leads to weird behaviour.
2170                 if (up)
2171                         tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2172                 else
2173                         tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2174                 x_target_ = old.x_target_;
2175                 clearSelection();
2176
2177                 // This happens when you move out of an inset.
2178                 // And to give the DEPM the possibility of doing
2179                 // something we must provide it with two different
2180                 // cursors. (Lgb)
2181                 Cursor dummy = *this;
2182                 if (dummy == old)
2183                         ++dummy.pos();
2184                 if (bv().checkDepm(dummy, old)) {
2185                         updateNeeded = true;
2186                         // Make sure that cur gets back whatever happened to dummy (Lgb)
2187                         operator=(dummy);
2188                 }
2189                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2190                         posBackward();
2191         } else {
2192                 // if there is a selection, we stay out of any inset,
2193                 // and just jump to the right position:
2194                 Cursor old = *this;
2195                 int next_row = row;
2196                 if (up) {
2197                         if (row > 0) {
2198                                 --next_row;
2199                         } else if (pit() > 0) {
2200                                 --pit();
2201                                 TextMetrics & tm2 = bv_->textMetrics(text());
2202                                 if (!tm2.contains(pit()))
2203                                         tm2.newParMetricsUp();
2204                                 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2205                                 next_row = pmcur.rows().size() - 1;
2206                         }
2207                 } else {
2208                         if (row + 1 < int(pm.rows().size())) {
2209                                 ++next_row;
2210                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
2211                                 ++pit();
2212                                 TextMetrics & tm2 = bv_->textMetrics(text());
2213                                 if (!tm2.contains(pit()))
2214                                         tm2.newParMetricsDown();
2215                                 next_row = 0;
2216                         }
2217                 }
2218
2219                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2220                 bool bound = false;
2221                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2222                 boundary(bound);
2223                 // When selection==false, this is done by TextMetrics::editXY
2224                 setCurrentFont();
2225
2226                 updateNeeded |= bv().checkDepm(*this, old);
2227         }
2228
2229         if (updateNeeded)
2230                 forceBufferUpdate();
2231         updateTextTargetOffset();
2232         return true;
2233 }
2234
2235
2236 void Cursor::handleFont(string const & font)
2237 {
2238         LYXERR(Debug::DEBUG, font);
2239         docstring safe;
2240         if (selection()) {
2241                 macroModeClose();
2242                 safe = cap::grabAndEraseSelection(*this);
2243         }
2244
2245         recordUndoInset();
2246
2247         if (lastpos() != 0) {
2248                 // something left in the cell
2249                 if (pos() == 0) {
2250                         // cursor in first position
2251                         popBackward();
2252                 } else if (pos() == lastpos()) {
2253                         // cursor in last position
2254                         popForward();
2255                 } else {
2256                         // cursor in between. split cell
2257                         MathData::iterator bt = cell().begin();
2258                         MathAtom at = createInsetMath(from_utf8(font), buffer());
2259                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2260                         cell().erase(bt, bt + pos());
2261                         popBackward();
2262                         plainInsert(at);
2263                 }
2264         } else {
2265                 // nothing left in the cell
2266                 popBackward();
2267                 plainErase();
2268                 resetAnchor();
2269         }
2270         insert(safe);
2271 }
2272
2273
2274 void Cursor::undispatched() const
2275 {
2276         disp_.dispatched(false);
2277 }
2278
2279
2280 void Cursor::dispatched() const
2281 {
2282         disp_.dispatched(true);
2283 }
2284
2285
2286 void Cursor::screenUpdateFlags(Update::flags f) const
2287 {
2288         disp_.screenUpdate(f);
2289 }
2290
2291
2292 void Cursor::noScreenUpdate() const
2293 {
2294         disp_.screenUpdate(Update::None);
2295 }
2296
2297
2298 void Cursor::forceBufferUpdate() const
2299 {
2300         disp_.forceBufferUpdate();
2301 }
2302
2303
2304 void Cursor::clearBufferUpdate() const
2305 {
2306         disp_.clearBufferUpdate();
2307 }
2308
2309
2310 bool Cursor::needBufferUpdate() const
2311 {
2312         return disp_.needBufferUpdate();
2313 }
2314
2315
2316 Font Cursor::getFont() const
2317 {
2318         // The logic here should more or less match to the
2319         // Cursor::setCurrentFont logic, i.e. the cursor height should
2320         // give a hint what will happen if a character is entered.
2321         // FIXME: this is not the case, what about removing this method ? (see #10478).
2322
2323         // HACK. far from being perfect...
2324
2325         CursorSlice const & sl = innerTextSlice();
2326         Text const & text = *sl.text();
2327         Paragraph const & par = text.getPar(sl.pit());
2328
2329         // on boundary, so we are really at the character before
2330         pos_type pos = sl.pos();
2331         if (pos > 0 && boundary())
2332                 --pos;
2333
2334         // on space? Take the font before (only for RTL boundary stay)
2335         if (pos > 0) {
2336                 TextMetrics const & tm = bv().textMetrics(&text);
2337                 if (pos == sl.lastpos()
2338                         || (par.isSeparator(pos)
2339                         && !tm.isRTLBoundary(sl.pit(), pos)))
2340                         --pos;
2341         }
2342
2343         // get font at the position
2344         Font font = par.getFont(buffer()->params(), pos,
2345                 text.outerFont(sl.pit()));
2346
2347         return font;
2348 }
2349
2350
2351 void Cursor::sanitize()
2352 {
2353         setBuffer(&bv_->buffer());
2354         CursorData::sanitize();
2355 }
2356
2357
2358 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2359 {
2360         // find inset in common
2361         size_type i;
2362         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2363                 if (&old[i].inset() != &cur[i].inset())
2364                         break;
2365         }
2366
2367         // update words if we just moved to another paragraph
2368         if (i == old.depth() && i == cur.depth()
2369             && !cur.buffer()->isClean()
2370             && cur.inTexted() && old.inTexted()
2371             && cur.pit() != old.pit()) {
2372                 old.paragraph().updateWords();
2373         }
2374
2375         // notify everything on top of the common part in old cursor,
2376         // but stop if the inset claims the cursor to be invalid now
2377         for (size_type j = i; j < old.depth(); ++j) {
2378                 Cursor inset_pos = old;
2379                 inset_pos.cutOff(j);
2380                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2381                         return true;
2382         }
2383
2384         // notify everything on top of the common part in new cursor,
2385         // but stop if the inset claims the cursor to be invalid now
2386         for (; i < cur.depth(); ++i) {
2387                 if (cur[i].inset().notifyCursorEnters(cur))
2388                         return true;
2389         }
2390
2391         return false;
2392 }
2393
2394
2395 void Cursor::setCurrentFont()
2396 {
2397         CursorSlice const & cs = innerTextSlice();
2398         Paragraph const & par = cs.paragraph();
2399         pos_type cpit = cs.pit();
2400         pos_type cpos = cs.pos();
2401         Text const & ctext = *cs.text();
2402         TextMetrics const & tm = bv().textMetrics(&ctext);
2403
2404         // are we behind previous char in fact? -> go to that char
2405         if (cpos > 0 && boundary())
2406                 --cpos;
2407
2408         // find position to take the font from
2409         if (cpos != 0) {
2410                 // paragraph end? -> font of last char
2411                 if (cpos == lastpos())
2412                         --cpos;
2413                 // on space? -> look at the words in front of space
2414                 else if (cpos > 0 && par.isSeparator(cpos))     {
2415                         // abc| def -> font of c
2416                         // abc |[WERBEH], i.e. boundary==true -> font of c
2417                         // abc [WERBEH]| def, font of the space
2418                         if (!tm.isRTLBoundary(cpit, cpos))
2419                                 --cpos;
2420                 }
2421         }
2422
2423         // get font
2424         BufferParams const & bufparams = buffer()->params();
2425         current_font = par.getFontSettings(bufparams, cpos);
2426         real_current_font = tm.displayFont(cpit, cpos);
2427
2428         // special case for paragraph end
2429         if (cs.pos() == lastpos()
2430             && tm.isRTLBoundary(cpit, cs.pos())
2431             && !boundary()) {
2432                 Language const * lang = par.getParLanguage(bufparams);
2433                 current_font.setLanguage(lang);
2434                 current_font.fontInfo().setNumber(FONT_OFF);
2435                 real_current_font.setLanguage(lang);
2436                 real_current_font.fontInfo().setNumber(FONT_OFF);
2437         }
2438 }
2439
2440
2441 void Cursor::checkBufferStructure()
2442 {
2443         Buffer const * master = buffer()->masterBuffer();
2444         master->tocBackend().updateItem(*this);
2445         if (master != buffer() && !master->hasGuiDelegate())
2446                 // In case the master has no gui associated with it,
2447                 // the TocItem is not updated (part of bug 5699).
2448                 buffer()->tocBackend().updateItem(*this);
2449
2450         // If the last tracked change of the paragraph has just been
2451         // deleted, then we need to recompute the buffer flag
2452         // tracked_changes_present_.
2453         if (inTexted() && paragraph().isChangeUpdateRequired())
2454                 disp_.forceChangesUpdate();
2455 }
2456
2457
2458 void Cursor::moveToClosestEdge(int const x, bool const edit)
2459 {
2460         if (Inset const * inset = nextInset()) {
2461                 // stay in front of insets for which we want to open the dialog
2462                 // (e.g. InsetMathSpace).
2463                 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2464                         return;
2465                 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2466                 if (!insetCache.has(inset))
2467                         return;
2468                 int const wid = insetCache.dim(inset).wid;
2469                 Point p = insetCache.xy(inset);
2470                 if (x > p.x_ + (wid + 1) / 2)
2471                         posForward();
2472         }
2473 }
2474
2475
2476 } // namespace lyx