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