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