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