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