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