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