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