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