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