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