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