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