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