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