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