]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Const.
[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         // trigger updates of macros, at least, if no full
1694         // updates take place anyway
1695         screenUpdateFlags(Update::Force);
1696
1697         // do nothing if the macro name is empty
1698         if (s == "\\" || cancel) {
1699                 return false;
1700         }
1701
1702         docstring const name = s.substr(1);
1703         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1704         if (in && in->interpretString(*this, s))
1705                 return true;
1706         bool const user_macro = buffer()->getMacro(name, *this, false);
1707         MathAtom atom = user_macro ? MathAtom(new InsetMathMacro(buffer(), name))
1708                                    : createInsetMath(name, buffer());
1709
1710         // try to put argument into macro, if we just inserted a macro
1711         bool macroArg = false;
1712         InsetMathMacro * atomAsMacro = atom.nucleus()->asMacro();
1713         InsetMathNest * atomAsNest = atom.nucleus()->asNestInset();
1714         if (atomAsMacro) {
1715                 // macros here are still unfolded (in init mode in fact). So
1716                 // we have to resolve the macro here manually and check its arity
1717                 // to put the selection behind it if arity > 0.
1718                 MacroData const * data = buffer()->getMacro(atomAsMacro->name());
1719                 if (!selection.empty() && data && data->numargs() - data->optionals() > 0) {
1720                         macroArg = true;
1721                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 1);
1722                 } else
1723                         // non-greedy case. Do not touch the arguments behind
1724                         atomAsMacro->setDisplayMode(InsetMathMacro::DISPLAY_INTERACTIVE_INIT, 0);
1725         }
1726
1727         // insert remembered selection into first argument of a non-macro
1728         else if (atomAsNest && atomAsNest->nargs() > 0)
1729                 atomAsNest->cell(atomAsNest->firstIdx()).append(selection);
1730
1731         MathWordList const & words = mathedWordList();
1732         MathWordList::const_iterator it = words.find(name);
1733         bool keep_mathmode = user_macro
1734                 || (it != words.end() && (it->second.inset == "font"
1735                                           || it->second.inset == "oldfont"
1736                                           || it->second.inset == "mbox"));
1737         bool ert_macro = !user_macro && it == words.end() && atomAsMacro;
1738
1739         if (in && in->currentMode() == Inset::TEXT_MODE
1740             && atom.nucleus()->currentMode() == Inset::MATH_MODE
1741             && name != from_ascii("ensuremath") && !ert_macro) {
1742                 MathAtom at(new InsetMathEnsureMath(buffer()));
1743                 at.nucleus()->cell(0).push_back(atom);
1744                 niceInsert(at);
1745                 posForward();
1746         } else if (in && in->currentMode() == Inset::MATH_MODE
1747                    && atom.nucleus()->currentMode() == Inset::TEXT_MODE
1748                    && !keep_mathmode) {
1749                 MathAtom at = createInsetMath("text", buffer());
1750                 at.nucleus()->cell(0).push_back(atom);
1751                 niceInsert(at);
1752                 posForward();
1753         } else
1754                 plainInsert(atom);
1755
1756         // finally put the macro argument behind, if needed
1757         if (macroArg) {
1758                 if (selection.size() > 1 || selection[0]->asScriptInset())
1759                         plainInsert(MathAtom(new InsetMathBrace(selection)));
1760                 else
1761                         insert(selection);
1762         }
1763
1764         return true;
1765 }
1766
1767
1768 bool Cursor::inMacroMode() const
1769 {
1770         if (!inMathed())
1771                 return false;
1772         if (pos() == 0 || cell().empty())
1773                 return false;
1774         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1775         return p && !p->final();
1776 }
1777
1778
1779 InsetMathUnknown * Cursor::activeMacro()
1780 {
1781         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1782 }
1783
1784
1785 InsetMathUnknown const * Cursor::activeMacro() const
1786 {
1787         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1788 }
1789
1790
1791 docstring Cursor::macroName()
1792 {
1793         return inMacroMode() ? activeMacro()->name() : docstring();
1794 }
1795
1796
1797 void Cursor::pullArg()
1798 {
1799         // FIXME: Look here
1800         MathData ar = cell();
1801         if (popBackward() && inMathed()) {
1802                 plainErase();
1803                 cell().insert(pos(), ar);
1804                 resetAnchor();
1805         } else {
1806                 //formula()->mutateToText();
1807         }
1808 }
1809
1810
1811 void Cursor::normalize()
1812 {
1813         if (idx() > lastidx()) {
1814                 lyxerr << "this should not really happen - 1: "
1815                        << idx() << ' ' << nargs()
1816                        << " in: " << &inset() << endl;
1817                 idx() = lastidx();
1818         }
1819
1820         if (pos() > lastpos()) {
1821                 lyxerr << "this should not really happen - 2: "
1822                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1823                        << " in atom: '";
1824                 odocstringstream os;
1825                 otexrowstream ots(os);
1826                 WriteStream wi(ots, false, true, WriteStream::wsDefault);
1827                 inset().asInsetMath()->write(wi);
1828                 lyxerr << to_utf8(os.str()) << endl;
1829                 pos() = lastpos();
1830         }
1831 }
1832
1833
1834 bool Cursor::upDownInMath(bool up)
1835 {
1836         // Be warned: The 'logic' implemented in this function is highly
1837         // fragile. A distance of one pixel or a '<' vs '<=' _really
1838         // matters. So fiddle around with it only if you think you know
1839         // what you are doing!
1840         int xo = 0;
1841         int yo = 0;
1842         getPos(xo, yo);
1843         xo = beforeDispatchPosX_;
1844
1845         // check if we had something else in mind, if not, this is the future
1846         // target
1847         if (x_target_ == -1)
1848                 setTargetX(xo);
1849         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1850                 // In text mode inside the line (not left or right) possibly set a new target_x,
1851                 // but only if we are somewhere else than the previous target-offset.
1852
1853                 // We want to keep the x-target on subsequent up/down movements
1854                 // that cross beyond the end of short lines. Thus a special
1855                 // handling when the cursor is at the end of line: Use the new
1856                 // x-target only if the old one was before the end of line
1857                 // or the old one was after the beginning of the line
1858                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
1859                 bool left;
1860                 bool right;
1861                 if (inRTL) {
1862                         left = pos() == textRow().endpos();
1863                         right = pos() == textRow().pos();
1864                 } else {
1865                         left = pos() == textRow().pos();
1866                         right = pos() == textRow().endpos();
1867                 }
1868                 if ((!left && !right) ||
1869                                 (left && !right && xo < x_target_) ||
1870                                 (!left && right && x_target_ < xo))
1871                         setTargetX(xo);
1872                 else
1873                         xo = targetX();
1874         } else
1875                 xo = targetX();
1876
1877         // try neigbouring script insets
1878         Cursor old = *this;
1879         if (inMathed() && !selection()) {
1880                 // try left
1881                 if (pos() != 0) {
1882                         InsetMathScript const * p = prevAtom()->asScriptInset();
1883                         if (p && p->has(up)) {
1884                                 --pos();
1885                                 push(*const_cast<InsetMathScript*>(p));
1886                                 idx() = p->idxOfScript(up);
1887                                 pos() = lastpos();
1888
1889                                 // we went in the right direction? Otherwise don't jump into the script
1890                                 int x;
1891                                 int y;
1892                                 getPos(x, y);
1893                                 int oy = beforeDispatchPosY_;
1894                                 if ((!up && y <= oy) ||
1895                                                 (up && y >= oy))
1896                                         operator=(old);
1897                                 else
1898                                         return true;
1899                         }
1900                 }
1901
1902                 // try right
1903                 if (pos() != lastpos()) {
1904                         InsetMathScript const * p = nextAtom()->asScriptInset();
1905                         if (p && p->has(up)) {
1906                                 push(*const_cast<InsetMathScript*>(p));
1907                                 idx() = p->idxOfScript(up);
1908                                 pos() = 0;
1909
1910                                 // we went in the right direction? Otherwise don't jump into the script
1911                                 int x;
1912                                 int y;
1913                                 getPos(x, y);
1914                                 int oy = beforeDispatchPosY_;
1915                                 if ((!up && y <= oy) ||
1916                                                 (up && y >= oy))
1917                                         operator=(old);
1918                                 else
1919                                         return true;
1920                         }
1921                 }
1922         }
1923
1924         // try to find an inset that knows better then we,
1925         if (inset().idxUpDown(*this, up)) {
1926                 //lyxerr << "idxUpDown triggered" << endl;
1927                 // try to find best position within this inset
1928                 if (!selection())
1929                         setCursor(bruteFind(*this, xo, yo));
1930                 return true;
1931         }
1932
1933         // any improvement going just out of inset?
1934         if (popBackward() && inMathed()) {
1935                 //lyxerr << "updown: popBackward succeeded" << endl;
1936                 int xnew;
1937                 int ynew;
1938                 int yold = beforeDispatchPosY_;
1939                 getPos(xnew, ynew);
1940                 if (up ? ynew < yold : ynew > yold)
1941                         return true;
1942         }
1943
1944         // no success, we are probably at the document top or bottom
1945         operator=(old);
1946         return false;
1947 }
1948
1949
1950 bool Cursor::mathForward(bool word)
1951 {
1952         LASSERT(inMathed(), return false);
1953         if (pos() < lastpos()) {
1954                 if (word) {
1955                         // word: skip a group of insets of the form X*(B*|R*|P*) (greedy
1956                         // match) where X is any math class, B is mathbin, R is mathrel, and
1957                         // P is mathpunct. Make sure that the following remains true:
1958                         //   mathForward(true); mathBackward(true); mathForward(true)
1959                         // is the same as mathForward(true) and
1960                         //   mathBackward(true); mathForward(true); mathBackward(true)
1961                         // is the same as mathBackward(true).
1962                         MathClass mc = nextMath().mathClass();
1963                         do
1964                                 posForward();
1965                         while (pos() < lastpos() && mc == nextMath().mathClass());
1966                         if (pos() < lastpos() &&
1967                             ((mc = nextMath().mathClass()) == MC_BIN ||
1968                              mc == MC_REL || mc == MC_PUNCT))
1969                                 do
1970                                         posForward();
1971                                 while (pos() < lastpos() && mc == nextMath().mathClass());
1972                 } else if (openable(nextAtom())) {
1973                         // single step: try to enter the next inset
1974                         pushBackward(nextMath());
1975                         inset().idxFirst(*this);
1976                 } else
1977                         posForward();
1978                 return true;
1979         }
1980         if (inset().idxForward(*this))
1981                 return true;
1982         // try to pop forwards --- but don't pop out of math! leave that to
1983         // the FINISH lfuns
1984         int s = depth() - 2;
1985         if (s >= 0 && operator[](s).inset().asInsetMath())
1986                 return popForward();
1987         return false;
1988 }
1989
1990
1991 bool Cursor::mathBackward(bool word)
1992 {
1993         LASSERT(inMathed(), return false);
1994         if (pos() > 0) {
1995                 if (word) {
1996                         // word: skip a group of insets. See the comment in mathForward.
1997                         MathClass mc = prevMath().mathClass();
1998                         do
1999                                 posBackward();
2000                         while (pos() > 0 && mc == prevMath().mathClass());
2001                         if (pos() > 0 && (mc == MC_BIN || mc == MC_REL || mc == MC_PUNCT)) {
2002                                 mc = prevMath().mathClass();
2003                                 do
2004                                         posBackward();
2005                                 while (pos() > 0 && mc == prevMath().mathClass());
2006                         }
2007                 } else if (openable(prevAtom())) {
2008                         // single step: try to enter the preceding inset
2009                         posBackward();
2010                         push(nextMath());
2011                         inset().idxLast(*this);
2012                 } else
2013                         posBackward();
2014                 return true;
2015         }
2016         if (inset().idxBackward(*this))
2017                 return true;
2018         // try to pop backwards --- but don't pop out of math! leave that to
2019         // the FINISH lfuns
2020         int s = depth() - 2;
2021         if (s >= 0 && operator[](s).inset().asInsetMath())
2022                 return popBackward();
2023         return false;
2024 }
2025
2026
2027 bool Cursor::upDownInText(bool up, bool & updateNeeded)
2028 {
2029         LASSERT(text(), return false);
2030
2031         // where are we?
2032         int xo = 0;
2033         int yo = 0;
2034         getPos(xo, yo);
2035         xo = beforeDispatchPosX_;
2036
2037         // update the targetX - this is here before the "return false"
2038         // to set a new target which can be used by InsetTexts above
2039         // if we cannot move up/down inside this inset anymore
2040         if (x_target_ == -1)
2041                 setTargetX(xo);
2042         else if (xo - textTargetOffset() != x_target() &&
2043                                          depth() == beforeDispatchCursor_.depth()) {
2044                 // In text mode inside the line (not left or right)
2045                 // possibly set a new target_x, but only if we are
2046                 // somewhere else than the previous target-offset.
2047
2048                 // We want to keep the x-target on subsequent up/down
2049                 // movements that cross beyond the end of short lines.
2050                 // Thus a special handling when the cursor is at the
2051                 // end of line: Use the new x-target only if the old
2052                 // one was before the end of line or the old one was
2053                 // after the beginning of the line
2054                 bool inRTL = innerParagraph().isRTL(bv().buffer().params());
2055                 bool left;
2056                 bool right;
2057                 if (inRTL) {
2058                         left = pos() == textRow().endpos();
2059                         right = pos() == textRow().pos();
2060                 } else {
2061                         left = pos() == textRow().pos();
2062                         right = pos() == textRow().endpos();
2063                 }
2064                 if ((!left && !right) ||
2065                                 (left && !right && xo < x_target_) ||
2066                                 (!left && right && x_target_ < xo))
2067                         setTargetX(xo);
2068                 else
2069                         xo = targetX();
2070         } else
2071                 xo = targetX();
2072
2073         // first get the current line
2074         TextMetrics & tm = bv_->textMetrics(text());
2075         ParagraphMetrics const & pm = tm.parMetrics(pit());
2076         int row;
2077         if (pos() && boundary())
2078                 row = pm.pos2row(pos() - 1);
2079         else
2080                 row = pm.pos2row(pos());
2081
2082         if (atFirstOrLastRow(up)) {
2083                 // Is there a place for the cursor to go ? If yes, we
2084                 // can execute the DEPM, otherwise we should keep the
2085                 // paragraph to host the cursor.
2086                 Cursor dummy = *this;
2087                 bool valid_destination = false;
2088                 for(; dummy.depth(); dummy.pop())
2089                         if (!dummy.atFirstOrLastRow(up)) {
2090                                 valid_destination = true;
2091                                 break;
2092                         }
2093
2094                 // will a next dispatch follow and if there is a new
2095                 // dispatch will it move the cursor out ?
2096                 if (depth() > 1 && valid_destination) {
2097                         // The cursor hasn't changed yet. This happens when
2098                         // you e.g. move out of an inset. And to give the
2099                         // DEPM the possibility of doing something we must
2100                         // provide it with two different cursors. (Lgb, vfr)
2101                         dummy = *this;
2102                         dummy.pos() = dummy.pos() == 0 ? dummy.lastpos() : 0;
2103                         dummy.pit() = dummy.pit() == 0 ? dummy.lastpit() : 0;
2104
2105                         updateNeeded |= bv().checkDepm(dummy, *this);
2106                         updateTextTargetOffset();
2107                         if (updateNeeded)
2108                                 forceBufferUpdate();
2109                 }
2110                 return false;
2111         }
2112
2113         // with and without selection are handled differently
2114         if (!selection()) {
2115                 int yo1 = bv().getPos(*this).y_;
2116                 Cursor old = *this;
2117                 // To next/previous row
2118                 // FIXME: the y position is often guessed wrongly across styles and
2119                 // insets, which leads to weird behaviour.
2120                 if (up)
2121                         tm.editXY(*this, xo, yo1 - textRow().ascent() - 1);
2122                 else
2123                         tm.editXY(*this, xo, yo1 + textRow().descent() + 1);
2124                 x_target_ = old.x_target_;
2125                 clearSelection();
2126
2127                 // This happens when you move out of an inset.
2128                 // And to give the DEPM the possibility of doing
2129                 // something we must provide it with two different
2130                 // cursors. (Lgb)
2131                 Cursor dummy = *this;
2132                 if (dummy == old)
2133                         ++dummy.pos();
2134                 if (bv().checkDepm(dummy, old)) {
2135                         updateNeeded = true;
2136                         // Make sure that cur gets back whatever happened to dummy (Lgb)
2137                         operator=(dummy);
2138                 }
2139                 if (inTexted() && pos() && paragraph().isEnvSeparator(pos() - 1))
2140                         posBackward();
2141         } else {
2142                 // if there is a selection, we stay out of any inset,
2143                 // and just jump to the right position:
2144                 Cursor old = *this;
2145                 int next_row = row;
2146                 if (up) {
2147                         if (row > 0) {
2148                                 --next_row;
2149                         } else if (pit() > 0) {
2150                                 --pit();
2151                                 TextMetrics & tm2 = bv_->textMetrics(text());
2152                                 if (!tm2.contains(pit()))
2153                                         tm2.newParMetricsUp();
2154                                 ParagraphMetrics const & pmcur = tm2.parMetrics(pit());
2155                                 next_row = pmcur.rows().size() - 1;
2156                         }
2157                 } else {
2158                         if (row + 1 < int(pm.rows().size())) {
2159                                 ++next_row;
2160                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
2161                                 ++pit();
2162                                 TextMetrics & tm2 = bv_->textMetrics(text());
2163                                 if (!tm2.contains(pit()))
2164                                         tm2.newParMetricsDown();
2165                                 next_row = 0;
2166                         }
2167                 }
2168
2169                 Row const & real_next_row = tm.parMetrics(pit()).rows()[next_row];
2170                 bool bound = false;
2171                 top().pos() = tm.getPosNearX(real_next_row, xo, bound);
2172                 boundary(bound);
2173                 // When selection==false, this is done by TextMetrics::editXY
2174                 setCurrentFont();
2175
2176                 updateNeeded |= bv().checkDepm(*this, old);
2177         }
2178
2179         if (updateNeeded)
2180                 forceBufferUpdate();
2181         updateTextTargetOffset();
2182         return true;
2183 }
2184
2185
2186 void Cursor::handleFont(string const & font)
2187 {
2188         LYXERR(Debug::DEBUG, font);
2189         docstring safe;
2190         if (selection()) {
2191                 macroModeClose();
2192                 safe = cap::grabAndEraseSelection(*this);
2193         }
2194
2195         recordUndoInset();
2196
2197         if (lastpos() != 0) {
2198                 // something left in the cell
2199                 if (pos() == 0) {
2200                         // cursor in first position
2201                         popBackward();
2202                 } else if (pos() == lastpos()) {
2203                         // cursor in last position
2204                         popForward();
2205                 } else {
2206                         // cursor in between. split cell
2207                         MathData::iterator bt = cell().begin();
2208                         MathAtom at = createInsetMath(from_utf8(font), buffer());
2209                         at.nucleus()->cell(0) = MathData(buffer(), bt, bt + pos());
2210                         cell().erase(bt, bt + pos());
2211                         popBackward();
2212                         plainInsert(at);
2213                 }
2214         } else {
2215                 // nothing left in the cell
2216                 popBackward();
2217                 plainErase();
2218                 resetAnchor();
2219         }
2220         insert(safe);
2221 }
2222
2223
2224 void Cursor::undispatched() const
2225 {
2226         disp_.dispatched(false);
2227 }
2228
2229
2230 void Cursor::dispatched() const
2231 {
2232         disp_.dispatched(true);
2233 }
2234
2235
2236 void Cursor::screenUpdateFlags(Update::flags f) const
2237 {
2238         disp_.screenUpdate(f);
2239 }
2240
2241
2242 void Cursor::forceBufferUpdate() const
2243 {
2244         disp_.forceBufferUpdate();
2245 }
2246
2247
2248 void Cursor::clearBufferUpdate() const
2249 {
2250         disp_.clearBufferUpdate();
2251 }
2252
2253
2254 bool Cursor::needBufferUpdate() const
2255 {
2256         return disp_.needBufferUpdate();
2257 }
2258
2259
2260 void Cursor::noScreenUpdate() const
2261 {
2262         disp_.screenUpdate(Update::None);
2263 }
2264
2265
2266 Font Cursor::getFont() const
2267 {
2268         // The logic here should more or less match to the
2269         // Cursor::setCurrentFont logic, i.e. the cursor height should
2270         // give a hint what will happen if a character is entered.
2271         // FIXME: this is not the case, what about removing this method ? (see #10478).
2272
2273         // HACK. far from being perfect...
2274
2275         CursorSlice const & sl = innerTextSlice();
2276         Text const & text = *sl.text();
2277         Paragraph const & par = text.getPar(sl.pit());
2278
2279         // on boundary, so we are really at the character before
2280         pos_type pos = sl.pos();
2281         if (pos > 0 && boundary())
2282                 --pos;
2283
2284         // on space? Take the font before (only for RTL boundary stay)
2285         if (pos > 0) {
2286                 TextMetrics const & tm = bv().textMetrics(&text);
2287                 if (pos == sl.lastpos()
2288                         || (par.isSeparator(pos)
2289                         && !tm.isRTLBoundary(sl.pit(), pos)))
2290                         --pos;
2291         }
2292
2293         // get font at the position
2294         Font font = par.getFont(buffer()->params(), pos,
2295                 text.outerFont(sl.pit()));
2296
2297         return font;
2298 }
2299
2300
2301 void Cursor::sanitize()
2302 {
2303         setBuffer(&bv_->buffer());
2304         CursorData::sanitize();
2305 }
2306
2307
2308 bool notifyCursorLeavesOrEnters(Cursor const & old, Cursor & cur)
2309 {
2310         // find inset in common
2311         size_type i;
2312         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
2313                 if (&old[i].inset() != &cur[i].inset())
2314                         break;
2315         }
2316
2317         // update words if we just moved to another paragraph
2318         if (i == old.depth() && i == cur.depth()
2319             && !cur.buffer()->isClean()
2320             && cur.inTexted() && old.inTexted()
2321             && cur.pit() != old.pit()) {
2322                 old.paragraph().updateWords();
2323         }
2324
2325         // notify everything on top of the common part in old cursor,
2326         // but stop if the inset claims the cursor to be invalid now
2327         for (size_type j = i; j < old.depth(); ++j) {
2328                 Cursor inset_pos = old;
2329                 inset_pos.cutOff(j);
2330                 if (old[j].inset().notifyCursorLeaves(inset_pos, cur))
2331                         return true;
2332         }
2333
2334         // notify everything on top of the common part in new cursor,
2335         // but stop if the inset claims the cursor to be invalid now
2336         for (; i < cur.depth(); ++i) {
2337                 if (cur[i].inset().notifyCursorEnters(cur))
2338                         return true;
2339         }
2340
2341         return false;
2342 }
2343
2344
2345 void Cursor::setCurrentFont()
2346 {
2347         CursorSlice const & cs = innerTextSlice();
2348         Paragraph const & par = cs.paragraph();
2349         pos_type cpit = cs.pit();
2350         pos_type cpos = cs.pos();
2351         Text const & ctext = *cs.text();
2352         TextMetrics const & tm = bv().textMetrics(&ctext);
2353
2354         // are we behind previous char in fact? -> go to that char
2355         if (cpos > 0 && boundary())
2356                 --cpos;
2357
2358         // find position to take the font from
2359         if (cpos != 0) {
2360                 // paragraph end? -> font of last char
2361                 if (cpos == lastpos())
2362                         --cpos;
2363                 // on space? -> look at the words in front of space
2364                 else if (cpos > 0 && par.isSeparator(cpos))     {
2365                         // abc| def -> font of c
2366                         // abc |[WERBEH], i.e. boundary==true -> font of c
2367                         // abc [WERBEH]| def, font of the space
2368                         if (!tm.isRTLBoundary(cpit, cpos))
2369                                 --cpos;
2370                 }
2371         }
2372
2373         // get font
2374         BufferParams const & bufparams = buffer()->params();
2375         current_font = par.getFontSettings(bufparams, cpos);
2376         real_current_font = tm.displayFont(cpit, cpos);
2377
2378         // special case for paragraph end
2379         if (cs.pos() == lastpos()
2380             && tm.isRTLBoundary(cpit, cs.pos())
2381             && !boundary()) {
2382                 Language const * lang = par.getParLanguage(bufparams);
2383                 current_font.setLanguage(lang);
2384                 current_font.fontInfo().setNumber(FONT_OFF);
2385                 real_current_font.setLanguage(lang);
2386                 real_current_font.fontInfo().setNumber(FONT_OFF);
2387         }
2388 }
2389
2390
2391 void Cursor::checkBufferStructure()
2392 {
2393         Buffer const * master = buffer()->masterBuffer();
2394         master->tocBackend().updateItem(*this);
2395         if (master != buffer() && !master->hasGuiDelegate())
2396                 // In case the master has no gui associated with it,
2397                 // the TocItem is not updated (part of bug 5699).
2398                 buffer()->tocBackend().updateItem(*this);
2399
2400         // If the last tracked change of the paragraph has just been
2401         // deleted, then we need to recompute the buffer flag
2402         // tracked_changes_present_.
2403         if (inTexted() && paragraph().isChangeUpdateRequired())
2404                 disp_.forceChangesUpdate();
2405 }
2406
2407
2408 void Cursor::moveToClosestEdge(int const x, bool const edit)
2409 {
2410         if (Inset const * inset = nextInset()) {
2411                 // stay in front of insets for which we want to open the dialog
2412                 // (e.g. InsetMathSpace).
2413                 if (edit && (inset->hasSettings() || !inset->contextMenuName().empty()))
2414                         return;
2415                 CoordCache::Insets const & insetCache = bv().coordCache().getInsets();
2416                 if (!insetCache.has(inset))
2417                         return;
2418                 int const wid = insetCache.dim(inset).wid;
2419                 Point p = insetCache.xy(inset);
2420                 if (x > p.x_ + (wid + 1) / 2)
2421                         posForward();
2422         }
2423 }
2424
2425
2426 } // namespace lyx