]> git.lyx.org Git - lyx.git/blob - src/Cursor.cpp
Fix bug http://bugzilla.lyx.org/show_bug.cgi?id=4599
[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 "FuncRequest.h"
27 #include "Language.h"
28 #include "lfuns.h"
29 #include "LyXFunc.h" // only for setMessage()
30 #include "LyXRC.h"
31 #include "paragraph_funcs.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
34 #include "Row.h"
35 #include "Text.h"
36 #include "TextMetrics.h"
37 #include "TocBackend.h"
38
39 #include "support/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/InsetMathScript.h"
47 #include "mathed/MacroTable.h"
48 #include "mathed/MathData.h"
49 #include "mathed/MathMacro.h"
50
51 #include <boost/assert.hpp>
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         BOOST_ASSERT(!cursor.empty());
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         Inset & inset = bv.buffer().inset();
208         DocIterator it = doc_iterator_begin(inset);
209         it.pit() = from;
210         DocIterator et = doc_iterator_end(inset);
211
212         double best_dist = numeric_limits<double>::max();
213         DocIterator best_cursor = et;
214
215         for ( ; it != et; it.forwardPos()) {
216                 // avoid invalid nesting when selecting
217                 if (bv.cursorStatus(it) == CUR_INSIDE
218                                 && (!cur.selection() || positionable(it, cur.anchor_))) {
219                         Point p = bv.getPos(it, false);
220                         int xo = p.x_;
221                         int yo = p.y_;
222                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
223                                 double const dx = xo - x;
224                                 double const dy = yo - y;
225                                 double const d = dx * dx + dy * dy;
226                                 //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
227                                 //      << " dx: " << dx << " dy: " << dy
228                                 //      << " idx: " << it.idx() << " pos: " << it.pos()
229                                 //      << " it:\n" << it
230                                 //      << endl;
231                                 // '<=' in order to take the last possible position
232                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
233                                 if (d <= best_dist) {
234                                         //lyxerr << "*" << endl;
235                                         best_dist   = d;
236                                         best_cursor = it;
237                                 }
238                         }
239                 }
240         }
241
242         //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
243         if (best_cursor == et)
244                 return false;
245         cur.setCursor(best_cursor);
246         return true;
247 }
248
249 docstring parbreak(Paragraph const & par)
250 {
251         odocstringstream ods;
252         ods << '\n';
253         // only add blank line if we're not in an ERT or Listings inset
254         if (par.ownerCode() != ERT_CODE
255                         && par.ownerCode() != LISTINGS_CODE)
256                 ods << '\n';
257         return ods.str();
258 }
259
260 } // namespace anon
261
262
263 // be careful: this is called from the bv's constructor, too, so
264 // bv functions are not yet available!
265 Cursor::Cursor(BufferView & bv)
266         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1), textTargetOffset_(0),
267           selection_(false), mark_(false), logicalpos_(false),
268           current_font(inherit_font)
269 {}
270
271
272 void Cursor::reset(Inset & inset)
273 {
274         clear();
275         push_back(CursorSlice(inset));
276         anchor_ = doc_iterator_begin(inset);
277         anchor_.clear();
278         clearTargetX();
279         selection_ = false;
280         mark_ = false;
281 }
282
283
284 // this (intentionally) does neither touch anchor nor selection status
285 void Cursor::setCursor(DocIterator const & cur)
286 {
287         DocIterator::operator=(cur);
288 }
289
290
291 void Cursor::dispatch(FuncRequest const & cmd0)
292 {
293         LYXERR(Debug::DEBUG, "cmd: " << cmd0 << '\n' << *this);
294         if (empty())
295                 return;
296
297         fixIfBroken();
298         FuncRequest cmd = cmd0;
299         Cursor safe = *this;
300         
301         // store some values to be used inside of the handlers
302         beforeDispatchCursor_ = *this;
303         for (; depth(); pop(), boundary(false)) {
304                 LYXERR(Debug::DEBUG, "Cursor::dispatch: cmd: "
305                         << cmd0 << endl << *this);
306                 BOOST_ASSERT(pos() <= lastpos());
307                 BOOST_ASSERT(idx() <= lastidx());
308                 BOOST_ASSERT(pit() <= lastpit());
309
310                 // The common case is 'LFUN handled, need update', so make the
311                 // LFUN handler's life easier by assuming this as default value.
312                 // The handler can reset the update and val flags if necessary.
313                 disp_.update(Update::FitCursor | Update::Force);
314                 disp_.dispatched(true);
315                 inset().dispatch(*this, cmd);
316                 if (disp_.dispatched())
317                         break;
318         }
319         
320         // it completely to get a 'bomb early' behaviour in case this
321         // object will be used again.
322         if (!disp_.dispatched()) {
323                 LYXERR(Debug::DEBUG, "RESTORING OLD CURSOR!");
324                 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 }
333
334
335 DispatchResult Cursor::result() const
336 {
337         return disp_;
338 }
339
340
341 BufferView & Cursor::bv() const
342 {
343         BOOST_ASSERT(bv_);
344         return *bv_;
345 }
346
347
348 Buffer & Cursor::buffer() const
349 {
350         BOOST_ASSERT(bv_);
351         return bv_->buffer();
352 }
353
354
355 void Cursor::pop()
356 {
357         BOOST_ASSERT(depth() >= 1);
358         pop_back();
359 }
360
361
362 void Cursor::push(Inset & p)
363 {
364         push_back(CursorSlice(p));
365         p.setBuffer(bv_->buffer());
366 }
367
368
369 void Cursor::pushBackward(Inset & p)
370 {
371         BOOST_ASSERT(!empty());
372         //lyxerr << "Entering inset " << t << " front" << endl;
373         push(p);
374         p.idxFirst(*this);
375 }
376
377
378 bool Cursor::popBackward()
379 {
380         BOOST_ASSERT(!empty());
381         if (depth() == 1)
382                 return false;
383         pop();
384         return true;
385 }
386
387
388 bool Cursor::popForward()
389 {
390         BOOST_ASSERT(!empty());
391         //lyxerr << "Leaving inset from in back" << endl;
392         const pos_type lp = (depth() > 1) ? (*this)[depth() - 2].lastpos() : 0;
393         if (depth() == 1)
394                 return false;
395         pop();
396         pos() += lastpos() - lp + 1;
397         return true;
398 }
399
400
401 int Cursor::currentMode()
402 {
403         BOOST_ASSERT(!empty());
404         for (int i = depth() - 1; i >= 0; --i) {
405                 int res = operator[](i).inset().currentMode();
406                 if (res != Inset::UNDECIDED_MODE)
407                         return res;
408         }
409         return Inset::TEXT_MODE;
410 }
411
412
413 void Cursor::getPos(int & x, int & y) const
414 {
415         Point p = bv().getPos(*this, boundary());
416         x = p.x_;
417         y = p.y_;
418 }
419
420
421 Row const & Cursor::textRow() const
422 {
423         CursorSlice const & cs = innerTextSlice();
424         ParagraphMetrics const & pm = bv().parMetrics(cs.text(), cs.pit());
425         BOOST_ASSERT(!pm.rows().empty());
426         return pm.getRow(pos(), boundary());
427 }
428
429
430 void Cursor::resetAnchor()
431 {
432         anchor_ = *this;
433 }
434
435
436
437 bool Cursor::posBackward()
438 {
439         if (pos() == 0)
440                 return false;
441         --pos();
442         return true;
443 }
444
445
446 bool Cursor::posForward()
447 {
448         if (pos() == lastpos())
449                 return false;
450         ++pos();
451         return true;
452 }
453
454
455 void Cursor::getSurroundingPos(pos_type & left_pos, pos_type & right_pos)
456 {
457         // preparing bidi tables
458         Paragraph const & par = paragraph();
459         Buffer const & buf = buffer();
460         Row const & row = textRow();
461         Bidi bidi;
462         bidi.computeTables(par, buf, row);
463
464         LYXERR(Debug::RTL, "bidi: " << row.pos() << "--" << row.endpos());
465
466         // The cursor is painted *before* the character at pos(), or, if 'boundary'
467         // is true, *after* the character at (pos() - 1). So we already have one
468         // known position around the cursor:
469         pos_type known_pos = boundary() ? pos() - 1 : pos();
470         
471         // edge case: if we're at the end of the paragraph, things are a little 
472         // different (because lastpos is a position which does not really "exist" 
473         // --- there's no character there yet).
474         if (known_pos == lastpos()) {
475                 if (par.isRTL(buf.params())) {
476                         left_pos = -1;
477                         right_pos = bidi.vis2log(row.pos());
478                 }
479                 else { // LTR paragraph
480                         right_pos = -1;
481                         left_pos = bidi.vis2log(row.endpos() - 1);
482                 }
483                 return;
484         }
485         
486         // Whether 'known_pos' is to the left or to the right of the cursor depends
487         // on whether it is an RTL or LTR character...
488         bool const cur_is_RTL = 
489                 par.getFontSettings(buf.params(), known_pos).isVisibleRightToLeft();
490         // ... in the following manner:
491         // For an RTL character, "before" means "to the right" and "after" means
492         // "to the left"; and for LTR, it's the reverse. So, 'known_pos' is to the
493         // right of the cursor if (RTL && boundary) or (!RTL && !boundary):
494         bool known_pos_on_right = (cur_is_RTL == boundary());
495
496         // So we now know one of the positions surrounding the cursor. Let's 
497         // determine the other one:
498         
499         if (known_pos_on_right) {
500                 right_pos = known_pos;
501                 // *visual* position of 'left_pos':
502                 pos_type v_left_pos = bidi.log2vis(right_pos) - 1;
503                 // If the position we just identified as 'left_pos' is a "skipped 
504                 // separator" (a separator which is at the logical end of a row,
505                 // except for the last row in a paragraph; such separators are not
506                 // painted, so they "are not really there"; note that in bidi text,
507                 // such a separator could appear visually in the middle of a row),
508                 // set 'left_pos' to the *next* position to the left.
509                 if (bidi.inRange(v_left_pos) 
510                                 && bidi.vis2log(v_left_pos) + 1 == row.endpos() 
511                                 && row.endpos() < lastpos()
512                                 && par.isSeparator(bidi.vis2log(v_left_pos))) {
513                         --v_left_pos;
514                 }
515                 // calculate the logical position of 'left_pos', if in row
516                 if (!bidi.inRange(v_left_pos))
517                         left_pos = -1;
518                 else
519                         left_pos = bidi.vis2log(v_left_pos);
520                 // If the position we identified as 'right_pos' is a "skipped 
521                 // separator", set 'right_pos' to the *next* position to the right.
522                 if (right_pos + 1 == row.endpos() && row.endpos() < lastpos() 
523                                 && par.isSeparator(right_pos)) {
524                         pos_type v_right_pos = bidi.log2vis(right_pos) + 1;
525                         if (!bidi.inRange(v_right_pos))
526                                 right_pos = -1;
527                         else
528                                 right_pos = bidi.vis2log(v_right_pos);
529                 }
530         } 
531         else { // known_pos is on the left
532                 left_pos = known_pos;
533                 // *visual* position of 'right_pos'
534                 pos_type v_right_pos = bidi.log2vis(left_pos) + 1;
535                 // If the position we just identified as 'right_pos' is a "skipped 
536                 // separator", set 'right_pos' to the *next* position to the right.
537                 if (bidi.inRange(v_right_pos) 
538                                 && bidi.vis2log(v_right_pos) + 1 == row.endpos() 
539                                 && row.endpos() < lastpos()
540                                 && par.isSeparator(bidi.vis2log(v_right_pos))) {
541                         ++v_right_pos;
542                 }
543                 // calculate the logical position of 'right_pos', if in row
544                 if (!bidi.inRange(v_right_pos)) 
545                         right_pos = -1;
546                 else
547                         right_pos = bidi.vis2log(v_right_pos);
548                 // If the position we identified as 'left_pos' is a "skipped 
549                 // separator", set 'left_pos' to the *next* position to the left.
550                 if (left_pos + 1 == row.endpos() && row.endpos() < lastpos() 
551                                 && par.isSeparator(left_pos)) {
552                         pos_type v_left_pos = bidi.log2vis(left_pos) - 1;
553                         if (!bidi.inRange(v_left_pos))
554                                 left_pos = -1;
555                         else
556                                 left_pos = bidi.vis2log(v_left_pos);
557                 }
558         }
559         return;
560 }
561
562
563 bool Cursor::posVisToNewRow(bool movingLeft)
564 {
565         Paragraph const & par = paragraph();
566         Buffer const & buf = buffer();
567         Row const & row = textRow();
568         bool par_is_LTR = !par.isRTL(buf.params());
569         
570         // if moving left in an LTR paragraph or moving right in an RTL one, 
571         // move to previous row
572         if (par_is_LTR == movingLeft) {
573                 if (row.pos() == 0) { // we're at first row in paragraph
574                         if (pit() == 0) // no previous paragraph! don't move
575                                 return false;
576                         // move to last pos in previous par
577                         --pit();
578                         pos() = lastpos();
579                         boundary(false);
580                 } else { // move to previous row in this par
581                         pos() = row.pos() - 1; // this is guaranteed to be in previous row
582                         boundary(false);
583                 }
584         }
585         // if moving left in an RTL paragraph or moving right in an LTR one, 
586         // move to next row
587         else {
588                 if (row.endpos() == lastpos()) { // we're at last row in paragraph
589                         if (pit() == lastpit()) // last paragraph! don't move
590                                 return false;
591                         // move to first row in next par
592                         ++pit();
593                         pos() = 0;
594                         boundary(false);
595                 } else { // move to next row in this par
596                         pos() = row.endpos();
597                         boundary(false);
598                 }
599         }
600         
601         // make sure we're at left-/right-most pos in new row
602         posVisToRowExtremity(!movingLeft);
603
604         return true;
605 }
606
607
608 void Cursor::posVisToRowExtremity(bool left)  
609 {
610         // prepare bidi tables
611         Paragraph const & par = paragraph();
612         Buffer const & buf = buffer();
613         Row const & row = textRow();
614         Bidi bidi;
615         bidi.computeTables(par, buf, row);
616
617         LYXERR(Debug::RTL, "entering extremity: " << pit() << "," << pos() << ","
618                 << (boundary() ? 1 : 0));
619
620         if (left) { // move to leftmost position
621                 // if this is an RTL paragraph, and we're at the last row in the
622                 // paragraph, move to lastpos
623                 if (par.isRTL(buf.params()) && row.endpos() == lastpos())
624                         pos() = lastpos();
625                 else {
626                         pos() = bidi.vis2log(row.pos());
627
628                         // Moving to the leftmost position in the row, the cursor should
629                         // normally be placed to the *left* of the leftmost position.
630                         // A very common exception, though, is if the leftmost character 
631                         // also happens to be the separator at the (logical) end of the row
632                         // --- in this case, the separator is positioned beyond the left 
633                         // margin, and we don't want to move the cursor there (moving to 
634                         // the left of the separator is equivalent to moving to the next
635                         // line). So, in this case we actually want to place the cursor 
636                         // to the *right* of the leftmost position (the separator). 
637                         // Another exception is if we're moving to the logically last 
638                         // position in the row, which is *not* a separator: this means
639                         // that the entire row has no separators (if there were any, the 
640                         // row would have been broken there); and therefore in this case
641                         // we also move to the *right* of the last position (this indicates
642                         // to the user that there is no space after this position, and is 
643                         // consistent with the behavior in the middle of a row --- moving
644                         // right or left moves to the next/previous character; if we were
645                         // to move to the *left* of this position, that would simulate 
646                         // a separator which is not really there!). 
647                         // Finally, there is an exception to the previous exception: if 
648                         // this non-separator-but-last-position-in-row is an inset, then
649                         // we *do* want to stay to the left of it anyway: this is the 
650                         // "boundary" which we simulate at insets.
651                         
652                         bool right_of_pos = false; // do we want to be to the right of pos?
653
654                         // as explained above, if at last pos in row, stay to the right
655                         if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
656                                 right_of_pos = true;
657
658                         // Now we know if we want to be to the left or to the right of pos,
659                         // let's make sure we are where we want to be.
660                         bool new_pos_is_RTL = 
661                                 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
662
663                         if (new_pos_is_RTL == !right_of_pos) {
664                                 ++pos();
665                                 boundary(true);
666                         }
667                         
668                 }
669         }
670         else { // move to rightmost position
671                 // if this is an LTR paragraph, and we're at the last row in the
672                 // paragraph, move to lastpos
673                 if (!par.isRTL(buf.params()) && row.endpos() == lastpos())
674                         pos() = lastpos();
675                 else {
676                         pos() = bidi.vis2log(row.endpos() - 1);
677
678                         // Moving to the rightmost position in the row, the cursor should
679                         // normally be placed to the *right* of the rightmost position.
680                         // A very common exception, though, is if the rightmost character 
681                         // also happens to be the separator at the (logical) end of the row
682                         // --- in this case, the separator is positioned beyond the right 
683                         // margin, and we don't want to move the cursor there (moving to 
684                         // the right of the separator is equivalent to moving to the next
685                         // line). So, in this case we actually want to place the cursor 
686                         // to the *left* of the rightmost position (the separator). 
687                         // Another exception is if we're moving to the logically last 
688                         // position in the row, which is *not* a separator: this means
689                         // that the entire row has no separators (if there were any, the 
690                         // row would have been broken there); and therefore in this case
691                         // we also move to the *left* of the last position (this indicates
692                         // to the user that there is no space after this position, and is 
693                         // consistent with the behavior in the middle of a row --- moving
694                         // right or left moves to the next/previous character; if we were
695                         // to move to the *right* of this position, that would simulate 
696                         // a separator which is not really there!). 
697                         // Finally, there is an exception to the previous exception: if 
698                         // this non-separator-but-last-position-in-row is an inset, then
699                         // we *do* want to stay to the right of it anyway: this is the 
700                         // "boundary" which we simulate at insets.
701                         
702                         bool left_of_pos = false; // do we want to be to the left of pos?
703
704                         // as explained above, if at last pos in row, stay to the left
705                         if ((pos() == row.endpos() - 1) && !par.isInset(pos()))
706                                 left_of_pos = true;
707
708                         // Now we know if we want to be to the left or to the right of pos,
709                         // let's make sure we are where we want to be.
710                         bool new_pos_is_RTL = 
711                                 par.getFontSettings(buf.params(), pos()).isVisibleRightToLeft();
712
713                         if (new_pos_is_RTL == left_of_pos) {
714                                 ++pos();
715                                 boundary(true);
716                         }
717                 }
718         }
719         LYXERR(Debug::RTL, "leaving extremity: " << pit() << "," << pos() << ","
720                 << (boundary() ? 1 : 0));
721 }
722
723
724 CursorSlice Cursor::anchor() const
725 {
726         BOOST_ASSERT(anchor_.depth() >= depth());
727         CursorSlice normal = anchor_[depth() - 1];
728         if (depth() < anchor_.depth() && top() <= normal) {
729                 // anchor is behind cursor -> move anchor behind the inset
730                 ++normal.pos();
731         }
732         return normal;
733 }
734
735
736 CursorSlice Cursor::selBegin() const
737 {
738         if (!selection())
739                 return top();
740         return anchor() < top() ? anchor() : top();
741 }
742
743
744 CursorSlice Cursor::selEnd() const
745 {
746         if (!selection())
747                 return top();
748         return anchor() > top() ? anchor() : top();
749 }
750
751
752 DocIterator Cursor::selectionBegin() const
753 {
754         if (!selection())
755                 return *this;
756         DocIterator di = (anchor() < top() ? anchor_ : *this);
757         di.resize(depth());
758         return di;
759 }
760
761
762 DocIterator Cursor::selectionEnd() const
763 {
764         if (!selection())
765                 return *this;
766         DocIterator di = (anchor() > top() ? anchor_ : *this);
767         if (di.depth() > depth()) {
768                 di.resize(depth());
769                 ++di.pos();
770         }
771         return di;
772 }
773
774
775 void Cursor::setSelection()
776 {
777         selection() = true;
778         // A selection with no contents is not a selection
779         // FIXME: doesnt look ok
780         if (pit() == anchor().pit() && pos() == anchor().pos())
781                 selection() = false;
782 }
783
784
785 void Cursor::setSelection(DocIterator const & where, int n)
786 {
787         setCursor(where);
788         selection() = true;
789         anchor_ = where;
790         pos() += n;
791 }
792
793
794 void Cursor::clearSelection()
795 {
796         selection() = false;
797         mark() = false;
798         resetAnchor();
799 }
800
801
802 void Cursor::setTargetX(int x)
803 {
804         x_target_ = x;
805         textTargetOffset_ = 0;
806 }
807
808
809 int Cursor::x_target() const
810 {
811         return x_target_;
812 }
813
814
815 void Cursor::clearTargetX()
816 {
817         x_target_ = -1;
818         textTargetOffset_ = 0;
819 }
820
821
822 void Cursor::updateTextTargetOffset()
823 {
824         int x;
825         int y;
826         getPos(x, y);
827         textTargetOffset_ = x - x_target_;
828 }
829
830
831 void Cursor::info(odocstream & os) const
832 {
833         for (int i = 1, n = depth(); i < n; ++i) {
834                 operator[](i).inset().infoize(os);
835                 os << "  ";
836         }
837         if (pos() != 0) {
838                 Inset const * inset = prevInset();
839                 // prevInset() can return 0 in certain case.
840                 if (inset)
841                         prevInset()->infoize2(os);
842         }
843         // overwite old message
844         os << "                    ";
845 }
846
847
848 bool Cursor::selHandle(bool sel)
849 {
850         //lyxerr << "Cursor::selHandle" << endl;
851         if (mark())
852                 sel = true;
853         if (sel == selection())
854                 return false;
855
856         if (!sel)
857                 cap::saveSelection(*this);
858
859         resetAnchor();
860         selection() = sel;
861         return true;
862 }
863
864
865 ostream & operator<<(ostream & os, Cursor const & cur)
866 {
867         os << "\n cursor:                                | anchor:\n";
868         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
869                 os << " " << cur[i] << " | ";
870                 if (i < cur.anchor_.depth())
871                         os << cur.anchor_[i];
872                 else
873                         os << "-------------------------------";
874                 os << "\n";
875         }
876         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
877                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
878         }
879         os << " selection: " << cur.selection_
880            << " x_target: " << cur.x_target_ << endl;
881         return os;
882 }
883
884
885 LyXErr & operator<<(LyXErr & os, Cursor const & cur)
886 {
887         os.stream() << cur;
888         return os;
889 }
890
891
892 } // namespace lyx
893
894
895 ///////////////////////////////////////////////////////////////////
896 //
897 // FIXME: Look here
898 // The part below is the non-integrated rest of the original math
899 // cursor. This should be either generalized for texted or moved
900 // back to mathed (in most cases to InsetMathNest).
901 //
902 ///////////////////////////////////////////////////////////////////
903
904 #include "mathed/InsetMathChar.h"
905 #include "mathed/InsetMathGrid.h"
906 #include "mathed/InsetMathScript.h"
907 #include "mathed/InsetMathUnknown.h"
908 #include "mathed/MathFactory.h"
909 #include "mathed/MathStream.h"
910 #include "mathed/MathSupport.h"
911
912
913 namespace lyx {
914
915 //#define FILEDEBUG 1
916
917
918 bool Cursor::isInside(Inset const * p) const
919 {
920         for (size_t i = 0; i != depth(); ++i)
921                 if (&operator[](i).inset() == p)
922                         return true;
923         return false;
924 }
925
926
927 void Cursor::leaveInset(Inset const & inset)
928 {
929         for (size_t i = 0; i != depth(); ++i) {
930                 if (&operator[](i).inset() == &inset) {
931                         resize(i);
932                         return;
933                 }
934         }
935 }
936
937
938 bool Cursor::openable(MathAtom const & t) const
939 {
940         if (!t->isActive())
941                 return false;
942
943         if (t->lock())
944                 return false;
945
946         if (!selection())
947                 return true;
948
949         // we can't move into anything new during selection
950         if (depth() >= anchor_.depth())
951                 return false;
952         if (t.nucleus() != &anchor_[depth()].inset())
953                 return false;
954
955         return true;
956 }
957
958
959 void Cursor::setScreenPos(int x, int /*y*/)
960 {
961         setTargetX(x);
962         //bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
963 }
964
965
966
967 void Cursor::plainErase()
968 {
969         cell().erase(pos());
970 }
971
972
973 void Cursor::markInsert()
974 {
975         insert(char_type(0));
976 }
977
978
979 void Cursor::markErase()
980 {
981         cell().erase(pos());
982 }
983
984
985 void Cursor::plainInsert(MathAtom const & t)
986 {
987         cell().insert(pos(), t);
988         ++pos();
989         inset().setBuffer(bv_->buffer());
990         inset().validate();
991 }
992
993
994 void Cursor::insert(docstring const & str)
995 {
996         for_each(str.begin(), str.end(),
997                  boost::bind(static_cast<void(Cursor::*)(char_type)>
998                              (&Cursor::insert), this, _1));
999 }
1000
1001
1002 void Cursor::insert(char_type c)
1003 {
1004         //lyxerr << "Cursor::insert char '" << c << "'" << endl;
1005         BOOST_ASSERT(!empty());
1006         if (inMathed()) {
1007                 cap::selClearOrDel(*this);
1008                 insert(new InsetMathChar(c));
1009         } else {
1010                 text()->insertChar(*this, c);
1011         }
1012 }
1013
1014
1015 void Cursor::insert(MathAtom const & t)
1016 {
1017         //lyxerr << "Cursor::insert MathAtom '" << t << "'" << endl;
1018         macroModeClose();
1019         cap::selClearOrDel(*this);
1020         plainInsert(t);
1021 }
1022
1023
1024 void Cursor::insert(Inset * inset0)
1025 {
1026         BOOST_ASSERT(inset0);
1027         if (inMathed())
1028                 insert(MathAtom(inset0));
1029         else {
1030                 text()->insertInset(*this, inset0);
1031                 inset0->setBuffer(bv_->buffer());
1032                 inset0->validate();
1033         }
1034 }
1035
1036
1037 void Cursor::niceInsert(docstring const & t)
1038 {
1039         MathData ar;
1040         asArray(t, ar);
1041         if (ar.size() == 1)
1042                 niceInsert(ar[0]);
1043         else
1044                 insert(ar);
1045 }
1046
1047
1048 void Cursor::niceInsert(MathAtom const & t)
1049 {
1050         macroModeClose();
1051         docstring const safe = cap::grabAndEraseSelection(*this);
1052         plainInsert(t);
1053         // enter the new inset and move the contents of the selection if possible
1054         if (t->isActive()) {
1055                 posBackward();
1056                 // be careful here: don't use 'pushBackward(t)' as this we need to
1057                 // push the clone, not the original
1058                 pushBackward(*nextInset());
1059                 // We may not use niceInsert here (recursion)
1060                 MathData ar;
1061                 asArray(safe, ar);
1062                 insert(ar);
1063         }
1064 }
1065
1066
1067 void Cursor::insert(MathData const & ar)
1068 {
1069         macroModeClose();
1070         if (selection())
1071                 cap::eraseSelection(*this);
1072         cell().insert(pos(), ar);
1073         pos() += ar.size();
1074 }
1075
1076
1077 bool Cursor::backspace()
1078 {
1079         autocorrect() = false;
1080
1081         if (selection()) {
1082                 cap::eraseSelection(*this);
1083                 return true;
1084         }
1085
1086         if (pos() == 0) {
1087                 // If empty cell, and not part of a big cell
1088                 if (lastpos() == 0 && inset().nargs() == 1) {
1089                         popBackward();
1090                         // Directly delete empty cell: [|[]] => [|]
1091                         if (inMathed()) {
1092                                 plainErase();
1093                                 resetAnchor();
1094                                 return true;
1095                         }
1096                         // [|], can not delete from inside
1097                         return false;
1098                 } else {
1099                         if (inMathed())
1100                                 pullArg();
1101                         else
1102                                 popBackward();
1103                         return true;
1104                 }
1105         }
1106
1107         if (inMacroMode()) {
1108                 InsetMathUnknown * p = activeMacro();
1109                 if (p->name().size() > 1) {
1110                         p->setName(p->name().substr(0, p->name().size() - 1));
1111                         return true;
1112                 }
1113         }
1114
1115         if (pos() != 0 && prevAtom()->nargs() > 0) {
1116                 // let's require two backspaces for 'big stuff' and
1117                 // highlight on the first
1118                 resetAnchor();
1119                 selection() = true;
1120                 --pos();
1121         } else {
1122                 --pos();
1123                 plainErase();
1124         }
1125         return true;
1126 }
1127
1128
1129 bool Cursor::erase()
1130 {
1131         autocorrect() = false;
1132         if (inMacroMode())
1133                 return true;
1134
1135         if (selection()) {
1136                 cap::eraseSelection(*this);
1137                 return true;
1138         }
1139
1140         // delete empty cells if possible
1141         if (pos() == lastpos() && inset().idxDelete(idx()))
1142                 return true;
1143
1144         // special behaviour when in last position of cell
1145         if (pos() == lastpos()) {
1146                 bool one_cell = inset().nargs() == 1;
1147                 if (one_cell && lastpos() == 0) {
1148                         popBackward();
1149                         // Directly delete empty cell: [|[]] => [|]
1150                         if (inMathed()) {
1151                                 plainErase();
1152                                 resetAnchor();
1153                                 return true;
1154                         }
1155                         // [|], can not delete from inside
1156                         return false;
1157                 }
1158                 // remove markup
1159                 if (!one_cell)
1160                         inset().idxGlue(idx());
1161                 return true;
1162         }
1163
1164         // 'clever' UI hack: only erase large items if previously slected
1165         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
1166                 resetAnchor();
1167                 selection() = true;
1168                 ++pos();
1169         } else {
1170                 plainErase();
1171         }
1172
1173         return true;
1174 }
1175
1176
1177 bool Cursor::up()
1178 {
1179         macroModeClose();
1180         DocIterator save = *this;
1181         FuncRequest cmd(selection() ? LFUN_UP_SELECT : LFUN_UP, docstring());
1182         this->dispatch(cmd);
1183         if (disp_.dispatched())
1184                 return true;
1185         setCursor(save);
1186         autocorrect() = false;
1187         return false;
1188 }
1189
1190
1191 bool Cursor::down()
1192 {
1193         macroModeClose();
1194         DocIterator save = *this;
1195         FuncRequest cmd(selection() ? LFUN_DOWN_SELECT : LFUN_DOWN, docstring());
1196         this->dispatch(cmd);
1197         if (disp_.dispatched())
1198                 return true;
1199         setCursor(save);
1200         autocorrect() = false;
1201         return false;
1202 }
1203
1204
1205 bool Cursor::macroModeClose()
1206 {
1207         if (!inMacroMode())
1208                 return false;
1209         InsetMathUnknown * p = activeMacro();
1210         p->finalize();
1211         docstring const s = p->name();
1212         --pos();
1213         cell().erase(pos());
1214
1215         // do nothing if the macro name is empty
1216         if (s == "\\")
1217                 return false;
1218
1219         // trigger updates of macros, at least, if no full
1220         // updates take place anyway
1221         updateFlags(Update::Force);
1222
1223         docstring const name = s.substr(1);
1224         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
1225         if (in && in->interpretString(*this, s))
1226                 return true;
1227         MathAtom atom = createInsetMath(name);
1228         MathMacro * atomAsMacro = atom.nucleus()->asMacro();
1229         if (atomAsMacro) {
1230                 // make non-greedy, i.e. don't eat parameters from the right
1231                 atomAsMacro->setDisplayMode(MathMacro::DISPLAY_INTERACTIVE_INIT);
1232         }
1233         plainInsert(atom);
1234         return true;
1235 }
1236
1237
1238 docstring Cursor::macroName()
1239 {
1240         return inMacroMode() ? activeMacro()->name() : docstring();
1241 }
1242
1243
1244 void Cursor::handleNest(MathAtom const & a, int c)
1245 {
1246         //lyxerr << "Cursor::handleNest: " << c << endl;
1247         MathAtom t = a;
1248         asArray(cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
1249         insert(t);
1250         posBackward();
1251         pushBackward(*nextInset());
1252 }
1253
1254
1255 int Cursor::targetX() const
1256 {
1257         if (x_target() != -1)
1258                 return x_target();
1259         int x = 0;
1260         int y = 0;
1261         getPos(x, y);
1262         return x;
1263 }
1264
1265
1266 int Cursor::textTargetOffset() const
1267 {
1268         return textTargetOffset_;
1269 }
1270
1271
1272 void Cursor::setTargetX()
1273 {
1274         int x;
1275         int y;
1276         getPos(x, y);
1277         setTargetX(x);
1278 }
1279
1280
1281 bool Cursor::inMacroMode() const
1282 {
1283         if (!inMathed())
1284                 return false;
1285         if (pos() == 0)
1286                 return false;
1287         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
1288         return p && !p->final();
1289 }
1290
1291
1292 InsetMathUnknown * Cursor::activeMacro()
1293 {
1294         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1295 }
1296
1297
1298 InsetMathUnknown const * Cursor::activeMacro() const
1299 {
1300         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1301 }
1302
1303
1304 void Cursor::pullArg()
1305 {
1306         // FIXME: Look here
1307         MathData ar = cell();
1308         if (popBackward() && inMathed()) {
1309                 plainErase();
1310                 cell().insert(pos(), ar);
1311                 resetAnchor();
1312         } else {
1313                 //formula()->mutateToText();
1314         }
1315 }
1316
1317
1318 void Cursor::touch()
1319 {
1320         // FIXME: look here
1321 #if 0
1322         DocIterator::const_iterator it = begin();
1323         DocIterator::const_iterator et = end();
1324         for ( ; it != et; ++it)
1325                 it->cell().touch();
1326 #endif
1327 }
1328
1329
1330 void Cursor::normalize()
1331 {
1332         if (idx() > lastidx()) {
1333                 lyxerr << "this should not really happen - 1: "
1334                        << idx() << ' ' << nargs()
1335                        << " in: " << &inset() << endl;
1336                 idx() = lastidx();
1337         }
1338
1339         if (pos() > lastpos()) {
1340                 lyxerr << "this should not really happen - 2: "
1341                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1342                        << " in atom: '";
1343                 odocstringstream os;
1344                 WriteStream wi(os, false, true);
1345                 inset().asInsetMath()->write(wi);
1346                 lyxerr << to_utf8(os.str()) << endl;
1347                 pos() = lastpos();
1348         }
1349 }
1350
1351
1352 bool Cursor::upDownInMath(bool up)
1353 {
1354         // Be warned: The 'logic' implemented in this function is highly
1355         // fragile. A distance of one pixel or a '<' vs '<=' _really
1356         // matters. So fiddle around with it only if you think you know
1357         // what you are doing!
1358         int xo = 0;
1359         int yo = 0;
1360         getPos(xo, yo);
1361         xo = theLyXFunc().cursorBeforeDispatchX();
1362         
1363         // check if we had something else in mind, if not, this is the future
1364         // target
1365         if (x_target_ == -1)
1366                 setTargetX(xo);
1367         else if (inset().asInsetText() && xo - textTargetOffset() != x_target()) {
1368                 // In text mode inside the line (not left or right) possibly set a new target_x,
1369                 // but only if we are somewhere else than the previous target-offset.
1370                 
1371                 // We want to keep the x-target on subsequent up/down movements
1372                 // that cross beyond the end of short lines. Thus a special
1373                 // handling when the cursor is at the end of line: Use the new
1374                 // x-target only if the old one was before the end of line
1375                 // or the old one was after the beginning of the line
1376                 bool inRTL = isWithinRtlParagraph(*this);
1377                 bool left;
1378                 bool right;
1379                 if (inRTL) {
1380                         left = pos() == textRow().endpos();
1381                         right = pos() == textRow().pos();
1382                 } else {
1383                         left = pos() == textRow().pos();
1384                         right = pos() == textRow().endpos();
1385                 }
1386                 if ((!left && !right) ||
1387                                 (left && !right && xo < x_target_) ||
1388                                 (!left && right && x_target_ < xo))
1389                         setTargetX(xo);
1390                 else
1391                         xo = targetX();
1392         } else
1393                 xo = targetX();
1394
1395         // try neigbouring script insets
1396         Cursor old = *this;
1397         if (inMathed() && !selection()) {
1398                 // try left
1399                 if (pos() != 0) {
1400                         InsetMathScript const * p = prevAtom()->asScriptInset();
1401                         if (p && p->has(up)) {
1402                                 --pos();
1403                                 push(*const_cast<InsetMathScript*>(p));
1404                                 idx() = p->idxOfScript(up);
1405                                 pos() = lastpos();
1406                                 
1407                                 // we went in the right direction? Otherwise don't jump into the script
1408                                 int x;
1409                                 int y;
1410                                 getPos(x, y);
1411                                 int oy = theLyXFunc().cursorBeforeDispatchY();
1412                                 if ((!up && y <= oy) ||
1413                                                 (up && y >= oy))
1414                                         operator=(old);
1415                                 else
1416                                         return true;
1417                         }
1418                 }
1419                 
1420                 // try right
1421                 if (pos() != lastpos()) {
1422                         InsetMathScript const * p = nextAtom()->asScriptInset();
1423                         if (p && p->has(up)) {
1424                                 push(*const_cast<InsetMathScript*>(p));
1425                                 idx() = p->idxOfScript(up);
1426                                 pos() = 0;
1427                                 
1428                                 // we went in the right direction? Otherwise don't jump into the script
1429                                 int x;
1430                                 int y;
1431                                 getPos(x, y);
1432                                 int oy = theLyXFunc().cursorBeforeDispatchY();
1433                                 if ((!up && y <= oy) ||
1434                                                 (up && y >= oy))
1435                                         operator=(old);
1436                                 else
1437                                         return true;
1438                         }
1439                 }
1440         }
1441                 
1442         // try to find an inset that knows better then we,
1443         if (inset().idxUpDown(*this, up)) {
1444                 //lyxerr << "idxUpDown triggered" << endl;
1445                 // try to find best position within this inset
1446                 if (!selection())
1447                         setCursor(bruteFind2(*this, xo, yo));
1448                 return true;
1449         }
1450         
1451         // any improvement going just out of inset?
1452         if (popBackward() && inMathed()) {
1453                 //lyxerr << "updown: popBackward succeeded" << endl;
1454                 int xnew;
1455                 int ynew;
1456                 int yold = theLyXFunc().cursorBeforeDispatchY();
1457                 getPos(xnew, ynew);
1458                 if (up ? ynew < yold : ynew > yold)
1459                         return true;
1460         }
1461         
1462         // no success, we are probably at the document top or bottom
1463         operator=(old);
1464         return false;
1465 }
1466
1467
1468 bool Cursor::upDownInText(bool up, bool & updateNeeded)
1469 {
1470         BOOST_ASSERT(text());
1471
1472         // where are we?
1473         int xo = 0;
1474         int yo = 0;
1475         getPos(xo, yo);
1476         xo = theLyXFunc().cursorBeforeDispatchX();
1477
1478         // update the targetX - this is here before the "return false"
1479         // to set a new target which can be used by InsetTexts above
1480         // if we cannot move up/down inside this inset anymore
1481         if (x_target_ == -1)
1482                 setTargetX(xo);
1483         else if (xo - textTargetOffset() != x_target() &&
1484                                          depth() == beforeDispatchCursor_.depth()) {
1485                 // In text mode inside the line (not left or right) possibly set a new target_x,
1486                 // but only if we are somewhere else than the previous target-offset.
1487                 
1488                 // We want to keep the x-target on subsequent up/down movements
1489                 // that cross beyond the end of short lines. Thus a special
1490                 // handling when the cursor is at the end of line: Use the new
1491                 // x-target only if the old one was before the end of line
1492                 // or the old one was after the beginning of the line
1493                 bool inRTL = isWithinRtlParagraph(*this);
1494                 bool left;
1495                 bool right;
1496                 if (inRTL) {
1497                         left = pos() == textRow().endpos();
1498                         right = pos() == textRow().pos();
1499                 } else {
1500                         left = pos() == textRow().pos();
1501                         right = pos() == textRow().endpos();
1502                 }
1503                 if ((!left && !right) ||
1504                                 (left && !right && xo < x_target_) ||
1505                                 (!left && right && x_target_ < xo))
1506                         setTargetX(xo);
1507                 else
1508                         xo = targetX();
1509         } else
1510                 xo = targetX();
1511                 
1512         // first get the current line
1513         TextMetrics & tm = bv_->textMetrics(text());
1514         ParagraphMetrics const & pm = tm.parMetrics(pit());
1515         int row;
1516         if (pos() && boundary())
1517                 row = pm.pos2row(pos() - 1);
1518         else
1519                 row = pm.pos2row(pos());
1520                 
1521         // are we not at the start or end?
1522         if (up) {
1523                 if (pit() == 0 && row == 0)
1524                         return false;
1525         } else {
1526                 if (pit() + 1 >= int(text()->paragraphs().size()) &&
1527                                 row + 1 >= int(pm.rows().size()))
1528                         return false;
1529         }       
1530
1531         // with and without selection are handled differently
1532         if (!selection()) {
1533                 int yo = bv().getPos(*this, boundary()).y_;
1534                 Cursor old = *this;
1535                 // To next/previous row
1536                 if (up)
1537                         tm.editXY(*this, xo, yo - textRow().ascent() - 1);
1538                 else
1539                         tm.editXY(*this, xo, yo + textRow().descent() + 1);
1540                 clearSelection();
1541                 
1542                 // This happens when you move out of an inset.
1543                 // And to give the DEPM the possibility of doing
1544                 // something we must provide it with two different
1545                 // cursors. (Lgb)
1546                 Cursor dummy = *this;
1547                 if (dummy == old)
1548                         ++dummy.pos();
1549                 if (bv().checkDepm(dummy, old)) {
1550                         updateNeeded = true;
1551                         // Make sure that cur gets back whatever happened to dummy(Lgb)
1552                         operator=(dummy);
1553                 }
1554         } else {
1555                 // if there is a selection, we stay out of any inset, and just jump to the right position:
1556                 Cursor old = *this;
1557                 if (up) {
1558                         if (row > 0) {
1559                                 top().pos() = min(tm.x2pos(pit(), row - 1, xo), top().lastpos());
1560                         } else if (pit() > 0) {
1561                                 --pit();
1562                                 ParagraphMetrics const & pmcur = bv_->parMetrics(text(), pit());
1563                                 top().pos() = min(tm.x2pos(pit(), pmcur.rows().size() - 1, xo), top().lastpos());
1564                         }
1565                 } else {
1566                         if (row + 1 < int(pm.rows().size())) {
1567                                 top().pos() = min(tm.x2pos(pit(), row + 1, xo), top().lastpos());
1568                         } else if (pit() + 1 < int(text()->paragraphs().size())) {
1569                                 ++pit();
1570                                 top().pos() = min(tm.x2pos(pit(), 0, xo), top().lastpos());
1571                         }
1572                 }
1573
1574                 updateNeeded |= bv().checkDepm(*this, old);
1575         }
1576
1577         updateTextTargetOffset();
1578         return true;
1579 }       
1580
1581
1582 void Cursor::handleFont(string const & font)
1583 {
1584         LYXERR(Debug::DEBUG, font);
1585         docstring safe;
1586         if (selection()) {
1587                 macroModeClose();
1588                 safe = cap::grabAndEraseSelection(*this);
1589         }
1590
1591         if (lastpos() != 0) {
1592                 // something left in the cell
1593                 if (pos() == 0) {
1594                         // cursor in first position
1595                         popBackward();
1596                 } else if (pos() == lastpos()) {
1597                         // cursor in last position
1598                         popForward();
1599                 } else {
1600                         // cursor in between. split cell
1601                         MathData::iterator bt = cell().begin();
1602                         MathAtom at = createInsetMath(from_utf8(font));
1603                         at.nucleus()->cell(0) = MathData(bt, bt + pos());
1604                         cell().erase(bt, bt + pos());
1605                         popBackward();
1606                         plainInsert(at);
1607                 }
1608         } else {
1609                 // nothing left in the cell
1610                 pullArg();
1611                 plainErase();
1612         }
1613         insert(safe);
1614 }
1615
1616
1617 void Cursor::message(docstring const & msg) const
1618 {
1619         theLyXFunc().setMessage(msg);
1620 }
1621
1622
1623 void Cursor::errorMessage(docstring const & msg) const
1624 {
1625         theLyXFunc().setErrorMessage(msg);
1626 }
1627
1628
1629 docstring Cursor::selectionAsString(bool label) const
1630 {
1631         if (!selection())
1632                 return docstring();
1633
1634         if (inTexted()) {
1635                 ParagraphList const & pars = text()->paragraphs();
1636
1637                 // should be const ...
1638                 pit_type startpit = selBegin().pit();
1639                 pit_type endpit = selEnd().pit();
1640                 size_t const startpos = selBegin().pos();
1641                 size_t const endpos = selEnd().pos();
1642
1643                 if (startpit == endpit)
1644                         return pars[startpit].asString(startpos, endpos, label);
1645
1646                 // First paragraph in selection
1647                 docstring result = pars[startpit].
1648                         asString(startpos, pars[startpit].size(), label)
1649                                  + parbreak(pars[startpit]);
1650
1651                 // The paragraphs in between (if any)
1652                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1653                         Paragraph const & par = pars[pit];
1654                         result += par.asString(0, par.size(), label)
1655                                   + parbreak(pars[pit]);
1656                 }
1657
1658                 // Last paragraph in selection
1659                 result += pars[endpit].asString(0, endpos, label);
1660
1661                 return result;
1662         }
1663
1664         if (inMathed())
1665                 return cap::grabSelection(*this);
1666
1667         return docstring();
1668 }
1669
1670
1671 docstring Cursor::currentState()
1672 {
1673         if (inMathed()) {
1674                 odocstringstream os;
1675                 info(os);
1676                 return os.str();
1677         }
1678
1679         if (inTexted())
1680                 return text()->currentState(*this);
1681
1682         return docstring();
1683 }
1684
1685
1686 docstring Cursor::getPossibleLabel()
1687 {
1688         return inMathed() ? from_ascii("eq:") : text()->getPossibleLabel(*this);
1689 }
1690
1691
1692 Encoding const * Cursor::getEncoding() const
1693 {
1694         if (empty())
1695                 return 0;
1696         CursorSlice const & sl = innerTextSlice();
1697         Text const & text = *sl.text();
1698         Font font = text.getPar(sl.pit()).getFont(
1699                 bv().buffer().params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1700         return font.language()->encoding();
1701 }
1702
1703
1704 void Cursor::undispatched()
1705 {
1706         disp_.dispatched(false);
1707 }
1708
1709
1710 void Cursor::dispatched()
1711 {
1712         disp_.dispatched(true);
1713 }
1714
1715
1716 void Cursor::updateFlags(Update::flags f)
1717 {
1718         disp_.update(f);
1719 }
1720
1721
1722 void Cursor::noUpdate()
1723 {
1724         disp_.update(Update::None);
1725 }
1726
1727
1728 Font Cursor::getFont() const
1729 {
1730         // The logic here should more or less match to the Cursor::setCurrentFont
1731         // logic, i.e. the cursor height should give a hint what will happen
1732         // if a character is entered.
1733         
1734         // HACK. far from being perfect...
1735
1736         CursorSlice const & sl = innerTextSlice();
1737         Text const & text = *sl.text();
1738         Paragraph const & par = text.getPar(sl.pit());
1739         
1740         // on boundary, so we are really at the character before
1741         pos_type pos = sl.pos();
1742         if (pos > 0 && boundary())
1743                 --pos;
1744         
1745         // on space? Take the font before (only for RTL boundary stay)
1746         if (pos > 0) {
1747                 TextMetrics const & tm = bv().textMetrics(&text);
1748                 if (pos == sl.lastpos()
1749                         || (par.isSeparator(pos) 
1750                         && !tm.isRTLBoundary(sl.pit(), pos)))
1751                         --pos;
1752         }
1753         
1754         // get font at the position
1755         Font font = par.getFont(bv().buffer().params(), pos,
1756                 outerFont(sl.pit(), text.paragraphs()));
1757
1758         return font;
1759 }
1760
1761
1762 bool Cursor::fixIfBroken()
1763 {
1764         if (DocIterator::fixIfBroken()) {
1765                         clearSelection();
1766                         resetAnchor();
1767                         return true;
1768         }
1769         return false;
1770 }
1771
1772
1773 bool notifyCursorLeaves(Cursor const & old, Cursor & cur)
1774 {
1775         // find inset in common
1776         size_type i;
1777         for (i = 0; i < old.depth() && i < cur.depth(); ++i) {
1778                 if (&old[i].inset() != &cur[i].inset())
1779                         break;
1780         }
1781
1782         // update words if we just moved to another paragraph
1783         if (i == old.depth() && i == cur.depth()
1784             && !cur.buffer().isClean()
1785             && cur.inTexted() && old.inTexted()
1786             && cur.pit() != old.pit()) {
1787                 old.paragraph().updateWords(old.buffer(), old.top());
1788                 return false;
1789         }
1790         
1791         // notify everything on top of the common part in old cursor,
1792         // but stop if the inset claims the cursor to be invalid now
1793         for (; i < old.depth(); ++i) {
1794                 Cursor insetPos = old;
1795                 insetPos.cutOff(i);
1796                 if (old[i].inset().notifyCursorLeaves(insetPos, cur))
1797                         return true;
1798         }
1799         
1800         return false;
1801 }
1802
1803
1804 void Cursor::setCurrentFont()
1805 {
1806         CursorSlice const & cs = innerTextSlice();
1807         Paragraph const & par = cs.paragraph();
1808         pos_type cpit = cs.pit();
1809         pos_type cpos = cs.pos();
1810         Text const & ctext = *cs.text();
1811         TextMetrics const & tm = bv().textMetrics(&ctext);
1812
1813         // are we behind previous char in fact? -> go to that char
1814         if (cpos > 0 && boundary())
1815                 --cpos;
1816
1817         // find position to take the font from
1818         if (cpos != 0) {
1819                 // paragraph end? -> font of last char
1820                 if (cpos == lastpos())
1821                         --cpos;
1822                 // on space? -> look at the words in front of space
1823                 else if (cpos > 0 && par.isSeparator(cpos))     {
1824                         // abc| def -> font of c
1825                         // abc |[WERBEH], i.e. boundary==true -> font of c
1826                         // abc [WERBEH]| def, font of the space
1827                         if (!tm.isRTLBoundary(cpit, cpos))
1828                                 --cpos;
1829                 }
1830         }
1831
1832         // get font
1833         BufferParams const & bufparams = buffer().params();
1834         current_font = par.getFontSettings(bufparams, cpos);
1835         real_current_font = tm.displayFont(cpit, cpos);
1836
1837         // special case for paragraph end
1838         if (cs.pos() == lastpos()
1839             && tm.isRTLBoundary(cpit, cs.pos())
1840             && !boundary()) {
1841                 Language const * lang = par.getParLanguage(bufparams);
1842                 current_font.setLanguage(lang);
1843                 current_font.fontInfo().setNumber(FONT_OFF);
1844                 real_current_font.setLanguage(lang);
1845                 real_current_font.fontInfo().setNumber(FONT_OFF);
1846         }
1847 }
1848
1849
1850 bool Cursor::textUndo()
1851 {
1852         DocIterator dit = *this;
1853         // Undo::textUndo() will modify dit.
1854         if (!bv_->buffer().undo().textUndo(dit))
1855                 return false;
1856         // Set cursor
1857         setCursor(dit);
1858         selection() = false;
1859         resetAnchor();
1860         fixIfBroken();
1861         return true;
1862 }
1863
1864
1865 bool Cursor::textRedo()
1866 {
1867         DocIterator dit = *this;
1868         // Undo::textRedo() will modify dit.
1869         if (!bv_->buffer().undo().textRedo(dit))
1870                 return false;
1871         // Set cursor
1872         setCursor(dit);
1873         selection() = false;
1874         resetAnchor();
1875         fixIfBroken();
1876         return true;
1877 }
1878
1879
1880 void Cursor::finishUndo()
1881 {
1882         bv_->buffer().undo().finishUndo();
1883 }
1884
1885
1886 void Cursor::recordUndo(UndoKind kind, pit_type from, pit_type to)
1887 {
1888         bv_->buffer().undo().recordUndo(*this, kind, from, to);
1889 }
1890
1891
1892 void Cursor::recordUndo(UndoKind kind, pit_type from)
1893 {
1894         bv_->buffer().undo().recordUndo(*this, kind, from);
1895 }
1896
1897
1898 void Cursor::recordUndo(UndoKind kind)
1899 {
1900         bv_->buffer().undo().recordUndo(*this, kind);
1901 }
1902
1903
1904 void Cursor::recordUndoInset(UndoKind kind)
1905 {
1906         bv_->buffer().undo().recordUndoInset(*this, kind);
1907 }
1908
1909
1910 void Cursor::recordUndoFullDocument()
1911 {
1912         bv_->buffer().undo().recordUndoFullDocument(*this);
1913 }
1914
1915
1916 void Cursor::recordUndoSelection()
1917 {
1918         bv_->buffer().undo().recordUndo(*this, ATOMIC_UNDO,
1919                 selBegin().pit(), selEnd().pit());
1920 }
1921
1922
1923 void Cursor::checkBufferStructure()
1924 {
1925         if (paragraph().layout()->toclevel == Layout::NOT_IN_TOC)
1926                 return;
1927         Buffer const * master = buffer().masterBuffer();
1928         master->tocBackend().updateItem(ParConstIterator(*this));
1929         master->structureChanged();
1930 }
1931
1932
1933 } // namespace lyx