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