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