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