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