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