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