]> git.lyx.org Git - lyx.git/blob - src/cursor.C
02c83938ac1f3265b25249fb4d2bf1e4df1b80ab
[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 "buffer.h"
16 #include "BufferView.h"
17 #include "cursor.h"
18 #include "debug.h"
19 #include "dispatchresult.h"
20 #include "funcrequest.h"
21 #include "iterators.h"
22 #include "lfuns.h"
23 #include "lyxfunc.h" // only for setMessage()
24 #include "lyxrc.h"
25 #include "lyxrow.h"
26 #include "lyxtext.h"
27 #include "paragraph.h"
28
29 #include "insets/updatableinset.h"
30 #include "insets/insettabular.h"
31 #include "insets/insettext.h"
32
33 #include "mathed/math_data.h"
34 #include "mathed/math_hullinset.h"
35 #include "mathed/math_support.h"
36
37 #include "support/limited_stack.h"
38 #include "frontends/LyXView.h"
39
40 #include <boost/assert.hpp>
41
42 using std::string;
43 using std::vector;
44 using std::endl;
45 #ifndef CXX_GLOBAL_CSTD
46 using std::isalpha;
47 #endif
48 using std::min;
49 using std::swap;
50
51
52
53 // our own cut buffer
54 limited_stack<string> theCutBuffer;
55
56
57 LCursor::LCursor(BufferView & bv)
58         : cursor_(1), anchor_(1), bv_(&bv), current_(0),
59           cached_y_(0), x_target_(-1),
60           selection_(false), mark_(false)
61 {}
62
63
64 void LCursor::reset()
65 {
66         cursor_.clear();
67         anchor_.clear();
68         cursor_.push_back(CursorSlice());
69         anchor_.push_back(CursorSlice());
70         current_ = 0;
71         cached_y_ = 0;
72         clearTargetX();
73         selection_ = false;
74         mark_ = false;
75 }
76
77
78 DispatchResult LCursor::dispatch(FuncRequest const & cmd0)
79 {
80         //lyxerr << "\nLCursor::dispatch: cmd: " << cmd0 << endl << *this << endl;
81         FuncRequest cmd = cmd0;
82         for (current_ = cursor_.size() - 1; current_ >= 1; --current_) {
83                 lyxerr << "trying to dispatch to inset " << inset() << endl;
84                 DispatchResult res = inset()->dispatch(*this, cmd);
85                 if (res.dispatched()) {
86                         lyxerr << " successfully dispatched to inset " << inset() << endl;
87                         return DispatchResult(true, true);
88                 }
89                 // "Mutate" the request for semi-handled requests that need
90                 // additional handling in outer levels.
91                 switch (res.val()) {
92                         case FINISHED:
93                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
94                                 break;
95                         case FINISHED_RIGHT:
96                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
97                                 break;
98                         case FINISHED_UP:
99                                 cmd = FuncRequest(LFUN_FINISHED_UP);
100                                 break;
101                         case FINISHED_DOWN:
102                                 cmd = FuncRequest(LFUN_FINISHED_DOWN);
103                                 break;
104                         default:
105                                 //lyxerr << "not handled on level " << current_
106                                 //      << " val: " << res.val() << endl;
107                                 break;
108                 }
109         }
110         BOOST_ASSERT(current_ == 0);
111         lyxerr << "trying to dispatch to main text " << bv_->text()
112                 << " with cursor: " << *this << endl;
113         DispatchResult res = bv_->text()->dispatch(*this, cmd);
114         //lyxerr << "   result: " << res.val() << endl;
115         return res;
116 }
117
118
119 void LCursor::push(InsetBase * inset)
120 {
121         lyxerr << "LCursor::push()  inset: " << inset << endl;
122         cursor_.push_back(CursorSlice(inset));
123         anchor_.push_back(CursorSlice(inset));
124         ++current_;
125         updatePos();
126 }
127
128
129 void LCursor::pop(int depth)
130 {
131         while (int(cursor_.size()) > depth + 1)
132                 pop();
133         lyxerr << "LCursor::pop() result: " << *this << endl;
134 }
135
136
137 void LCursor::pop()
138 {
139         BOOST_ASSERT(cursor_.size() >= 1);
140         cursor_.pop_back();
141         anchor_.pop_back();
142         current_ = cursor_.size() - 1;
143 }
144
145
146 void LCursor::pushLeft(InsetBase * p)
147 {
148         BOOST_ASSERT(!cursor_.empty());
149         //lyxerr << "Entering inset " << t << " left" << endl;
150         push(p);
151         p->idxFirst(*this);
152 }
153
154
155 bool LCursor::popLeft()
156 {
157         BOOST_ASSERT(!cursor_.empty());
158         //lyxerr << "Leaving inset to the left" << endl;
159         if (depth() <= 1) {
160                 if (depth() == 1)
161                         inset()->notifyCursorLeaves(idx());
162                 return false;
163         }
164         inset()->notifyCursorLeaves(idx());
165         pop();
166         return true;
167 }
168
169
170 bool LCursor::popRight()
171 {
172         BOOST_ASSERT(!cursor_.empty());
173         //lyxerr << "Leaving inset to the right" << endl;
174         if (depth() <= 1) {
175                 if (depth() == 1)
176                         inset()->notifyCursorLeaves(idx());
177                 return false;
178         }
179         inset()->notifyCursorLeaves(idx());
180         pop();
181         posRight();
182         return true;
183 }
184
185
186 CursorSlice & LCursor::current()
187 {
188         BOOST_ASSERT(!cursor_.empty());
189         //lyxerr << "accessing cursor slice " << current_
190         //      << ": " << cursor_[current_] << endl;
191         return cursor_[current_];
192 }
193
194
195 CursorSlice const & LCursor::current() const
196 {
197         //lyxerr << "accessing cursor slice " << current_
198         //      << ": " << cursor_[current_] << endl;
199         return cursor_[current_];
200 }
201
202
203 int LCursor::currentMode()
204 {
205         BOOST_ASSERT(!cursor_.empty());
206         for (int i = cursor_.size() - 1; i >= 1; --i) {
207                 int res = cursor_[i].inset()->currentMode();
208                 if (res != MathInset::UNDECIDED_MODE)
209                         return res;
210         }
211         return MathInset::TEXT_MODE;
212 }
213
214
215 LyXText * LCursor::innerText() const
216 {
217         BOOST_ASSERT(!cursor_.empty());
218         //lyxerr << "LCursor::innerText()  depth: " << cursor_.size() << endl;
219         if (cursor_.size() > 1) {
220                 // go up until first non-0 text is hit
221                 // (innermost text is 0 in mathed)
222                 for (int i = cursor_.size() - 1; i >= 1; --i)
223                         if (cursor_[i].text())
224                                 return cursor_[i].text();
225         }
226         return bv_->text();
227 }
228
229
230 CursorSlice const & LCursor::innerTextSlice() const
231 {
232         BOOST_ASSERT(!cursor_.empty());
233         //lyxerr << "LCursor::innerTextSlice()  depth: " << cursor_.size() << endl;
234         if (cursor_.size() > 1) {
235                 // go up until first non-0 text is hit
236                 // (innermost text is 0 in mathed)
237                 for (int i = cursor_.size() - 1; i >= 1; --i)
238                         if (cursor_[i].text())
239                                 return cursor_[i];
240         }
241         return cursor_[0];
242 }
243
244
245 void LCursor::updatePos()
246 {
247         BOOST_ASSERT(!cursor_.empty());
248         if (cursor_.size() > 1)
249                 cached_y_ = bv_->top_y() + cursor_.back().inset()->yo();
250                 //cached_y_ = cursor_.back().inset()->yo();
251 }
252
253
254 void LCursor::getDim(int & asc, int & des) const
255 {
256         BOOST_ASSERT(!cursor_.empty());
257         LyXText * text = innerText();
258 #warning crashes with text-in-math
259         if (0 && text) {
260                 RowList::iterator const rit = text->cursorRow();
261                 if (rit != text->endRow()) {
262                         asc = rit->baseline();
263                         des = rit->height() - asc;
264                 } else {
265                         asc = 10;
266                         des = 10;
267                 }
268         } else {
269                 asc = 10;
270                 des = 10;
271                 //innerInset()->getCursorDim(asc, des);
272         }
273 }
274
275
276 void LCursor::getPos(int & x, int & y) const
277 {
278         BOOST_ASSERT(!cursor_.empty());
279         x = 0;
280         y = 0;
281         if (cursor_.size() <= 1) {
282                 x = bv_->text()->cursorX(cursor_.front());
283                 y = bv_->text()->cursorY(cursor_.front());
284         } else {
285                 inset()->getCursorPos(cursor_.back(), x, y);
286                 // getCursorPos gives _screen_ coordinates. We need to add
287                 // top_y to get document coordinates. This is hidden in cached_y_.
288                 //y += cached_y_ - inset()->yo();
289                 // The rest is non-obvious. The reason we have to have these
290                 // extra computation is that the getCursorPos() calls rely
291                 // on the inset's own knowledge of its screen position.
292                 // If we scroll up or down in a big enough increment,
293                 // inset->draw() is not called: this doesn't update
294                 // inset.yo_, so getCursor() returns an old value.
295                 // Ugly as you like.
296         }
297         //lyxerr << "#### LCursor::getPos: " << *this 
298         // << " x: " << x << " y: " << y << endl;
299 }
300
301
302 void LCursor::paste(string const & data)
303 {
304         dispatch(FuncRequest(LFUN_PASTE, data));
305 }
306
307
308 InsetBase * LCursor::innerInsetOfType(int code) const
309 {
310         for (int i = cursor_.size() - 1; i >= 1; --i)
311                 if (cursor_[i].inset_->lyxCode() == code)
312                         return cursor_[i].inset_;
313         return 0;
314 }
315
316
317 InsetTabular * LCursor::innerInsetTabular() const
318 {
319         return static_cast<InsetTabular *>(innerInsetOfType(InsetBase::TABULAR_CODE));
320 }
321
322
323 void LCursor::resetAnchor()
324 {
325         anchor_ = cursor_;
326 }
327
328
329 BufferView & LCursor::bv() const
330 {
331         return *bv_;
332 }
333
334
335 MathAtom const & LCursor::prevAtom() const
336 {
337         BOOST_ASSERT(pos() > 0);
338         return cell()[pos() - 1];
339 }
340
341
342 MathAtom & LCursor::prevAtom()
343 {
344         BOOST_ASSERT(pos() > 0);
345         return cell()[pos() - 1];
346 }
347
348
349 MathAtom const & LCursor::nextAtom() const
350 {
351         BOOST_ASSERT(pos() < lastpos());
352         return cell()[pos()];
353 }
354
355
356 MathAtom & LCursor::nextAtom()
357 {
358         BOOST_ASSERT(pos() < lastpos());
359         return cell()[pos()];
360 }
361
362
363 bool LCursor::posLeft()
364 {
365         if (pos() == 0)
366                 return false;
367         --pos();
368         return true;
369 }
370
371
372 bool LCursor::posRight()
373 {
374         if (pos() == lastpos())
375                 return false;
376         ++pos();
377         return true;
378 }
379
380
381 CursorSlice & LCursor::anchor()
382 {
383         return anchor_.back();
384 }
385
386
387 CursorSlice const & LCursor::anchor() const
388 {
389         return anchor_.back();
390 }
391
392
393 CursorSlice const & LCursor::selBegin() const
394 {
395         if (!selection())
396                 return cursor_.back();
397         // can't use std::min as this creates a new object
398         return anchor() < cursor_.back() ? anchor() : cursor_.back();
399 }
400
401
402 CursorSlice & LCursor::selBegin()
403 {
404         if (!selection())
405                 return cursor_.back();
406         return anchor() < cursor_.back() ? anchor() : cursor_.back();
407 }
408
409
410 CursorSlice const & LCursor::selEnd() const
411 {
412         if (!selection())
413                 return cursor_.back();
414         return anchor() > cursor_.back() ? anchor() : cursor_.back();
415 }
416
417
418 CursorSlice & LCursor::selEnd()
419 {
420         if (selection())
421                 return cursor_.back();
422         return anchor() > cursor_.back() ? anchor() : cursor_.back();
423 }
424
425
426 void LCursor::setSelection()
427 {
428         selection() = true;
429         // a selection with no contents is not a selection
430         if (par() == anchor().par() && pos() == anchor().pos())
431                 selection() = false;
432 }
433
434
435 void LCursor::setSelection(CursorBase const & where, size_t n)
436 {
437         selection() = true;
438         cursor_ = where;
439         anchor_ = where;
440         pos() += n;
441 }
442
443
444 void LCursor::clearSelection()
445 {
446         selection() = false;
447         mark() = false;
448         resetAnchor();
449         bv().unsetXSel();
450 }
451
452
453 int & LCursor::x_target()
454 {
455         return x_target_;
456 }
457
458
459 int LCursor::x_target() const
460 {
461         return x_target_;
462 }
463
464
465 void LCursor::clearTargetX()
466 {
467         x_target_ = -1;
468 }
469
470
471 LyXText * LCursor::text() const
472 {
473         return current_ ? current().text() : bv_->text();
474 }
475
476
477 Paragraph & LCursor::paragraph()
478 {
479         BOOST_ASSERT(!inMathed());
480         return current_ ? current().paragraph() : *bv_->text()->getPar(par());
481 }
482
483
484 Paragraph const & LCursor::paragraph() const
485 {
486         BOOST_ASSERT(!inMathed());
487         return current_ ? current().paragraph() : *bv_->text()->getPar(par());
488 }
489
490
491 LCursor::par_type LCursor::lastpar() const
492 {
493         return inMathed() ? 0 : text()->paragraphs().size() - 1;
494 }
495
496
497 LCursor::pos_type LCursor::lastpos() const
498 {
499         InsetBase * inset = current().inset();
500         return inset && inset->asMathInset() ? cell().size() : paragraph().size();
501 }
502
503
504 LCursor::row_type LCursor::crow() const
505 {
506         return paragraph().row(pos());
507 }
508
509
510 LCursor::row_type LCursor::lastcrow() const
511 {
512         return paragraph().rows.size();
513 }
514
515
516 size_t LCursor::nargs() const
517 {
518         // assume 1x1 grid for 'plain text'
519         return current_ ? current().nargs() : 1;
520 }
521
522
523 size_t LCursor::ncols() const
524 {
525         // assume 1x1 grid for 'plain text'
526         return current_ ? current().ncols() : 1;
527 }
528
529
530 size_t LCursor::nrows() const
531 {
532         // assume 1x1 grid for 'plain text'
533         return current_ ? current().nrows() : 1;
534 }
535
536
537 LCursor::row_type LCursor::row() const
538 {
539         BOOST_ASSERT(current_ > 0);
540         return current().row();
541 }
542
543
544 LCursor::col_type LCursor::col() const
545 {
546         BOOST_ASSERT(current_ > 0);
547         return current().col();
548 }
549
550
551 MathArray const & LCursor::cell() const
552 {
553         BOOST_ASSERT(current_ > 0);
554         return current().cell();
555 }
556
557
558 MathArray & LCursor::cell()
559 {
560         BOOST_ASSERT(current_ > 0);
561         return current().cell();
562 }
563
564
565 void LCursor::info(std::ostream & os)
566 {
567         for (int i = 1, n = depth(); i < n; ++i) {
568                 cursor_[i].inset()->infoize(os);
569                 os << "  ";
570         }
571         if (pos() != 0)
572                 prevInset()->infoize2(os);
573         // overwite old message
574         os << "                    ";
575 }
576
577
578 namespace {
579
580 void region(CursorSlice const & i1, CursorSlice const & i2,
581         LCursor::row_type & r1, LCursor::row_type & r2,
582         LCursor::col_type & c1, LCursor::col_type & c2)
583 {
584         InsetBase * p = i1.inset();
585         c1 = p->col(i1.idx_);
586         c2 = p->col(i2.idx_);
587         if (c1 > c2)
588                 swap(c1, c2);
589         r1 = p->row(i1.idx_);
590         r2 = p->row(i2.idx_);
591         if (r1 > r2)
592                 swap(r1, r2);
593 }
594
595 }
596
597
598 string LCursor::grabSelection()
599 {
600         if (!selection())
601                 return string();
602
603         CursorSlice i1 = selBegin();
604         CursorSlice i2 = selEnd();
605
606         if (i1.idx_ == i2.idx_) {
607                 if (i1.inset()->asMathInset()) {
608                         MathArray::const_iterator it = i1.cell().begin();
609                         return asString(MathArray(it + i1.pos_, it + i2.pos_));
610                 } else {
611                         return "unknown selection 1";
612                 }
613         }
614
615         row_type r1, r2;
616         col_type c1, c2;
617         region(i1, i2, r1, r2, c1, c2);
618
619         string data;
620         if (i1.inset()->asMathInset()) {
621                 for (row_type row = r1; row <= r2; ++row) {
622                         if (row > r1)
623                                 data += "\\\\";
624                         for (col_type col = c1; col <= c2; ++col) {
625                                 if (col > c1)
626                                         data += '&';
627                                 data += asString(i1.asMathInset()->cell(i1.asMathInset()->index(row, col)));
628                         }
629                 }
630         } else {
631                 data = "unknown selection 2";
632         }
633         return data;
634 }
635
636
637 void LCursor::eraseSelection()
638 {
639         CursorSlice i1 = selBegin();
640         CursorSlice i2 = selEnd();
641 #warning FIXME
642         if (i1.inset()->asMathInset()) {
643                 if (i1.idx_ == i2.idx_) {
644                         i1.cell().erase(i1.pos_, i2.pos_);
645                 } else {
646                         MathInset * p = i1.asMathInset();
647                         row_type r1, r2;
648                         col_type c1, c2;
649                         region(i1, i2, r1, r2, c1, c2);
650                         for (row_type row = r1; row <= r2; ++row)
651                                 for (col_type col = c1; col <= c2; ++col)
652                                         p->cell(p->index(row, col)).clear();
653                 }
654                 current() = i1;
655         } else {
656                 lyxerr << "can't erase this selection 1" << endl;
657         }
658 }
659
660
661 string LCursor::grabAndEraseSelection()
662 {
663         if (!selection())
664                 return string();
665         string res = grabSelection();
666         eraseSelection();
667         selection() = false;
668         return res;
669 }
670
671
672 void LCursor::selClear()
673 {
674         resetAnchor();
675         clearSelection();
676 }
677
678
679 void LCursor::selCopy()
680 {
681         if (selection()) {
682                 theCutBuffer.push(grabSelection());
683                 selection() = false;
684         } else {
685                 //theCutBuffer.erase();
686         }
687 }
688
689
690 void LCursor::selCut()
691 {
692         theCutBuffer.push(grabAndEraseSelection());
693 }
694
695
696 void LCursor::selDel()
697 {
698         if (selection()) {
699                 eraseSelection();
700                 selection() = false;
701         }
702 }
703
704
705 void LCursor::selPaste(size_t n)
706 {
707         selClearOrDel();
708         if (n < theCutBuffer.size())
709                 paste(theCutBuffer[n]);
710         //grabSelection();
711         selection() = false;
712 }
713
714
715 void LCursor::selHandle(bool sel)
716 {
717         if (sel == selection())
718                 return;
719         resetAnchor();
720         selection() = sel;
721 }
722
723
724 void LCursor::selStart()
725 {
726         resetAnchor();
727         selection() = true;
728 }
729
730
731 void LCursor::selClearOrDel()
732 {
733         if (lyxrc.auto_region_delete)
734                 selDel();
735         else
736                 selection() = false;
737 }
738
739
740 std::ostream & operator<<(std::ostream & os, LCursor const & cur)
741 {
742         os << "\n";
743         for (size_t i = 0, n = cur.cursor_.size(); i != n; ++i)
744                 os << "  (" << cur.cursor_[i] << " | " << cur.anchor_[i] << "\n";
745         return os << "current: " << cur.current_ << endl;
746 }
747
748
749
750
751 //
752 // CursorBase
753 //
754
755
756 void increment(CursorBase & it)
757 {
758         CursorSlice & top = it.back();
759         MathArray & ar = top.asMathInset()->cell(top.idx_);
760
761         // move into the current inset if possible
762         // it is impossible for pos() == size()!
763         MathInset * n = 0;
764         if (top.pos() != top.lastpos())
765                 n = (ar.begin() + top.pos_)->nucleus();
766         if (n && n->isActive()) {
767                 it.push_back(CursorSlice(n));
768                 return;
769         }
770
771         // otherwise move on one cell back if possible
772         if (top.pos() < top.lastpos()) {
773                 // pos() == lastpos() is valid!
774                 ++top.pos_;
775                 return;
776         }
777
778         // otherwise try to move on one cell if possible
779         while (top.idx() < top.lastidx()) {
780                 ++top.idx_;
781                 if (top.asMathInset()->validCell(top.idx_)) {
782                         top.pos_ = 0;
783                         return;
784                 }
785         }
786
787         // otherwise leave array, move on one back
788         // this might yield pos() == size(), but that's a ok.
789         it.pop_back();
790         // it certainly invalidates top
791         ++it.back().pos_;
792 }
793
794
795 CursorBase ibegin(InsetBase * p)
796 {
797         CursorBase it;
798         it.push_back(CursorSlice(p));
799         return it;
800 }
801
802
803 CursorBase iend(InsetBase * p)
804 {
805         CursorBase it;
806         it.push_back(CursorSlice(p));
807         CursorSlice & cur = it.back();
808         cur.idx() = cur.lastidx();
809         cur.pos() = cur.lastpos();
810         return it;
811 }
812
813
814
815
816 ///////////////////////////////////////////////////////////////////
817 //
818 // The part below is the non-integrated rest of the original math
819 // cursor. This should be either generalized for texted or moved
820 // back to the math insets.
821 //
822 ///////////////////////////////////////////////////////////////////
823
824 #include "mathed/math_braceinset.h"
825 #include "mathed/math_charinset.h"
826 #include "mathed/math_commentinset.h"
827 #include "mathed/math_factory.h"
828 #include "mathed/math_gridinset.h"
829 #include "mathed/math_macroarg.h"
830 #include "mathed/math_macrotemplate.h"
831 #include "mathed/math_mathmlstream.h"
832 #include "mathed/math_scriptinset.h"
833 #include "mathed/math_spaceinset.h"
834 #include "mathed/math_support.h"
835 #include "mathed/math_unknowninset.h"
836
837 //#define FILEDEBUG 1
838
839
840 bool LCursor::isInside(InsetBase const * p)
841 {
842         for (unsigned i = 0; i < depth(); ++i)
843                 if (cursor_[i].inset() == p)
844                         return true;
845         return false;
846 }
847
848
849 bool LCursor::openable(MathAtom const & t)
850 {
851         if (!t->isActive())
852                 return false;
853
854         if (t->lock())
855                 return false;
856
857         if (!selection())
858                 return true;
859
860         // we can't move into anything new during selection
861         if (depth() == anchor_.size())
862                 return false;
863         if (!ptr_cmp(t.nucleus(), anchor_[depth()].inset()))
864                 return false;
865
866         return true;
867 }
868
869
870 bool LCursor::inNucleus()
871 {
872         return inset()->asMathInset()->asScriptInset() && idx() == 2;
873 }
874
875
876 bool LCursor::left()
877 {
878         autocorrect() = false;
879         clearTargetX();
880         if (inMacroMode()) {
881                 macroModeClose();
882                 return true;
883         }
884
885         if (pos() != 0 && openable(prevAtom())) {
886                 posLeft();
887                 push(nextAtom().nucleus());
888                 inset()->idxLast(*this);
889                 return true;
890         }
891
892         return posLeft() || idxLeft() || popLeft() || selection();
893 }
894
895
896 bool LCursor::right()
897 {
898         autocorrect() = false;
899         clearTargetX();
900         if (inMacroMode()) {
901                 macroModeClose();
902                 return true;
903         }
904
905         if (pos() != lastpos() && openable(nextAtom())) {
906                 pushLeft(nextAtom().nucleus());
907                 inset()->idxFirst(*this);
908                 return true;
909         }
910
911         return posRight() || idxRight() || popRight() || selection();
912 }
913
914
915 bool positionable(CursorBase const & cursor, CursorBase const & anchor)
916 {
917         // avoid deeper nested insets when selecting
918         if (cursor.size() > anchor.size())
919                 return false;
920
921         // anchor might be deeper, should have same path then
922         for (size_t i = 0; i < cursor.size(); ++i)
923                 if (cursor[i].inset() != anchor[i].inset())
924                         return false;
925
926         // position should be ok.
927         return true;
928 }
929
930
931 void LCursor::setScreenPos(int x, int y)
932 {
933         bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
934                 formula()->ylow(), formula()->yhigh());
935         if (!res) {
936                 // this can happen on creation of "math-display"
937                 idx() = 0;
938                 pos() = 0;
939         }
940         clearTargetX();
941 }
942
943
944
945 bool LCursor::home()
946 {
947         autocorrect() = false;
948         macroModeClose();
949         if (!inset()->idxHome(*this))
950                 return popLeft();
951         clearTargetX();
952         return true;
953 }
954
955
956 bool LCursor::end()
957 {
958         autocorrect() = false;
959         macroModeClose();
960         if (!inset()->idxEnd(*this))
961                 return popRight();
962         clearTargetX();
963         return true;
964 }
965
966
967 void LCursor::plainErase()
968 {
969         cell().erase(pos());
970 }
971
972
973 void LCursor::markInsert()
974 {
975         cell().insert(pos(), MathAtom(new MathCharInset(0)));
976 }
977
978
979 void LCursor::markErase()
980 {
981         cell().erase(pos());
982 }
983
984
985 void LCursor::plainInsert(MathAtom const & t)
986 {
987         cell().insert(pos(), t);
988         ++pos();
989 }
990
991
992 void LCursor::insert2(string const & str)
993 {
994         MathArray ar;
995         asArray(str, ar);
996         insert(ar);
997 }
998
999
1000 void LCursor::insert(string const & str)
1001 {
1002         lyxerr << "inserting '" << str << "'" << endl;
1003         selClearOrDel();
1004         for (string::const_iterator it = str.begin(); it != str.end(); ++it)
1005                 plainInsert(MathAtom(new MathCharInset(*it)));
1006 }
1007
1008
1009 void LCursor::insert(char c)
1010 {
1011         lyxerr << "inserting '" << c << "'" << endl;
1012         selClearOrDel();
1013         plainInsert(MathAtom(new MathCharInset(c)));
1014 }
1015
1016
1017 void LCursor::insert(MathAtom const & t)
1018 {
1019         macroModeClose();
1020         selClearOrDel();
1021         plainInsert(t);
1022 }
1023
1024
1025 void LCursor::niceInsert(string const & t)
1026 {
1027         lyxerr << "*** LCursor::niceInsert 1: " << t << endl;
1028         MathArray ar;
1029         asArray(t, ar);
1030         if (ar.size() == 1)
1031                 niceInsert(ar[0]);
1032         else
1033                 insert(ar);
1034 }
1035
1036
1037 void LCursor::niceInsert(MathAtom const & t)
1038 {
1039         lyxerr << "*** LCursor::niceInsert 2: " << t << endl;
1040         macroModeClose();
1041         string safe = grabAndEraseSelection();
1042         plainInsert(t);
1043         // enter the new inset and move the contents of the selection if possible
1044         if (t->isActive()) {
1045                 posLeft();
1046                 pushLeft(nextAtom().nucleus());
1047                 paste(safe);
1048         }
1049         lyxerr << "*** LCursor::niceInsert 3: " << t << endl;
1050 }
1051
1052
1053 void LCursor::insert(MathArray const & ar)
1054 {
1055         macroModeClose();
1056         if (selection())
1057                 eraseSelection();
1058         cell().insert(pos(), ar);
1059         pos() += ar.size();
1060 }
1061
1062
1063 bool LCursor::backspace()
1064 {
1065         autocorrect() = false;
1066
1067         if (selection()) {
1068                 selDel();
1069                 return true;
1070         }
1071
1072         if (pos() == 0) {
1073                 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1074                         return false;
1075                 pullArg();
1076                 return true;
1077         }
1078
1079         if (inMacroMode()) {
1080                 MathUnknownInset * p = activeMacro();
1081                 if (p->name().size() > 1) {
1082                         p->setName(p->name().substr(0, p->name().size() - 1));
1083                         return true;
1084                 }
1085         }
1086
1087         if (pos() != 0 && prevAtom()->nargs() > 0) {
1088                 // let's require two backspaces for 'big stuff' and
1089                 // highlight on the first
1090                 selection() = true;
1091                 left();
1092         } else {
1093                 --pos();
1094                 plainErase();
1095         }
1096         return true;
1097 }
1098
1099
1100 bool LCursor::erase()
1101 {
1102         autocorrect() = false;
1103         if (inMacroMode())
1104                 return true;
1105
1106         if (selection()) {
1107                 selDel();
1108                 return true;
1109         }
1110
1111         // delete empty cells if possible
1112         if (pos() == lastpos() && inset()->idxDelete(idx()))
1113                 return true;
1114
1115         // special behaviour when in last position of cell
1116         if (pos() == lastpos()) {
1117                 bool one_cell = inset()->nargs() == 1;
1118                 if (one_cell && depth() == 1 && lastpos() == 0)
1119                         return false;
1120                 // remove markup
1121                 if (one_cell)
1122                         pullArg();
1123                 else
1124                         inset()->idxGlue(idx());
1125                 return true;
1126         }
1127
1128         if (pos() != lastpos() && inset()->nargs() > 0) {
1129                 selection() = true;
1130                 right();
1131         } else {
1132                 plainErase();
1133         }
1134
1135         return true;
1136 }
1137
1138
1139 bool LCursor::up()
1140 {
1141         macroModeClose();
1142         CursorBase save = cursor_;
1143         if (goUpDown(true))
1144                 return true;
1145         cursor_ = save;
1146         autocorrect() = false;
1147         return selection();
1148 }
1149
1150
1151 bool LCursor::down()
1152 {
1153         macroModeClose();
1154         CursorBase save = cursor_;
1155         if (goUpDown(false))
1156                 return true;
1157         cursor_ = save;
1158         autocorrect() = false;
1159         return selection();
1160 }
1161
1162
1163 void LCursor::macroModeClose()
1164 {
1165         if (!inMacroMode())
1166                 return;
1167         MathUnknownInset * p = activeMacro();
1168         p->finalize();
1169         string s = p->name();
1170         --pos();
1171         cell().erase(pos());
1172
1173         // do nothing if the macro name is empty
1174         if (s == "\\")
1175                 return;
1176
1177         string const name = s.substr(1);
1178
1179         // prevent entering of recursive macros
1180         if (formula()->lyxCode() == InsetOld::MATHMACRO_CODE
1181                         && formula()->getInsetName() == name)
1182                 lyxerr << "can't enter recursive macro" << endl;
1183
1184         niceInsert(createMathInset(name));
1185 }
1186
1187
1188 string LCursor::macroName()
1189 {
1190         return inMacroMode() ? activeMacro()->name() : string();
1191 }
1192
1193
1194 void LCursor::handleNest(MathAtom const & a, int c)
1195 {
1196         MathAtom t = a;
1197         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1198         insert(t);
1199         posLeft();
1200         pushLeft(t.nucleus());
1201 }
1202
1203
1204 int LCursor::targetX() const
1205 {
1206         if (x_target() != -1)
1207                 return x_target();
1208         int x = 0;
1209         int y = 0;
1210         getPos(x, y);
1211         return x;
1212 }
1213
1214
1215 MathHullInset * LCursor::formula() const
1216 {
1217         for (int i = cursor_.size() - 1; i >= 1; --i)
1218                 if (cursor_[i].inset()->lyxCode() == InsetBase::MATH_CODE)
1219                         return static_cast<MathHullInset *>(cursor_[i].inset());
1220         return 0;
1221 }
1222
1223
1224 void LCursor::adjust(pos_type from, int diff)
1225 {
1226         if (pos() > from)
1227                 pos() += diff;
1228         if (anchor().pos_ > from)
1229                 anchor().pos_ += diff;
1230         // just to be on the safe side
1231         // theoretically unecessary
1232         normalize();
1233 }
1234
1235
1236 bool LCursor::inMacroMode() const
1237 {
1238         if (!pos() != 0)
1239                 return false;
1240         MathUnknownInset const * p = prevAtom()->asUnknownInset();
1241         return p && !p->final();
1242 }
1243
1244
1245 MathUnknownInset * LCursor::activeMacro()
1246 {
1247         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1248 }
1249
1250
1251 bool LCursor::inMacroArgMode() const
1252 {
1253         return pos() > 0 && prevAtom()->getChar() == '#';
1254 }
1255
1256
1257 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1258 {
1259         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1260                 MathInset * m = cursor_[i].inset()->asMathInset();
1261                 if (!m)
1262                         return 0;
1263                 MathGridInset * p = m->asGridInset();
1264                 if (p) {
1265                         idx = cursor_[i].idx_;
1266                         return p;
1267                 }
1268         }
1269         return 0;
1270 }
1271
1272
1273 void LCursor::pullArg()
1274 {
1275 #warning look here
1276 #if 0
1277         MathArray ar = cell();
1278         if (popLeft()) {
1279                 plainErase();
1280                 cell().insert(pos(), ar);
1281                 resetAnchor();
1282         } else {
1283                 formula()->mutateToText();
1284         }
1285 #endif
1286 }
1287
1288
1289 void LCursor::touch()
1290 {
1291 #warning look here
1292 #if 0
1293         CursorBase::const_iterator it = cursor_.begin();
1294         CursorBase::const_iterator et = cursor_.end();
1295         for ( ; it != et; ++it)
1296                 it->cell().touch();
1297 #endif
1298 }
1299
1300
1301 void LCursor::normalize()
1302 {
1303         if (idx() >= nargs()) {
1304                 lyxerr << "this should not really happen - 1: "
1305                        << idx() << ' ' << nargs()
1306                        << " in: " << inset() << endl;
1307         }
1308         idx() = min(idx(), lastidx());
1309
1310         if (pos() > lastpos()) {
1311                 lyxerr << "this should not really happen - 2: "
1312                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1313                        << " in atom: '";
1314                 WriteStream wi(lyxerr, false, true);
1315                 inset()->asMathInset()->write(wi);
1316                 lyxerr << endl;
1317         }
1318         pos() = min(pos(), lastpos());
1319 }
1320
1321
1322 char LCursor::valign()
1323 {
1324         idx_type idx;
1325         MathGridInset * p = enclosingGrid(idx);
1326         return p ? p->valign() : '\0';
1327 }
1328
1329
1330 char LCursor::halign()
1331 {
1332         idx_type idx;
1333         MathGridInset * p = enclosingGrid(idx);
1334         return p ? p->halign(idx % p->ncols()) : '\0';
1335 }
1336
1337
1338 bool LCursor::goUpDown(bool up)
1339 {
1340         // Be warned: The 'logic' implemented in this function is highly fragile.
1341         // A distance of one pixel or a '<' vs '<=' _really_ matters.
1342         // So fiddle around with it only if you know what you are doing!
1343   int xo = 0;
1344         int yo = 0;
1345         getPos(xo, yo);
1346
1347         // check if we had something else in mind, if not, this is the future goal
1348         if (x_target() == -1)
1349                 x_target() = xo;
1350         else
1351                 xo = x_target();
1352
1353         // try neigbouring script insets
1354         if (!selection()) {
1355                 // try left
1356                 if (pos() != 0) {
1357                         MathScriptInset const * p = prevAtom()->asScriptInset();
1358                         if (p && p->has(up)) {
1359                                 --pos();
1360                                 push(inset());
1361                                 idx() = up; // the superscript has index 1
1362                                 pos() = lastpos();
1363                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1364                                 return true;
1365                         }
1366                 }
1367
1368                 // try right
1369                 if (pos() != lastpos()) {
1370                         MathScriptInset const * p = nextAtom()->asScriptInset();
1371                         if (p && p->has(up)) {
1372                                 push(inset());
1373                                 idx() = up;
1374                                 pos() = 0;
1375                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1376                                 return true;
1377                         }
1378                 }
1379         }
1380
1381         // try current cell for e.g. text insets
1382         if (inset()->idxUpDown2(*this, up))
1383                 return true;
1384
1385         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1386         //if (up)
1387         //      yhigh = yo - 4;
1388         //else
1389         //      ylow = yo + 4;
1390         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1391         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1392         //      return true;
1393         //}
1394
1395         // try to find an inset that knows better then we
1396         while (1) {
1397                 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1398                 // ask inset first
1399                 if (inset()->idxUpDown(*this, up)) {
1400                         // try to find best position within this inset
1401                         if (!selection())
1402                                 bruteFind2(xo, yo);
1403                         return true;
1404                 }
1405
1406                 // no such inset found, just take something "above"
1407                 //lyxerr << "updown: handled by strange case" << endl;
1408                 if (!popLeft()) {
1409                         return
1410                                 bruteFind(xo, yo,
1411                                         formula()->xlow(),
1412                                         formula()->xhigh(),
1413                                         up ? formula()->ylow() : yo + 4,
1414                                         up ? yo - 4 : formula()->yhigh()
1415                                 );
1416                 }
1417
1418                 // any improvement so far?
1419                 int xnew, ynew;
1420                 getPos(xnew, ynew);
1421                 if (up ? ynew < yo : ynew > yo)
1422                         return true;
1423         }
1424 }
1425
1426
1427 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1428 {
1429         CursorBase best_cursor;
1430         double best_dist = 1e10;
1431
1432         CursorBase it = ibegin(formula());
1433         CursorBase et = iend(formula());
1434         while (1) {
1435                 // avoid invalid nesting when selecting
1436                 if (!selection() || positionable(it, anchor_)) {
1437                         int xo, yo;
1438                         CursorSlice & cur = it.back();
1439                         cur.inset()->getCursorPos(cur, xo, yo);
1440                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1441                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1442                                 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1443                                 // '<=' in order to take the last possible position
1444                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1445                                 if (d <= best_dist) {
1446                                         best_dist   = d;
1447                                         best_cursor = it;
1448                                 }
1449                         }
1450                 }
1451
1452                 if (it == et)
1453                         break;
1454                 increment(it);
1455         }
1456
1457         if (best_dist < 1e10)
1458                 cursor_ = best_cursor;
1459         return best_dist < 1e10;
1460 }
1461
1462
1463 void LCursor::bruteFind2(int x, int y)
1464 {
1465         double best_dist = 1e10;
1466
1467         CursorBase it = cursor_;
1468         it.back().pos(0);
1469         CursorBase et = cursor_;
1470         int n = et.back().asMathInset()->cell(et.back().idx_).size();
1471         et.back().pos(n);
1472         for (int i = 0; ; ++i) {
1473                 int xo, yo;
1474                 CursorSlice & cur = it.back();
1475                 cur.inset()->getCursorPos(cur, xo, yo);
1476                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1477                 // '<=' in order to take the last possible position
1478                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1479                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1480                 if (d <= best_dist) {
1481                         best_dist = d;
1482                         cursor_ = it;
1483                 }
1484                 if (it == et)
1485                         break;
1486                 increment(it);
1487         }
1488 }
1489
1490
1491 bool LCursor::idxLineLast()
1492 {
1493         idx() -= idx() % ncols();
1494         idx() += ncols() - 1;
1495         pos() = lastpos();
1496         return true;
1497 }
1498
1499
1500 bool LCursor::idxLeft()
1501 {
1502         return inset()->idxLeft(*this);
1503 }
1504
1505
1506 bool LCursor::idxRight()
1507 {
1508         return inset()->idxRight(*this);
1509 }
1510
1511
1512 bool LCursor::script(bool up)
1513 {
1514         // Hack to get \\^ and \\_ working
1515         lyxerr << "handling script: up: " << up << endl;
1516         if (inMacroMode() && macroName() == "\\") {
1517                 if (up)
1518                         niceInsert(createMathInset("mathcircumflex"));
1519                 else
1520                         interpret('_');
1521                 return true;
1522         }
1523
1524         macroModeClose();
1525         string safe = grabAndEraseSelection();
1526         if (inNucleus()) {
1527                 // we are in a nucleus of a script inset, move to _our_ script
1528                 inset()->asMathInset()->asScriptInset()->ensure(up);
1529                 idx() = up;
1530                 pos() = 0;
1531         } else if (pos() != 0 && prevAtom()->asScriptInset()) {
1532                 --pos();
1533                 nextAtom().nucleus()->asScriptInset()->ensure(up);
1534                 push(nextInset());
1535                 idx() = up;
1536                 pos() = lastpos();
1537         } else if (pos() != 0) {
1538                 --pos();
1539                 cell()[pos()] = MathAtom(new MathScriptInset(nextAtom(), up));
1540                 push(nextInset());
1541                 idx() = up;
1542                 pos() = 0;
1543         } else {
1544                 plainInsert(MathAtom(new MathScriptInset(up)));
1545                 --pos();
1546                 nextAtom().nucleus()->asScriptInset()->ensure(up);
1547                 push(nextInset());
1548                 idx() = up;
1549                 pos() = 0;
1550         }
1551         paste(safe);
1552         return true;
1553 }
1554
1555
1556 bool LCursor::interpret(char c)
1557 {
1558         //lyxerr << "interpret 2: '" << c << "'" << endl;
1559         clearTargetX();
1560         if (inMacroArgMode()) {
1561                 posLeft();
1562                 plainErase();
1563 #warning FIXME
1564 #if 0
1565                 int n = c - '0';
1566                 MathMacroTemplate const * p = formula()->asMacroTemplate();
1567                 if (p && 1 <= n && n <= p->numargs())
1568                         insert(MathAtom(new MathMacroArgument(c - '0')));
1569                 else {
1570                         insert(createMathInset("#"));
1571                         interpret(c); // try again
1572                 }
1573 #endif
1574                 return true;
1575         }
1576
1577         // handle macroMode
1578         if (inMacroMode()) {
1579                 string name = macroName();
1580                 //lyxerr << "interpret name: '" << name << "'" << endl;
1581
1582                 if (isalpha(c)) {
1583                         activeMacro()->setName(activeMacro()->name() + c);
1584                         return true;
1585                 }
1586
1587                 // handle 'special char' macros
1588                 if (name == "\\") {
1589                         // remove the '\\'
1590                         backspace();
1591                         if (c == '\\') {
1592                                 if (currentMode() == MathInset::TEXT_MODE)
1593                                         niceInsert(createMathInset("textbackslash"));
1594                                 else
1595                                         niceInsert(createMathInset("backslash"));
1596                         } else if (c == '{') {
1597                                 niceInsert(MathAtom(new MathBraceInset));
1598                         } else {
1599                                 niceInsert(createMathInset(string(1, c)));
1600                         }
1601                         return true;
1602                 }
1603
1604                 // leave macro mode and try again if necessary
1605                 macroModeClose();
1606                 if (c == '{')
1607                         niceInsert(MathAtom(new MathBraceInset));
1608                 else if (c != ' ')
1609                         interpret(c);
1610                 return true;
1611         }
1612
1613         // This is annoying as one has to press <space> far too often.
1614         // Disable it.
1615
1616         if (0) {
1617                 // leave autocorrect mode if necessary
1618                 if (autocorrect() && c == ' ') {
1619                         autocorrect() = false;
1620                         return true;
1621                 }
1622         }
1623
1624         // just clear selection on pressing the space bar
1625         if (selection() && c == ' ') {
1626                 selection() = false;
1627                 return true;
1628         }
1629
1630         selClearOrDel();
1631
1632         if (c == '\\') {
1633                 //lyxerr << "starting with macro" << endl;
1634                 insert(MathAtom(new MathUnknownInset("\\", false)));
1635                 return true;
1636         }
1637
1638         if (c == '\n') {
1639                 if (currentMode() == MathInset::TEXT_MODE)
1640                         insert(c);
1641                 return true;
1642         }
1643
1644         if (c == ' ') {
1645                 if (currentMode() == MathInset::TEXT_MODE) {
1646                         // insert spaces in text mode,
1647                         // but suppress direct insertion of two spaces in a row
1648                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1649                         // it is better than nothing...
1650                         if (!pos() != 0 || prevAtom()->getChar() != ' ')
1651                                 insert(c);
1652                         return true;
1653                 }
1654                 if (pos() != 0 && prevAtom()->asSpaceInset()) {
1655                         prevAtom().nucleus()->asSpaceInset()->incSpace();
1656                         return true;
1657                 }
1658                 if (popRight())
1659                         return true;
1660                 // if are at the very end, leave the formula
1661                 return pos() != lastpos();
1662         }
1663
1664         if (c == '_') {
1665                 script(false);
1666                 return true;
1667         }
1668
1669         if (c == '^') {
1670                 script(true);
1671                 return true;
1672         }
1673
1674         if (c == '{' || c == '}' || c == '#' || c == '&' || c == '$') {
1675                 niceInsert(createMathInset(string(1, c)));
1676                 return true;
1677         }
1678
1679         if (c == '%') {
1680                 niceInsert(MathAtom(new MathCommentInset));
1681                 return true;
1682         }
1683
1684         // try auto-correction
1685         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1686         //      return true;
1687
1688         // no special circumstances, so insert the character without any fuss
1689         insert(c);
1690         autocorrect() = true;
1691         return true;
1692 }
1693
1694
1695 void LCursor::lockToggle()
1696 {
1697         if (pos() != lastpos()) {
1698                 // toggle previous inset ...
1699                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1700         } else if (popLeft() && pos() != lastpos()) {
1701                 // ... or enclosing inset if we are in the last inset position
1702                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1703                 posRight();
1704         }
1705 }
1706
1707
1708 CursorSlice LCursor::normalAnchor()
1709 {
1710         if (anchor_.size() < depth()) {
1711                 resetAnchor();
1712                 lyxerr << "unusual Anchor size" << endl;
1713         }
1714         //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1715         // use Anchor on the same level as Cursor
1716         CursorSlice normal = anchor_[current_];
1717 #if 0
1718         if (depth() < anchor_.size() && !(normal < xx())) {
1719                 // anchor is behind cursor -> move anchor behind the inset
1720                 ++normal.pos_;
1721         }
1722 #endif
1723         return normal;
1724 }
1725
1726
1727 /*
1728 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1729 {
1730         // mouse clicks are somewhat special
1731         // check
1732         switch (cmd.action) {
1733         case LFUN_MOUSE_PRESS:
1734         case LFUN_MOUSE_MOTION:
1735         case LFUN_MOUSE_RELEASE:
1736         case LFUN_MOUSE_DOUBLE: {
1737                 CursorSlice & pos = cursor_.back();
1738                 int x = 0;
1739                 int y = 0;
1740                 getPos(x, y);
1741                 if (x < cmd.x && pos() != 0) {
1742                         DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1743                         if (res.dispatched())
1744                                 return res;
1745                 }
1746                 if (x > cmd.x && pos() != lastpos()) {
1747                         DispatchResult const res = inset()->dispatch(cmd);
1748                         if (res.dispatched())
1749                                 return res;
1750                 }
1751         }
1752         default:
1753         break;
1754         }
1755 }
1756 */
1757
1758
1759 void LCursor::handleFont(string const & font)
1760 {
1761         string safe;
1762         if (selection()) {
1763                 macroModeClose();
1764                 safe = grabAndEraseSelection();
1765         }
1766
1767         if (lastpos() != 0) {
1768                 // something left in the cell
1769                 if (pos() == 0) {
1770                         // cursor in first position
1771                         popLeft();
1772                 } else if (pos() == lastpos()) {
1773                         // cursor in last position
1774                         popRight();
1775                 } else {
1776                         // cursor in between. split cell
1777                         MathArray::iterator bt = cell().begin();
1778                         MathAtom at = createMathInset(font);
1779                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1780                         cell().erase(bt, bt + pos());
1781                         popLeft();
1782                         plainInsert(at);
1783                 }
1784         } else {
1785                 // nothing left in the cell
1786                 pullArg();
1787                 plainErase();
1788         }
1789         insert(safe);
1790 }
1791
1792
1793 void LCursor::releaseMathCursor()
1794 {
1795         if (inMathed())
1796                 formula()->insetUnlock(bv());
1797 }
1798
1799
1800 bool LCursor::inMathed() const
1801 {
1802         return formula();
1803 }
1804
1805
1806 InsetBase * LCursor::nextInset()
1807 {
1808         if (pos() == lastpos())
1809                 return 0;
1810         if (inMathed()) 
1811                 return nextAtom().nucleus();
1812         Paragraph & par = paragraph();
1813         return par.isInset(pos()) ? par.getInset(pos()) : 0;
1814 }
1815
1816
1817 InsetBase * LCursor::prevInset()
1818 {
1819         if (pos() == 0)
1820                 return 0;
1821         if (inMathed()) 
1822                 return prevAtom().nucleus();
1823         Paragraph & par = paragraph();
1824         return par.isInset(pos() - 1) ? par.getInset(pos() - 1) : 0;
1825 }
1826
1827
1828 void LCursor::message(string const & msg) const
1829 {
1830         bv().owner()->getLyXFunc().setMessage(msg);
1831 }
1832
1833
1834 void LCursor::errorMessage(string const & msg) const
1835 {
1836         bv().owner()->getLyXFunc().setErrorMessage(msg);
1837 }