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