]> git.lyx.org Git - lyx.git/blob - src/cursor.C
move definition of variables to the main cmake file
[lyx.git] / src / cursor.C
1 /**
2  * \file cursor.C
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 André Pönitz
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "BufferView.h"
16 #include "buffer.h"
17 #include "cursor.h"
18 #include "coordcache.h"
19 #include "CutAndPaste.h"
20 #include "debug.h"
21 #include "dispatchresult.h"
22 #include "encoding.h"
23 #include "funcrequest.h"
24 #include "language.h"
25 #include "lfuns.h"
26 #include "lyxfont.h"
27 #include "lyxfunc.h" // only for setMessage()
28 #include "lyxrc.h"
29 #include "lyxrow.h"
30 #include "lyxtext.h"
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "pariterator.h"
34
35 #include "insets/insettabular.h"
36 #include "insets/insettext.h"
37
38 #include "mathed/MathData.h"
39 #include "mathed/InsetMath.h"
40 #include "mathed/InsetMathScript.h"
41 #include "mathed/MathMacroTable.h"
42 #include "mathed/MathParser.h"
43
44 #include "support/limited_stack.h"
45
46 #include "frontends/LyXView.h"
47 #include "frontends/font_metrics.h"
48
49 #include <boost/assert.hpp>
50 #include <boost/bind.hpp>
51 #include <boost/current_function.hpp>
52
53 #include <sstream>
54 #include <limits>
55
56 using lyx::char_type;
57 using lyx::docstring;
58 using lyx::pit_type;
59
60 using std::string;
61 using std::vector;
62 using std::endl;
63 #ifndef CXX_GLOBAL_CSTD
64 using std::isalpha;
65 #endif
66 using std::min;
67
68 namespace {
69
70         bool
71         positionable(DocIterator const & cursor, DocIterator const & anchor)
72         {
73                 // avoid deeper nested insets when selecting
74                 if (cursor.depth() > anchor.depth())
75                         return false;
76
77                 // anchor might be deeper, should have same path then
78                 for (size_t i = 0; i < cursor.depth(); ++i)
79                         if (&cursor[i].inset() != &anchor[i].inset())
80                                 return false;
81
82                 // position should be ok.
83                 return true;
84         }
85
86
87         // Find position closest to (x, y) in cell given by iter.
88         // Used only in mathed
89         DocIterator bruteFind2(LCursor const & c, int x, int y)
90         {
91                 double best_dist = std::numeric_limits<double>::max();
92
93                 DocIterator result;
94
95                 DocIterator it = c;
96                 it.top().pos() = 0;
97                 DocIterator et = c;
98                 et.top().pos() = et.top().asInsetMath()->cell(et.top().idx()).size();
99                 for (size_t i = 0; ; ++i) {
100                         int xo;
101                         int yo;
102                         InsetBase const * inset = &it.inset();
103                         Point o = theCoords.getInsets().xy(inset);
104                         inset->cursorPos(it.top(), c.boundary(), xo, yo);
105                         // Convert to absolute
106                         xo += o.x_;
107                         yo += o.y_;
108                         double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
109                         // '<=' in order to take the last possible position
110                         // this is important for clicking behind \sum in e.g. '\sum_i a'
111                         lyxerr[Debug::DEBUG] << "i: " << i << " d: " << d
112                                 << " best: " << best_dist << endl;
113                         if (d <= best_dist) {
114                                 best_dist = d;
115                                 result = it;
116                         }
117                         if (it == et)
118                                 break;
119                         it.forwardPos();
120                 }
121                 return result;
122         }
123
124
125         /// moves position closest to (x, y) in given box
126         bool bruteFind(LCursor & cursor,
127                 int x, int y, int xlow, int xhigh, int ylow, int yhigh)
128         {
129                 BOOST_ASSERT(!cursor.empty());
130                 InsetBase & inset = cursor[0].inset();
131
132                 CoordCache::InnerParPosCache const & cache = theCoords.getParPos().find(cursor.bottom().text())->second;
133                 // Get an iterator on the first paragraph in the cache
134                 DocIterator it(inset);
135                 it.push_back(CursorSlice(inset));
136                 it.pit() = cache.begin()->first;
137                 // Get an iterator after the last paragraph in the cache
138                 DocIterator et(inset);
139                 et.push_back(CursorSlice(inset));
140                 et.pit() = boost::prior(cache.end())->first;
141                 if (et.pit() >= et.lastpit())
142                         et = doc_iterator_end(inset);
143                 else
144                         ++et.pit();
145
146                 double best_dist = std::numeric_limits<double>::max();;
147                 DocIterator best_cursor = et;
148
149                 for ( ; it != et; it.forwardPos(true)) {
150                         // avoid invalid nesting when selecting
151                         if (!cursor.selection() || positionable(it, cursor.anchor_)) {
152                                 Point p = bv_funcs::getPos(it, false);
153                                 int xo = p.x_;
154                                 int yo = p.y_;
155                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
156                                         double const dx = xo - x;
157                                         double const dy = yo - y;
158                                         double const d = dx * dx + dy * dy;
159                                         // '<=' in order to take the last possible position
160                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
161                                         if (d <= best_dist) {
162                                                 //      lyxerr << "*" << endl;
163                                                 best_dist   = d;
164                                                 best_cursor = it;
165                                         }
166                                 }
167                         }
168                 }
169
170                 if (best_cursor != et) {
171                         cursor.setCursor(best_cursor);
172                         return true;
173                 }
174
175                 return false;
176         }
177
178
179         /// moves position closest to (x, y) in given box
180         bool bruteFind3(LCursor & cur, int x, int y, bool up)
181         {
182                 BufferView & bv = cur.bv();
183                 int ylow  = up ? 0 : y + 1;
184                 int yhigh = up ? y - 1 : bv.workHeight();
185                 int xlow = 0;
186                 int xhigh = bv.workWidth();
187
188 // FIXME: bit more work needed to get 'from' and 'to' right.
189                 pit_type from = cur.bottom().pit();
190                 //pit_type to = cur.bottom().pit();
191                 //lyxerr << "Pit start: " << from << endl;
192
193                 //lyxerr << "bruteFind3: x: " << x << " y: " << y
194                 //      << " xlow: " << xlow << " xhigh: " << xhigh
195                 //      << " ylow: " << ylow << " yhigh: " << yhigh
196                 //      << endl;
197                 InsetBase & inset = bv.buffer()->inset();
198                 DocIterator it = doc_iterator_begin(inset);
199                 it.pit() = from;
200                 DocIterator et = doc_iterator_end(inset);
201
202                 double best_dist = std::numeric_limits<double>::max();
203                 DocIterator best_cursor = et;
204
205                 for ( ; it != et; it.forwardPos()) {
206                         // avoid invalid nesting when selecting
207                         if (bv_funcs::status(&bv, it) == bv_funcs::CUR_INSIDE
208                             && (!cur.selection() || positionable(it, cur.anchor_))) {
209                                 Point p = bv_funcs::getPos(it, false);
210                                 int xo = p.x_;
211                                 int yo = p.y_;
212                                 if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
213                                         double const dx = xo - x;
214                                         double const dy = yo - y;
215                                         double const d = dx * dx + dy * dy;
216                                         //lyxerr << "itx: " << xo << " ity: " << yo << " d: " << d
217                                         //      << " dx: " << dx << " dy: " << dy
218                                         //      << " idx: " << it.idx() << " pos: " << it.pos()
219                                         //      << " it:\n" << it
220                                         //      << endl;
221                                         // '<=' in order to take the last possible position
222                                         // this is important for clicking behind \sum in e.g. '\sum_i a'
223                                         if (d <= best_dist) {
224                                                 //lyxerr << "*" << endl;
225                                                 best_dist   = d;
226                                                 best_cursor = it;
227                                         }
228                                 }
229                         }
230                 }
231
232                 //lyxerr << "best_dist: " << best_dist << " cur:\n" << best_cursor << endl;
233                 if (best_cursor == et)
234                         return false;
235                 cur.setCursor(best_cursor);
236                 return true;
237         }
238
239 } // namespace anon
240
241
242 // be careful: this is called from the bv's constructor, too, so
243 // bv functions are not yet available!
244 LCursor::LCursor(BufferView & bv)
245         : DocIterator(), bv_(&bv), anchor_(), x_target_(-1),
246           selection_(false), mark_(false), logicalpos_(false)
247 {}
248
249
250 void LCursor::reset(InsetBase & inset)
251 {
252         clear();
253         push_back(CursorSlice(inset));
254         anchor_ = DocIterator(inset);
255         clearTargetX();
256         selection_ = false;
257         mark_ = false;
258 }
259
260
261 // this (intentionally) does neither touch anchor nor selection status
262 void LCursor::setCursor(DocIterator const & cur)
263 {
264         DocIterator::operator=(cur);
265 }
266
267
268 void LCursor::dispatch(FuncRequest const & cmd0)
269 {
270         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
271                              << " cmd: " << cmd0 << '\n'
272                              << *this << endl;
273         if (empty())
274                 return;
275
276         fixIfBroken();
277         FuncRequest cmd = cmd0;
278         LCursor safe = *this;
279
280         for (; depth(); pop()) {
281                 lyxerr[Debug::DEBUG] << "LCursor::dispatch: cmd: "
282                         << cmd0 << endl << *this << endl;
283                 BOOST_ASSERT(pos() <= lastpos());
284                 BOOST_ASSERT(idx() <= lastidx());
285                 BOOST_ASSERT(pit() <= lastpit());
286
287                 // The common case is 'LFUN handled, need update', so make the
288                 // LFUN handler's life easier by assuming this as default value.
289                 // The handler can reset the update and val flags if necessary.
290                 disp_.update(true);
291                 disp_.dispatched(true);
292                 inset().dispatch(*this, cmd);
293                 if (disp_.dispatched())
294                         break;
295         }
296         // it completely to get a 'bomb early' behaviour in case this
297         // object will be used again.
298         if (!disp_.dispatched()) {
299                 lyxerr[Debug::DEBUG] << "RESTORING OLD CURSOR!" << endl;
300                 operator=(safe);
301                 disp_.dispatched(false);
302         }
303 }
304
305
306 DispatchResult LCursor::result() const
307 {
308         return disp_;
309 }
310
311
312 BufferView & LCursor::bv() const
313 {
314         BOOST_ASSERT(bv_);
315         return *bv_;
316 }
317
318
319 Buffer & LCursor::buffer() const
320 {
321         BOOST_ASSERT(bv_);
322         BOOST_ASSERT(bv_->buffer());
323         return *bv_->buffer();
324 }
325
326
327 void LCursor::pop()
328 {
329         BOOST_ASSERT(depth() >= 1);
330         pop_back();
331 }
332
333
334 void LCursor::push(InsetBase & p)
335 {
336         push_back(CursorSlice(p));
337 }
338
339
340 void LCursor::pushLeft(InsetBase & p)
341 {
342         BOOST_ASSERT(!empty());
343         //lyxerr << "Entering inset " << t << " left" << endl;
344         push(p);
345         p.idxFirst(*this);
346 }
347
348
349 bool LCursor::popLeft()
350 {
351         BOOST_ASSERT(!empty());
352         //lyxerr << "Leaving inset to the left" << endl;
353         inset().notifyCursorLeaves(*this);
354         if (depth() == 1)
355                 return false;
356         pop();
357         return true;
358 }
359
360
361 bool LCursor::popRight()
362 {
363         BOOST_ASSERT(!empty());
364         //lyxerr << "Leaving inset to the right" << endl;
365         inset().notifyCursorLeaves(*this);
366         if (depth() == 1)
367                 return false;
368         pop();
369         ++pos();
370         return true;
371 }
372
373
374 int LCursor::currentMode()
375 {
376         BOOST_ASSERT(!empty());
377         for (int i = depth() - 1; i >= 0; --i) {
378                 int res = operator[](i).inset().currentMode();
379                 if (res != InsetBase::UNDECIDED_MODE)
380                         return res;
381         }
382         return InsetBase::TEXT_MODE;
383 }
384
385
386 void LCursor::getPos(int & x, int & y) const
387 {
388         Point p = bv_funcs::getPos(*this, boundary());
389         x = p.x_;
390         y = p.y_;
391 }
392
393
394 void LCursor::resetAnchor()
395 {
396         anchor_ = *this;
397 }
398
399
400
401 bool LCursor::posLeft()
402 {
403         if (pos() == 0)
404                 return false;
405         --pos();
406         return true;
407 }
408
409
410 bool LCursor::posRight()
411 {
412         if (pos() == lastpos())
413                 return false;
414         ++pos();
415         return true;
416 }
417
418
419 CursorSlice LCursor::anchor() const
420 {
421         BOOST_ASSERT(anchor_.depth() >= depth());
422         CursorSlice normal = anchor_[depth() - 1];
423         if (depth() < anchor_.depth() && top() <= normal) {
424                 // anchor is behind cursor -> move anchor behind the inset
425                 ++normal.pos();
426         }
427         return normal;
428 }
429
430
431 CursorSlice LCursor::selBegin() const
432 {
433         if (!selection())
434                 return top();
435         return anchor() < top() ? anchor() : top();
436 }
437
438
439 CursorSlice LCursor::selEnd() const
440 {
441         if (!selection())
442                 return top();
443         return anchor() > top() ? anchor() : top();
444 }
445
446
447 DocIterator LCursor::selectionBegin() const
448 {
449         if (!selection())
450                 return *this;
451         DocIterator di = (anchor() < top() ? anchor_ : *this);
452         di.resize(depth());
453         return di;
454 }
455
456
457 DocIterator LCursor::selectionEnd() const
458 {
459         if (!selection())
460                 return *this;
461         DocIterator di = (anchor() > top() ? anchor_ : *this);
462         if (di.depth() > depth()) {
463                 di.resize(depth());
464                 ++di.pos();
465         }
466         return di;
467 }
468
469
470 void LCursor::setSelection()
471 {
472         selection() = true;
473         // A selection with no contents is not a selection
474 #ifdef WITH_WARNINGS
475 #warning doesnt look ok
476 #endif
477         if (pit() == anchor().pit() && pos() == anchor().pos())
478                 selection() = false;
479 }
480
481
482 void LCursor::setSelection(DocIterator const & where, size_t n)
483 {
484         setCursor(where);
485         selection() = true;
486         anchor_ = where;
487         pos() += n;
488 }
489
490
491 void LCursor::clearSelection()
492 {
493         selection() = false;
494         mark() = false;
495         resetAnchor();
496 }
497
498
499 int & LCursor::x_target()
500 {
501         return x_target_;
502 }
503
504
505 int LCursor::x_target() const
506 {
507         return x_target_;
508 }
509
510
511 void LCursor::clearTargetX()
512 {
513         x_target_ = -1;
514 }
515
516
517
518 void LCursor::info(std::ostream & os) const
519 {
520         for (int i = 1, n = depth(); i < n; ++i) {
521                 operator[](i).inset().infoize(os);
522                 os << "  ";
523         }
524         if (pos() != 0)
525                 prevInset()->infoize2(os);
526         // overwite old message
527         os << "                    ";
528 }
529
530
531 void LCursor::selHandle(bool sel)
532 {
533         //lyxerr << "LCursor::selHandle" << endl;
534         if (sel == selection())
535                 return;
536
537         resetAnchor();
538         selection() = sel;
539 }
540
541
542 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
543 {
544         os << "\n cursor:                                | anchor:\n";
545         for (size_t i = 0, n = cur.depth(); i != n; ++i) {
546                 os << " " << cur[i] << " | ";
547                 if (i < cur.anchor_.depth())
548                         os << cur.anchor_[i];
549                 else
550                         os << "-------------------------------";
551                 os << "\n";
552         }
553         for (size_t i = cur.depth(), n = cur.anchor_.depth(); i < n; ++i) {
554                 os << "------------------------------- | " << cur.anchor_[i] << "\n";
555         }
556         os << " selection: " << cur.selection_
557            << " x_target: " << cur.x_target_ << endl;
558         return os;
559 }
560
561
562
563
564 ///////////////////////////////////////////////////////////////////
565 //
566 // The part below is the non-integrated rest of the original math
567 // cursor. This should be either generalized for texted or moved
568 // back to mathed (in most cases to InsetMathNest).
569 //
570 ///////////////////////////////////////////////////////////////////
571
572 #include "mathed/InsetMathChar.h"
573 #include "mathed/MathFactory.h"
574 #include "mathed/InsetMathGrid.h"
575 #include "mathed/MathMacroArgument.h"
576 #include "mathed/MathMLStream.h"
577 #include "mathed/InsetMathScript.h"
578 #include "mathed/MathSupport.h"
579 #include "mathed/InsetMathUnknown.h"
580
581 //#define FILEDEBUG 1
582
583
584 bool LCursor::isInside(InsetBase const * p)
585 {
586         for (size_t i = 0; i != depth(); ++i)
587                 if (&operator[](i).inset() == p)
588                         return true;
589         return false;
590 }
591
592
593 void LCursor::leaveInset(InsetBase const & inset)
594 {
595         for (size_t i = 0; i != depth(); ++i) {
596                 if (&operator[](i).inset() == &inset) {
597                         resize(i);
598                         return;
599                 }
600         }
601 }
602
603
604 bool LCursor::openable(MathAtom const & t) const
605 {
606         if (!t->isActive())
607                 return false;
608
609         if (t->lock())
610                 return false;
611
612         if (!selection())
613                 return true;
614
615         // we can't move into anything new during selection
616         if (depth() >= anchor_.depth())
617                 return false;
618         if (!ptr_cmp(t.nucleus(), &anchor_[depth()].inset()))
619                 return false;
620
621         return true;
622 }
623
624
625 void LCursor::setScreenPos(int x, int y)
626 {
627         x_target() = x;
628         bruteFind(*this, x, y, 0, bv().workWidth(), 0, bv().workHeight());
629 }
630
631
632
633 void LCursor::plainErase()
634 {
635         cell().erase(pos());
636 }
637
638
639 void LCursor::markInsert()
640 {
641         insert(char_type(0));
642 }
643
644
645 void LCursor::markErase()
646 {
647         cell().erase(pos());
648 }
649
650
651 void LCursor::plainInsert(MathAtom const & t)
652 {
653         cell().insert(pos(), t);
654         ++pos();
655 }
656
657
658 void LCursor::insert(string const & str)
659 {
660         for_each(str.begin(), str.end(),
661                  boost::bind(static_cast<void(LCursor::*)(char_type)>
662                              (&LCursor::insert), this, _1));
663 }
664
665
666 void LCursor::insert(char_type c)
667 {
668         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
669         BOOST_ASSERT(!empty());
670         if (inMathed()) {
671                 lyx::cap::selClearOrDel(*this);
672                 insert(new InsetMathChar(c));
673         } else {
674                 text()->insertChar(*this, c);
675         }
676 }
677
678
679 void LCursor::insert(MathAtom const & t)
680 {
681         //lyxerr << "LCursor::insert MathAtom '" << t << "'" << endl;
682         macroModeClose();
683         lyx::cap::selClearOrDel(*this);
684         plainInsert(t);
685 }
686
687
688 void LCursor::insert(InsetBase * inset)
689 {
690         if (inMathed())
691                 insert(MathAtom(inset));
692         else
693                 text()->insertInset(*this, inset);
694 }
695
696
697 void LCursor::niceInsert(string const & t)
698 {
699         MathArray ar;
700         asArray(t, ar);
701         if (ar.size() == 1)
702                 niceInsert(ar[0]);
703         else
704                 insert(ar);
705 }
706
707
708 void LCursor::niceInsert(MathAtom const & t)
709 {
710         macroModeClose();
711         string const safe = lyx::cap::grabAndEraseSelection(*this);
712         plainInsert(t);
713         // enter the new inset and move the contents of the selection if possible
714         if (t->isActive()) {
715                 posLeft();
716                 // be careful here: don't use 'pushLeft(t)' as this we need to
717                 // push the clone, not the original
718                 pushLeft(*nextInset());
719                 // We may not use niceInsert here (recursion)
720                 MathArray ar;
721                 asArray(safe, ar);
722                 insert(ar);
723         }
724 }
725
726
727 void LCursor::insert(MathArray const & ar)
728 {
729         macroModeClose();
730         if (selection())
731                 lyx::cap::eraseSelection(*this);
732         cell().insert(pos(), ar);
733         pos() += ar.size();
734 }
735
736
737 bool LCursor::backspace()
738 {
739         autocorrect() = false;
740
741         if (selection()) {
742                 lyx::cap::selDel(*this);
743                 return true;
744         }
745
746         if (pos() == 0) {
747                 if (inset().nargs() == 1 && depth() == 1 && lastpos() == 0)
748                         return false;
749                 pullArg();
750                 return true;
751         }
752
753         if (inMacroMode()) {
754                 InsetMathUnknown * p = activeMacro();
755                 if (p->name().size() > 1) {
756                         p->setName(p->name().substr(0, p->name().size() - 1));
757                         return true;
758                 }
759         }
760
761         if (pos() != 0 && prevAtom()->nargs() > 0) {
762                 // let's require two backspaces for 'big stuff' and
763                 // highlight on the first
764                 resetAnchor();
765                 selection() = true;
766                 --pos();
767         } else {
768                 --pos();
769                 plainErase();
770         }
771         return true;
772 }
773
774
775 bool LCursor::erase()
776 {
777         autocorrect() = false;
778         if (inMacroMode())
779                 return true;
780
781         if (selection()) {
782                 lyx::cap::selDel(*this);
783                 return true;
784         }
785
786         // delete empty cells if possible
787         if (pos() == lastpos() && inset().idxDelete(idx()))
788                 return true;
789
790         // special behaviour when in last position of cell
791         if (pos() == lastpos()) {
792                 bool one_cell = inset().nargs() == 1;
793                 if (one_cell && depth() == 1 && lastpos() == 0)
794                         return false;
795                 // remove markup
796                 if (one_cell)
797                         pullArg();
798                 else
799                         inset().idxGlue(idx());
800                 return true;
801         }
802
803         // 'clever' UI hack: only erase large items if previously slected
804         if (pos() != lastpos() && nextAtom()->nargs() > 0) {
805                 resetAnchor();
806                 selection() = true;
807                 ++pos();
808         } else {
809                 plainErase();
810         }
811
812         return true;
813 }
814
815
816 bool LCursor::up()
817 {
818         macroModeClose();
819         DocIterator save = *this;
820         if (goUpDown(true))
821                 return true;
822         setCursor(save);
823         autocorrect() = false;
824         return selection();
825 }
826
827
828 bool LCursor::down()
829 {
830         macroModeClose();
831         DocIterator save = *this;
832         if (goUpDown(false))
833                 return true;
834         setCursor(save);
835         autocorrect() = false;
836         return selection();
837 }
838
839
840 bool LCursor::macroModeClose()
841 {
842         if (!inMacroMode())
843                 return false;
844         InsetMathUnknown * p = activeMacro();
845         p->finalize();
846         string const s = p->name();
847         --pos();
848         cell().erase(pos());
849
850         // do nothing if the macro name is empty
851         if (s == "\\")
852                 return false;
853
854         // prevent entering of recursive macros
855         // FIXME: this is only a weak attempt... only prevents immediate
856         // recursion
857         string const name = s.substr(1);
858         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
859         if (macro && macro->getInsetName() == name)
860                 lyxerr << "can't enter recursive macro" << endl;
861
862         InsetMathNest * const in = inset().asInsetMath()->asNestInset();
863         if (in && in->interpret(*this, s))
864                 return true;
865         plainInsert(createInsetMath(name));
866         return true;
867 }
868
869
870 string LCursor::macroName()
871 {
872         return inMacroMode() ? activeMacro()->name() : string();
873 }
874
875
876 void LCursor::handleNest(MathAtom const & a, int c)
877 {
878         //lyxerr << "LCursor::handleNest: " << c << endl;
879         MathAtom t = a;
880         asArray(lyx::cap::grabAndEraseSelection(*this), t.nucleus()->cell(c));
881         insert(t);
882         posLeft();
883         pushLeft(*nextInset());
884 }
885
886
887 int LCursor::targetX() const
888 {
889         if (x_target() != -1)
890                 return x_target();
891         int x = 0;
892         int y = 0;
893         getPos(x, y);
894         return x;
895 }
896
897
898 void LCursor::setTargetX()
899 {
900         // For now this is good enough. A better solution would be to
901         // avoid this rebreak by setting cursorX only after drawing
902         bottom().text()->redoParagraph(bottom().pit());
903         int x;
904         int y;
905         getPos(x, y);
906         x_target_ = x;
907 }
908
909
910 bool LCursor::inMacroMode() const
911 {
912         if (pos() == 0)
913                 return false;
914         InsetMathUnknown const * p = prevAtom()->asUnknownInset();
915         return p && !p->final();
916 }
917
918
919 InsetMathUnknown * LCursor::activeMacro()
920 {
921         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
922 }
923
924
925 void LCursor::pullArg()
926 {
927 #ifdef WITH_WARNINGS
928 #warning Look here
929 #endif
930         MathArray ar = cell();
931         if (popLeft() && inMathed()) {
932                 plainErase();
933                 cell().insert(pos(), ar);
934                 resetAnchor();
935         } else {
936                 //formula()->mutateToText();
937         }
938 }
939
940
941 void LCursor::touch()
942 {
943 #ifdef WITH_WARNINGS
944 #warning look here
945 #endif
946 #if 0
947         DocIterator::const_iterator it = begin();
948         DocIterator::const_iterator et = end();
949         for ( ; it != et; ++it)
950                 it->cell().touch();
951 #endif
952 }
953
954
955 void LCursor::normalize()
956 {
957         if (idx() > lastidx()) {
958                 lyxerr << "this should not really happen - 1: "
959                        << idx() << ' ' << nargs()
960                        << " in: " << &inset() << endl;
961                 idx() = lastidx();
962         }
963
964         if (pos() > lastpos()) {
965                 lyxerr << "this should not really happen - 2: "
966                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
967                        << " in atom: '";
968                 WriteStream wi(lyxerr, false, true);
969                 inset().asInsetMath()->write(wi);
970                 lyxerr << endl;
971                 pos() = lastpos();
972         }
973 }
974
975
976 bool LCursor::goUpDown(bool up)
977 {
978         // Be warned: The 'logic' implemented in this function is highly
979         // fragile. A distance of one pixel or a '<' vs '<=' _really
980         // matters. So fiddle around with it only if you think you know
981         // what you are doing!
982
983         int xo = 0;
984         int yo = 0;
985         getPos(xo, yo);
986
987         // check if we had something else in mind, if not, this is the future
988         // target
989         if (x_target() == -1)
990                 x_target() = xo;
991         else
992                 xo = x_target();
993
994         // try neigbouring script insets
995         if (!selection()) {
996                 // try left
997                 if (pos() != 0) {
998                         InsetMathScript const * p = prevAtom()->asScriptInset();
999                         if (p && p->has(up)) {
1000                                 --pos();
1001                                 push(*const_cast<InsetMathScript*>(p));
1002                                 idx() = p->idxOfScript(up);
1003                                 pos() = lastpos();
1004                                 return true;
1005                         }
1006                 }
1007
1008                 // try right
1009                 if (pos() != lastpos()) {
1010                         InsetMathScript const * p = nextAtom()->asScriptInset();
1011                         if (p && p->has(up)) {
1012                                 push(*const_cast<InsetMathScript*>(p));
1013                                 idx() = p->idxOfScript(up);
1014                                 pos() = 0;
1015                                 return true;
1016                         }
1017                 }
1018         }
1019
1020 // FIXME: Switch this on for more robust movement
1021 #if 0
1022
1023         return bruteFind3(*this, xo, yo, up);
1024
1025 #else
1026         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1027         //if (up)
1028         //      yhigh = yo - 4;
1029         //else
1030         //      ylow = yo + 4;
1031         //if (bruteFind(*this, xo, yo, xlow, xhigh, ylow, yhigh)) {
1032         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1033         //      return true;
1034         //}
1035
1036         // try to find an inset that knows better then we
1037         while (true) {
1038                 //lyxerr << "updown: We are in " << &inset() << " idx: " << idx() << endl;
1039                 // ask inset first
1040                 if (inset().idxUpDown(*this, up)) {
1041                         //lyxerr << "idxUpDown triggered" << endl;
1042                         // try to find best position within this inset
1043                         if (!selection())
1044                                 setCursor(bruteFind2(*this, xo, yo));
1045                         return true;
1046                 }
1047
1048                 // no such inset found, just take something "above"
1049                 if (!popLeft()) {
1050                         //lyxerr << "updown: popleft failed (strange case)" << endl;
1051                         int ylow  = up ? 0 : yo + 1;
1052                         int yhigh = up ? yo - 1 : bv().workHeight();
1053                         return bruteFind(*this, xo, yo, 0, bv().workWidth(), ylow, yhigh);
1054                 }
1055
1056                 // any improvement so far?
1057                 //lyxerr << "updown: popLeft succeeded" << endl;
1058                 int xnew;
1059                 int ynew;
1060                 getPos(xnew, ynew);
1061                 if (up ? ynew < yo : ynew > yo)
1062                         return true;
1063         }
1064
1065         // we should not come here.
1066         BOOST_ASSERT(false);
1067 #endif
1068 }
1069
1070
1071 void LCursor::handleFont(string const & font)
1072 {
1073         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << ": " << font << endl;
1074         string safe;
1075         if (selection()) {
1076                 macroModeClose();
1077                 safe = lyx::cap::grabAndEraseSelection(*this);
1078         }
1079
1080         if (lastpos() != 0) {
1081                 // something left in the cell
1082                 if (pos() == 0) {
1083                         // cursor in first position
1084                         popLeft();
1085                 } else if (pos() == lastpos()) {
1086                         // cursor in last position
1087                         popRight();
1088                 } else {
1089                         // cursor in between. split cell
1090                         MathArray::iterator bt = cell().begin();
1091                         MathAtom at = createInsetMath(font);
1092                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1093                         cell().erase(bt, bt + pos());
1094                         popLeft();
1095                         plainInsert(at);
1096                 }
1097         } else {
1098                 // nothing left in the cell
1099                 pullArg();
1100                 plainErase();
1101         }
1102         insert(safe);
1103 }
1104
1105
1106 void LCursor::message(docstring const & msg) const
1107 {
1108         bv().owner()->getLyXFunc().setMessage(msg);
1109 }
1110
1111
1112 void LCursor::errorMessage(docstring const & msg) const
1113 {
1114         bv().owner()->getLyXFunc().setErrorMessage(msg);
1115 }
1116
1117
1118 docstring LCursor::selectionAsString(bool label) const
1119 {
1120         if (!selection())
1121                 return docstring();
1122
1123         if (inTexted()) {
1124                 Buffer const & buffer = *bv().buffer();
1125                 ParagraphList const & pars = text()->paragraphs();
1126
1127                 // should be const ...
1128                 pit_type startpit = selBegin().pit();
1129                 pit_type endpit = selEnd().pit();
1130                 size_t const startpos = selBegin().pos();
1131                 size_t const endpos = selEnd().pos();
1132
1133                 if (startpit == endpit)
1134                         return lyx::from_utf8(pars[startpit].asString(buffer, startpos, endpos, label));
1135
1136                 // First paragraph in selection
1137                 string result = pars[startpit].
1138                         asString(buffer, startpos, pars[startpit].size(), label) + "\n\n";
1139
1140                 // The paragraphs in between (if any)
1141                 for (pit_type pit = startpit + 1; pit != endpit; ++pit) {
1142                         Paragraph const & par = pars[pit];
1143                         result += par.asString(buffer, 0, par.size(), label) + "\n\n";
1144                 }
1145
1146                 // Last paragraph in selection
1147                 result += pars[endpit].asString(buffer, 0, endpos, label);
1148
1149                 return lyx::from_utf8(result);
1150         }
1151
1152         if (inMathed())
1153                 return lyx::from_utf8(lyx::cap::grabSelection(*this));
1154
1155         return docstring();
1156 }
1157
1158
1159 string LCursor::currentState()
1160 {
1161         if (inMathed()) {
1162                 std::ostringstream os;
1163                 info(os);
1164                 return os.str();
1165         }
1166
1167         if (inTexted())
1168                 return text()->currentState(*this);
1169
1170         return string();
1171 }
1172
1173
1174 string LCursor::getPossibleLabel()
1175 {
1176         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1177 }
1178
1179
1180 Encoding const * LCursor::getEncoding() const
1181 {
1182         if (empty())
1183                 return 0;
1184         if (!bv().buffer())
1185                 return 0;
1186         int s = 0;
1187         // go up until first non-0 text is hit
1188         // (innermost text is 0 in mathed)
1189         for (s = depth() - 1; s >= 0; --s)
1190                 if (operator[](s).text())
1191                         break;
1192         CursorSlice const & sl = operator[](s);
1193         LyXText const & text = *sl.text();
1194         LyXFont font = text.getPar(sl.pit()).getFont(
1195                 bv().buffer()->params(), sl.pos(), outerFont(sl.pit(), text.paragraphs()));
1196         return font.language()->encoding();
1197 }
1198
1199
1200 void LCursor::undispatched()
1201 {
1202         disp_.dispatched(false);
1203 }
1204
1205
1206 void LCursor::dispatched()
1207 {
1208         disp_.dispatched(true);
1209 }
1210
1211
1212 void LCursor::needsUpdate()
1213 {
1214         disp_.update(true);
1215 }
1216
1217
1218 void LCursor::noUpdate()
1219 {
1220         disp_.update(false);
1221 }
1222
1223
1224 LyXFont LCursor::getFont() const
1225 {
1226         // HACK. far from being perfect...
1227         int s = 0;
1228         // go up until first non-0 text is hit
1229         // (innermost text is 0 in mathed)
1230         for (s = depth() - 1; s >= 0; --s)
1231                 if (operator[](s).text())
1232                         break;
1233         CursorSlice const & sl = operator[](s);
1234         LyXText const & text = *sl.text();
1235         LyXFont font = text.getPar(sl.pit()).getFont(
1236                 bv().buffer()->params(),
1237                 sl.pos(),
1238                 outerFont(sl.pit(), text.paragraphs()));
1239
1240         return font;
1241 }
1242
1243
1244 void LCursor::fixIfBroken()
1245 {
1246         // find out last good level
1247         LCursor copy = *this;
1248         size_t newdepth = depth();
1249         while (!copy.empty()) {
1250                 if (copy.idx() > copy.lastidx()) {
1251                         lyxerr << "wrong idx " << copy.idx()
1252                                << ", max is " << copy.lastidx()
1253                                << " at level " << copy.depth()
1254                                << ". Trying to correct this."  << endl;
1255                         newdepth = copy.depth() - 1;
1256                 }
1257                 else if (copy.pit() > copy.lastpit()) {
1258                         lyxerr << "wrong pit " << copy.pit()
1259                                << ", max is " << copy.lastpit()
1260                                << " at level " << copy.depth()
1261                                << ". Trying to correct this."  << endl;
1262                         newdepth = copy.depth() - 1;
1263                 }
1264                 else if (copy.pos() > copy.lastpos()) {
1265                         lyxerr << "wrong pos " << copy.pos()
1266                                << ", max is " << copy.lastpos()
1267                                << " at level " << copy.depth()
1268                                << ". Trying to correct this."  << endl;
1269                         newdepth = copy.depth() - 1;
1270                 }
1271                 copy.pop();
1272         }
1273         // shrink cursor to a size where everything is valid, possibly
1274         // leaving insets
1275         while (depth() > newdepth) {
1276                 pop();
1277                 lyxerr << "correcting cursor to level " << depth() << endl;
1278         }
1279 }