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