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