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