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