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