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