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