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