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