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