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