]> git.lyx.org Git - lyx.git/blob - src/cursor.C
move FontIterator to own files
[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 positionable(CursorBase const & cursor, CursorBase const & anchor)
919 {
920         // avoid deeper nested insets when selecting
921         if (cursor.size() > anchor.size())
922                 return false;
923
924         // anchor might be deeper, should have same path then
925         for (size_t i = 0; i < cursor.size(); ++i)
926                 if (cursor[i].inset() != anchor[i].inset())
927                         return false;
928
929         // position should be ok.
930         return true;
931 }
932
933
934 void LCursor::setScreenPos(int x, int y)
935 {
936         bool res = bruteFind(x, y, formula()->xlow(), formula()->xhigh(),
937                 formula()->ylow(), formula()->yhigh());
938         if (!res) {
939                 // this can happen on creation of "math-display"
940                 idx() = 0;
941                 pos() = 0;
942         }
943         clearTargetX();
944 }
945
946
947
948 void LCursor::plainErase()
949 {
950         cell().erase(pos());
951 }
952
953
954 void LCursor::markInsert()
955 {
956         cell().insert(pos(), MathAtom(new MathCharInset(0)));
957 }
958
959
960 void LCursor::markErase()
961 {
962         cell().erase(pos());
963 }
964
965
966 void LCursor::plainInsert(MathAtom const & t)
967 {
968         cell().insert(pos(), t);
969         ++pos();
970 }
971
972
973 void LCursor::insert(string const & str)
974 {
975         lyxerr << "LCursor::insert str '" << str << "'" << endl;
976         selClearOrDel();
977 #if 0
978         for (string::const_iterator it = str.begin(); it != str.end(); ++it)
979                 plainInsert(MathAtom(new MathCharInset(*it)));
980 #else
981         MathArray ar;
982         asArray(str, ar);
983         insert(ar);
984 #endif
985 }
986
987
988 void LCursor::insert(char c)
989 {
990         //lyxerr << "LCursor::insert char '" << c << "'" << endl;
991         selClearOrDel();
992         plainInsert(MathAtom(new MathCharInset(c)));
993 }
994
995
996 void LCursor::insert(MathAtom const & t)
997 {
998         //lyxerr << "LCursor::insert MathAtom: " << endl;
999         macroModeClose();
1000         selClearOrDel();
1001         plainInsert(t);
1002 }
1003
1004
1005 void LCursor::insert(InsetBase * inset)
1006 {
1007         if (inMathed())
1008                 insert(MathAtom(inset));
1009         else
1010                 text()->insertInset(*this, inset);
1011 }
1012
1013
1014 void LCursor::niceInsert(string const & t)
1015 {
1016         MathArray ar;
1017         asArray(t, ar);
1018         if (ar.size() == 1)
1019                 niceInsert(ar[0]);
1020         else
1021                 insert(ar);
1022 }
1023
1024
1025 void LCursor::niceInsert(MathAtom const & t)
1026 {
1027         macroModeClose();
1028         string safe = grabAndEraseSelection();
1029         plainInsert(t);
1030         // enter the new inset and move the contents of the selection if possible
1031         if (t->isActive()) {
1032                 posLeft();
1033                 // be careful here: don't use 'pushLeft(t)' as this we need to
1034                 // push the clone, not the original
1035                 pushLeft(nextAtom().nucleus());
1036                 paste(safe);
1037         }
1038 }
1039
1040
1041 void LCursor::insert(MathArray const & ar)
1042 {
1043         macroModeClose();
1044         if (selection())
1045                 eraseSelection();
1046         cell().insert(pos(), ar);
1047         pos() += ar.size();
1048 }
1049
1050
1051 bool LCursor::backspace()
1052 {
1053         autocorrect() = false;
1054
1055         if (selection()) {
1056                 selDel();
1057                 return true;
1058         }
1059
1060         if (pos() == 0) {
1061                 if (inset()->nargs() == 1 && depth() == 1 && lastpos() == 0)
1062                         return false;
1063                 pullArg();
1064                 return true;
1065         }
1066
1067         if (inMacroMode()) {
1068                 MathUnknownInset * p = activeMacro();
1069                 if (p->name().size() > 1) {
1070                         p->setName(p->name().substr(0, p->name().size() - 1));
1071                         return true;
1072                 }
1073         }
1074
1075         if (pos() != 0 && prevAtom()->nargs() > 0) {
1076                 // let's require two backspaces for 'big stuff' and
1077                 // highlight on the first
1078                 selection() = true;
1079                 --pos();
1080         } else {
1081                 --pos();
1082                 plainErase();
1083         }
1084         return true;
1085 }
1086
1087
1088 bool LCursor::erase()
1089 {
1090         autocorrect() = false;
1091         if (inMacroMode())
1092                 return true;
1093
1094         if (selection()) {
1095                 selDel();
1096                 return true;
1097         }
1098
1099         // delete empty cells if possible
1100         if (pos() == lastpos() && inset()->idxDelete(idx()))
1101                 return true;
1102
1103         // special behaviour when in last position of cell
1104         if (pos() == lastpos()) {
1105                 bool one_cell = inset()->nargs() == 1;
1106                 if (one_cell && depth() == 1 && lastpos() == 0)
1107                         return false;
1108                 // remove markup
1109                 if (one_cell)
1110                         pullArg();
1111                 else
1112                         inset()->idxGlue(idx());
1113                 return true;
1114         }
1115
1116         if (pos() != lastpos() && inset()->nargs() > 0) {
1117                 selection() = true;
1118                 ++pos();
1119         } else {
1120                 plainErase();
1121         }
1122
1123         return true;
1124 }
1125
1126
1127 bool LCursor::up()
1128 {
1129         macroModeClose();
1130         CursorBase save = cursor_;
1131         if (goUpDown(true))
1132                 return true;
1133         cursor_ = save;
1134         autocorrect() = false;
1135         return selection();
1136 }
1137
1138
1139 bool LCursor::down()
1140 {
1141         macroModeClose();
1142         CursorBase save = cursor_;
1143         if (goUpDown(false))
1144                 return true;
1145         cursor_ = save;
1146         autocorrect() = false;
1147         return selection();
1148 }
1149
1150
1151 void LCursor::macroModeClose()
1152 {
1153         if (!inMacroMode())
1154                 return;
1155         MathUnknownInset * p = activeMacro();
1156         p->finalize();
1157         string s = p->name();
1158         --pos();
1159         cell().erase(pos());
1160
1161         // do nothing if the macro name is empty
1162         if (s == "\\")
1163                 return;
1164
1165         string const name = s.substr(1);
1166
1167         // prevent entering of recursive macros
1168         InsetBase const * macro = innerInsetOfType(InsetBase::MATHMACRO_CODE);
1169         if (macro && macro->getInsetName() == name)
1170                 lyxerr << "can't enter recursive macro" << endl;
1171
1172         niceInsert(createMathInset(name));
1173 }
1174
1175
1176 string LCursor::macroName()
1177 {
1178         return inMacroMode() ? activeMacro()->name() : string();
1179 }
1180
1181
1182 void LCursor::handleNest(MathAtom const & a, int c)
1183 {
1184         //lyxerr << "LCursor::handleNest: " << c << endl;
1185         MathAtom t = a;
1186         asArray(grabAndEraseSelection(), t.nucleus()->cell(c));
1187         insert(t);
1188         posLeft();
1189         pushLeft(nextAtom().nucleus());
1190 }
1191
1192
1193 int LCursor::targetX() const
1194 {
1195         if (x_target() != -1)
1196                 return x_target();
1197         int x = 0;
1198         int y = 0;
1199         getPos(x, y);
1200         return x;
1201 }
1202
1203
1204 MathHullInset * LCursor::formula() const
1205 {
1206         for (int i = cursor_.size() - 1; i >= 1; --i) {
1207                 MathInset * inset = cursor_[i].inset()->asMathInset();
1208                 if (inset && inset->asHullInset())
1209                         return static_cast<MathHullInset *>(inset);
1210         }
1211         return 0;
1212 }
1213
1214
1215 void LCursor::adjust(pos_type from, int diff)
1216 {
1217         if (pos() > from)
1218                 pos() += diff;
1219         if (anchor().pos_ > from)
1220                 anchor().pos_ += diff;
1221         // just to be on the safe side
1222         // theoretically unecessary
1223         normalize();
1224 }
1225
1226
1227 bool LCursor::inMacroMode() const
1228 {
1229         if (!pos() != 0)
1230                 return false;
1231         MathUnknownInset const * p = prevAtom()->asUnknownInset();
1232         return p && !p->final();
1233 }
1234
1235
1236 MathUnknownInset * LCursor::activeMacro()
1237 {
1238         return inMacroMode() ? prevAtom().nucleus()->asUnknownInset() : 0;
1239 }
1240
1241
1242 bool LCursor::inMacroArgMode() const
1243 {
1244         return pos() > 0 && prevAtom()->getChar() == '#';
1245 }
1246
1247
1248 MathGridInset * LCursor::enclosingGrid(idx_type & idx) const
1249 {
1250         for (MathInset::difference_type i = depth() - 1; i >= 0; --i) {
1251                 MathInset * m = cursor_[i].inset()->asMathInset();
1252                 if (!m)
1253                         return 0;
1254                 MathGridInset * p = m->asGridInset();
1255                 if (p) {
1256                         idx = cursor_[i].idx_;
1257                         return p;
1258                 }
1259         }
1260         return 0;
1261 }
1262
1263
1264 void LCursor::pullArg()
1265 {
1266 #warning Look here
1267         MathArray ar = cell();
1268         if (popLeft() && inMathed()) {
1269                 plainErase();
1270                 cell().insert(pos(), ar);
1271                 resetAnchor();
1272         } else {
1273                 //formula()->mutateToText();
1274         }
1275 }
1276
1277
1278 void LCursor::touch()
1279 {
1280 #warning look here
1281 #if 0
1282         CursorBase::const_iterator it = cursor_.begin();
1283         CursorBase::const_iterator et = cursor_.end();
1284         for ( ; it != et; ++it)
1285                 it->cell().touch();
1286 #endif
1287 }
1288
1289
1290 void LCursor::normalize()
1291 {
1292         if (idx() >= nargs()) {
1293                 lyxerr << "this should not really happen - 1: "
1294                        << idx() << ' ' << nargs()
1295                        << " in: " << inset() << endl;
1296         }
1297         idx() = min(idx(), lastidx());
1298
1299         if (pos() > lastpos()) {
1300                 lyxerr << "this should not really happen - 2: "
1301                         << pos() << ' ' << lastpos() <<  " in idx: " << idx()
1302                        << " in atom: '";
1303                 WriteStream wi(lyxerr, false, true);
1304                 inset()->asMathInset()->write(wi);
1305                 lyxerr << endl;
1306         }
1307         pos() = min(pos(), lastpos());
1308 }
1309
1310
1311 char LCursor::valign()
1312 {
1313         idx_type idx;
1314         MathGridInset * p = enclosingGrid(idx);
1315         return p ? p->valign() : '\0';
1316 }
1317
1318
1319 char LCursor::halign()
1320 {
1321         idx_type idx;
1322         MathGridInset * p = enclosingGrid(idx);
1323         return p ? p->halign(idx % p->ncols()) : '\0';
1324 }
1325
1326
1327 bool LCursor::goUpDown(bool up)
1328 {
1329         // Be warned: The 'logic' implemented in this function is highly
1330         // fragile. A distance of one pixel or a '<' vs '<=' _really
1331         // matters. So fiddle around with it only if you think you know
1332         // what you are doing!
1333   int xo = 0;
1334         int yo = 0;
1335         getPos(xo, yo);
1336
1337         // check if we had something else in mind, if not, this is the future goal
1338         if (x_target() == -1)
1339                 x_target() = xo;
1340         else
1341                 xo = x_target();
1342
1343         // try neigbouring script insets
1344         if (!selection()) {
1345                 // try left
1346                 if (pos() != 0) {
1347                         MathScriptInset const * p = prevAtom()->asScriptInset();
1348                         if (p && p->has(up)) {
1349                                 --pos();
1350                                 push(inset());
1351                                 idx() = up; // the superscript has index 1
1352                                 pos() = lastpos();
1353                                 //lyxerr << "updown: handled by scriptinset to the left" << endl;
1354                                 return true;
1355                         }
1356                 }
1357
1358                 // try right
1359                 if (pos() != lastpos()) {
1360                         MathScriptInset const * p = nextAtom()->asScriptInset();
1361                         if (p && p->has(up)) {
1362                                 push(inset());
1363                                 idx() = up;
1364                                 pos() = 0;
1365                                 //lyxerr << "updown: handled by scriptinset to the right" << endl;
1366                                 return true;
1367                         }
1368                 }
1369         }
1370
1371         // try current cell for e.g. text insets
1372         if (inset()->idxUpDown2(*this, up))
1373                 return true;
1374
1375         //xarray().boundingBox(xlow, xhigh, ylow, yhigh);
1376         //if (up)
1377         //      yhigh = yo - 4;
1378         //else
1379         //      ylow = yo + 4;
1380         //if (bruteFind(xo, yo, xlow, xhigh, ylow, yhigh)) {
1381         //      lyxerr << "updown: handled by brute find in the same cell" << endl;
1382         //      return true;
1383         //}
1384
1385         // try to find an inset that knows better then we
1386         while (1) {
1387                 //lyxerr << "updown: We are in " << inset() << " idx: " << idx() << endl;
1388                 // ask inset first
1389                 if (inset()->idxUpDown(*this, up)) {
1390                         // try to find best position within this inset
1391                         if (!selection())
1392                                 bruteFind2(xo, yo);
1393                         return true;
1394                 }
1395
1396                 // no such inset found, just take something "above"
1397                 //lyxerr << "updown: handled by strange case" << endl;
1398                 if (!popLeft()) {
1399                         return
1400                                 bruteFind(xo, yo,
1401                                         formula()->xlow(),
1402                                         formula()->xhigh(),
1403                                         up ? formula()->ylow() : yo + 4,
1404                                         up ? yo - 4 : formula()->yhigh()
1405                                 );
1406                 }
1407
1408                 // any improvement so far?
1409                 int xnew, ynew;
1410                 getPos(xnew, ynew);
1411                 if (up ? ynew < yo : ynew > yo)
1412                         return true;
1413         }
1414 }
1415
1416
1417 bool LCursor::bruteFind(int x, int y, int xlow, int xhigh, int ylow, int yhigh)
1418 {
1419         CursorBase best_cursor;
1420         double best_dist = 1e10;
1421
1422         CursorBase it = ibegin(formula());
1423         CursorBase et = iend(formula());
1424         while (1) {
1425                 // avoid invalid nesting when selecting
1426                 if (!selection() || positionable(it, anchor_)) {
1427                         int xo, yo;
1428                         CursorSlice & cur = it.back();
1429                         cur.inset()->getCursorPos(cur, xo, yo);
1430                         if (xlow <= xo && xo <= xhigh && ylow <= yo && yo <= yhigh) {
1431                                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1432                                 //lyxerr << "x: " << x << " y: " << y << " d: " << endl;
1433                                 // '<=' in order to take the last possible position
1434                                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1435                                 if (d <= best_dist) {
1436                                         best_dist   = d;
1437                                         best_cursor = it;
1438                                 }
1439                         }
1440                 }
1441
1442                 if (it == et)
1443                         break;
1444                 increment(it);
1445         }
1446
1447         if (best_dist < 1e10)
1448                 cursor_ = best_cursor;
1449         return best_dist < 1e10;
1450 }
1451
1452
1453 void LCursor::bruteFind2(int x, int y)
1454 {
1455         double best_dist = 1e10;
1456
1457         CursorBase it = cursor_;
1458         it.back().pos() = 0;
1459         CursorBase et = cursor_;
1460         et.back().pos() = et.back().asMathInset()->cell(et.back().idx_).size();
1461         for (int i = 0; ; ++i) {
1462                 int xo, yo;
1463                 CursorSlice & cur = it.back();
1464                 cur.inset()->getCursorPos(cur, xo, yo);
1465                 double d = (x - xo) * (x - xo) + (y - yo) * (y - yo);
1466                 // '<=' in order to take the last possible position
1467                 // this is important for clicking behind \sum in e.g. '\sum_i a'
1468                 lyxerr << "i: " << i << " d: " << d << " best: " << best_dist << endl;
1469                 if (d <= best_dist) {
1470                         best_dist = d;
1471                         cursor_ = it;
1472                 }
1473                 if (it == et)
1474                         break;
1475                 increment(it);
1476         }
1477 }
1478
1479
1480 void LCursor::lockToggle()
1481 {
1482         if (pos() != lastpos()) {
1483                 // toggle previous inset ...
1484                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1485         } else if (popLeft() && pos() != lastpos()) {
1486                 // ... or enclosing inset if we are in the last inset position
1487                 nextAtom().nucleus()->lock(!nextAtom()->lock());
1488                 ++pos();
1489         }
1490 }
1491
1492
1493 CursorSlice LCursor::normalAnchor()
1494 {
1495         if (anchor_.size() < depth()) {
1496                 resetAnchor();
1497                 lyxerr << "unusual Anchor size" << endl;
1498         }
1499         //lyx::BOOST_ASSERT(Anchor_.size() >= cursor.depth());
1500         // use Anchor on the same level as Cursor
1501         CursorSlice normal = anchor_[current_];
1502 #if 0
1503         if (depth() < anchor_.size() && !(normal < xx())) {
1504                 // anchor is behind cursor -> move anchor behind the inset
1505                 ++normal.pos_;
1506         }
1507 #endif
1508         return normal;
1509 }
1510
1511
1512 /*
1513 DispatchResult dispatch(LCursor & cur, FuncRequest const & cmd)
1514 {
1515         // mouse clicks are somewhat special
1516         // check
1517         switch (cmd.action) {
1518         case LFUN_MOUSE_PRESS:
1519         case LFUN_MOUSE_MOTION:
1520         case LFUN_MOUSE_RELEASE:
1521         case LFUN_MOUSE_DOUBLE: {
1522                 CursorSlice & pos = cursor_.back();
1523                 int x = 0;
1524                 int y = 0;
1525                 getPos(x, y);
1526                 if (x < cmd.x && pos() != 0) {
1527                         DispatchResult const res = prevAtom().nucleus()->dispatch(cmd);
1528                         if (res.dispatched())
1529                                 return res;
1530                 }
1531                 if (x > cmd.x && pos() != lastpos()) {
1532                         DispatchResult const res = inset()->dispatch(cmd);
1533                         if (res.dispatched())
1534                                 return res;
1535                 }
1536         }
1537         default:
1538         break;
1539         }
1540 }
1541 */
1542
1543
1544 void LCursor::handleFont(string const & font)
1545 {
1546         lyxerr << "LCursor::handleFont: " << font << endl;
1547         string safe;
1548         if (selection()) {
1549                 macroModeClose();
1550                 safe = grabAndEraseSelection();
1551         }
1552
1553         if (lastpos() != 0) {
1554                 // something left in the cell
1555                 if (pos() == 0) {
1556                         // cursor in first position
1557                         popLeft();
1558                 } else if (pos() == lastpos()) {
1559                         // cursor in last position
1560                         popRight();
1561                 } else {
1562                         // cursor in between. split cell
1563                         MathArray::iterator bt = cell().begin();
1564                         MathAtom at = createMathInset(font);
1565                         at.nucleus()->cell(0) = MathArray(bt, bt + pos());
1566                         cell().erase(bt, bt + pos());
1567                         popLeft();
1568                         plainInsert(at);
1569                 }
1570         } else {
1571                 // nothing left in the cell
1572                 pullArg();
1573                 plainErase();
1574         }
1575         insert(safe);
1576 }
1577
1578
1579 bool LCursor::inMathed() const
1580 {
1581         return current_ && inset()->inMathed();
1582 }
1583
1584
1585 bool LCursor::inTexted() const
1586 {
1587         return !inMathed();
1588 }
1589
1590
1591 InsetBase * LCursor::nextInset()
1592 {
1593         if (pos() == lastpos())
1594                 return 0;
1595         if (inMathed()) 
1596                 return nextAtom().nucleus();
1597         return paragraph().isInset(pos()) ? paragraph().getInset(pos()) : 0;
1598 }
1599
1600
1601 InsetBase * LCursor::prevInset()
1602 {
1603         if (pos() == 0)
1604                 return 0;
1605         if (inMathed()) 
1606                 return prevAtom().nucleus();
1607         return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1608 }
1609
1610
1611 InsetBase const * LCursor::prevInset() const
1612 {
1613         if (pos() == 0)
1614                 return 0;
1615         if (inMathed()) 
1616                 return prevAtom().nucleus();
1617         return paragraph().isInset(pos() - 1) ? paragraph().getInset(pos() - 1) : 0;
1618 }
1619
1620
1621 void LCursor::message(string const & msg) const
1622 {
1623         bv().owner()->getLyXFunc().setMessage(msg);
1624 }
1625
1626
1627 void LCursor::errorMessage(string const & msg) const
1628 {
1629         bv().owner()->getLyXFunc().setErrorMessage(msg);
1630 }
1631
1632
1633 string LCursor::selectionAsString(bool label) const
1634 {
1635         if (!selection())
1636                 return string();
1637
1638         if (inTexted()) {
1639                 Buffer const & buffer = *bv().buffer();
1640
1641                 // should be const ...
1642                 ParagraphList::iterator startpit = text()->getPar(selBegin());
1643                 ParagraphList::iterator endpit = text()->getPar(selEnd());
1644                 size_t const startpos = selBegin().pos();
1645                 size_t const endpos = selEnd().pos();
1646
1647                 if (startpit == endpit)
1648                         return startpit->asString(buffer, startpos, endpos, label);
1649
1650                 // First paragraph in selection
1651                 string result =
1652                         startpit->asString(buffer, startpos, startpit->size(), label) + "\n\n";
1653
1654                 // The paragraphs in between (if any)
1655                 ParagraphList::iterator pit = startpit;
1656                 for (++pit; pit != endpit; ++pit)
1657                         result += pit->asString(buffer, 0, pit->size(), label) + "\n\n";
1658
1659                 // Last paragraph in selection
1660                 result += endpit->asString(buffer, 0, endpos, label);
1661
1662                 return result;
1663         }
1664
1665 #warning an mathed?
1666         return string();
1667 }
1668
1669
1670 string LCursor::currentState()
1671 {
1672         if (inMathed()) {
1673                 std::ostringstream os;
1674                 info(os);
1675                 return os.str();
1676         }
1677         return text() ? text()->currentState(*this) : string();
1678 }
1679
1680
1681 // only used by the spellchecker
1682 void LCursor::replaceWord(string const & replacestring)
1683 {
1684         LyXText * t = text();
1685         BOOST_ASSERT(t);
1686
1687         t->replaceSelectionWithString(*this, replacestring);
1688         t->setSelectionRange(*this, replacestring.length());
1689
1690         // Go back so that replacement string is also spellchecked
1691         for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
1692                 t->cursorLeft(*this);
1693 }
1694
1695
1696 void LCursor::update()
1697 {
1698         bv().update();
1699 }
1700
1701
1702 string LCursor::getPossibleLabel()
1703 {
1704         return inMathed() ? "eq:" : text()->getPossibleLabel(*this);
1705 }
1706
1707
1708 void LCursor::notdispatched()
1709 {
1710         disp_.dispatched(false);
1711 }
1712
1713
1714 void LCursor::dispatched(dispatch_result_t res)
1715 {
1716         disp_.val(res);
1717 }
1718
1719
1720 void LCursor::noupdate()
1721 {
1722         disp_.update(false);
1723 }