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