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