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