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