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