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