]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
* src/mathed/InsetMathHull.cpp:
[lyx.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "InsetMathRef.h"
24 #include "InsetMathScript.h"
25 #include "InsetMathSpace.h"
26 #include "InsetMathSymbol.h"
27 #include "InsetMathUnknown.h"
28 #include "MathCompletionList.h"
29 #include "MathData.h"
30 #include "MathFactory.h"
31 #include "MathMacro.h"
32 #include "MathMacroArgument.h"
33 #include "MathParser.h"
34 #include "MathStream.h"
35 #include "MathSupport.h"
36
37 #include "Bidi.h"
38 #include "Buffer.h"
39 #include "BufferView.h"
40 #include "CoordCache.h"
41 #include "Cursor.h"
42 #include "CutAndPaste.h"
43 #include "DispatchResult.h"
44 #include "FuncRequest.h"
45 #include "FuncStatus.h"
46 #include "LyXFunc.h"
47 #include "LyXRC.h"
48 #include "OutputParams.h"
49 #include "Text.h"
50
51 #include "frontends/Clipboard.h"
52 #include "frontends/Painter.h"
53 #include "frontends/Selection.h"
54
55 #include "support/lassert.h"
56 #include "support/debug.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
59 #include "support/textutils.h"
60 #include "support/docstream.h"
61
62 #include <algorithm>
63 #include <sstream>
64
65 using namespace std;
66 using namespace lyx::support;
67
68 namespace lyx {
69
70 using cap::copySelection;
71 using cap::grabAndEraseSelection;
72 using cap::cutSelection;
73 using cap::replaceSelection;
74 using cap::selClearOrDel;
75
76
77 InsetMathNest::InsetMathNest(idx_type nargs)
78         : cells_(nargs), lock_(false), mouse_hover_(false)
79 {}
80
81
82 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
83         : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
84           mouse_hover_(false)
85 {}
86
87
88 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
89 {
90         cells_ = inset.cells_;
91         lock_ = inset.lock_;
92         mouse_hover_ = false;
93         InsetMath::operator=(inset);
94         return *this;
95 }
96
97
98 InsetMath::idx_type InsetMathNest::nargs() const
99 {
100         return cells_.size();
101 }
102
103
104 void InsetMathNest::cursorPos(BufferView const & bv,
105                 CursorSlice const & sl, bool /*boundary*/,
106                 int & x, int & y) const
107 {
108 // FIXME: This is a hack. Ideally, the coord cache should not store
109 // absolute positions, but relative ones. This would mean to call
110 // setXY() not in MathData::draw(), but in the parent insets' draw()
111 // with the correctly adjusted x,y values. But this means that we'd have
112 // to touch all (math)inset's draw() methods. Right now, we'll store
113 // absolute value, and make them here relative, only to make them
114 // absolute again when actually drawing the cursor. What a mess.
115         LASSERT(&sl.inset() == this, /**/);
116         MathData const & ar = sl.cell();
117         CoordCache const & coord_cache = bv.coordCache();
118         if (!coord_cache.getArrays().has(&ar)) {
119                 // this can (semi-)legally happen if we just created this cell
120                 // and it never has been drawn before. So don't ASSERT.
121                 //lyxerr << "no cached data for array " << &ar << endl;
122                 x = 0;
123                 y = 0;
124                 return;
125         }
126         Point const pt = coord_cache.getArrays().xy(&ar);
127         if (!coord_cache.getInsets().has(this)) {
128                 // same as above
129                 //lyxerr << "no cached data for inset " << this << endl;
130                 x = 0;
131                 y = 0;
132                 return;
133         }
134         Point const pt2 = coord_cache.getInsets().xy(this);
135         //lyxerr << "retrieving position cache for MathData "
136         //      << pt.x_ << ' ' << pt.y_ << endl;
137         x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
138         y = pt.y_ - pt2.y_;
139 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
140 //              << " asc: " << ascent() << "  des: " << descent()
141 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
142         // move cursor visually into empty cells ("blue rectangles");
143         if (ar.empty())
144                 x += 2;
145 }
146
147
148 void InsetMathNest::metrics(MetricsInfo const & mi) const
149 {
150         MetricsInfo m = mi;
151         for (idx_type i = 0, n = nargs(); i != n; ++i) {
152                 Dimension dim;
153                 cell(i).metrics(m, dim);
154         }
155 }
156
157
158 bool InsetMathNest::idxNext(Cursor & cur) const
159 {
160         LASSERT(&cur.inset() == this, /**/);
161         if (cur.idx() == cur.lastidx())
162                 return false;
163         ++cur.idx();
164         cur.pos() = 0;
165         return true;
166 }
167
168
169 bool InsetMathNest::idxForward(Cursor & cur) const
170 {
171         return idxNext(cur);
172 }
173
174
175 bool InsetMathNest::idxPrev(Cursor & cur) const
176 {
177         LASSERT(&cur.inset() == this, /**/);
178         if (cur.idx() == 0)
179                 return false;
180         --cur.idx();
181         cur.pos() = cur.lastpos();
182         return true;
183 }
184
185
186 bool InsetMathNest::idxBackward(Cursor & cur) const
187 {
188         return idxPrev(cur);
189 }
190
191
192 bool InsetMathNest::idxFirst(Cursor & cur) const
193 {
194         LASSERT(&cur.inset() == this, /**/);
195         if (nargs() == 0)
196                 return false;
197         cur.idx() = 0;
198         cur.pos() = 0;
199         return true;
200 }
201
202
203 bool InsetMathNest::idxLast(Cursor & cur) const
204 {
205         LASSERT(&cur.inset() == this, /**/);
206         if (nargs() == 0)
207                 return false;
208         cur.idx() = cur.lastidx();
209         cur.pos() = cur.lastpos();
210         return true;
211 }
212
213
214 void InsetMathNest::dump() const
215 {
216         odocstringstream oss;
217         WriteStream os(oss);
218         os << "---------------------------------------------\n";
219         write(os);
220         os << "\n";
221         for (idx_type i = 0, n = nargs(); i != n; ++i)
222                 os << cell(i) << "\n";
223         os << "---------------------------------------------\n";
224         lyxerr << to_utf8(oss.str());
225 }
226
227
228 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
229 {
230 #if 0
231         if (lock_)
232                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
233                                         Color_mathlockbg);
234 #endif
235         setPosCache(pi, x, y);
236 }
237
238
239 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
240 {
241         BufferView & bv = *pi.base.bv;
242         // this should use the x/y values given, not the cached values
243         Cursor & cur = bv.cursor();
244         if (!cur.selection())
245                 return;
246         if (&cur.inset() != this)
247                 return;
248
249         // FIXME: hack to get position cache warm
250         bool const original_drawing_state = pi.pain.isDrawingEnabled();
251         pi.pain.setDrawingEnabled(false);
252         draw(pi, x, y);
253         pi.pain.setDrawingEnabled(original_drawing_state);
254
255         CursorSlice s1 = cur.selBegin();
256         CursorSlice s2 = cur.selEnd();
257
258         //lyxerr << "InsetMathNest::drawing selection: "
259         //      << " s1: " << s1 << " s2: " << s2 << endl;
260         if (s1.idx() == s2.idx()) {
261                 MathData const & c = cell(s1.idx());
262                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
263                 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
264                 int y1 = g.pos.y_ - g.dim.ascent();
265                 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
266                 int y2 = g.pos.y_ + g.dim.descent();
267                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
268         //lyxerr << "InsetMathNest::drawing selection 3: "
269         //      << " x1: " << x1 << " x2: " << x2
270         //      << " y1: " << y1 << " y2: " << y2 << endl;
271         } else {
272                 for (idx_type i = 0; i < nargs(); ++i) {
273                         if (idxBetween(i, s1.idx(), s2.idx())) {
274                                 MathData const & c = cell(i);
275                                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
276                                 int x1 = g.pos.x_;
277                                 int y1 = g.pos.y_ - g.dim.ascent();
278                                 int x2 = g.pos.x_ + g.dim.width();
279                                 int y2 = g.pos.y_ + g.dim.descent();
280                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
281                         }
282                 }
283         }
284 }
285
286
287 void InsetMathNest::validate(LaTeXFeatures & features) const
288 {
289         for (idx_type i = 0; i < nargs(); ++i)
290                 cell(i).validate(features);
291 }
292
293
294 void InsetMathNest::replace(ReplaceData & rep)
295 {
296         for (idx_type i = 0; i < nargs(); ++i)
297                 cell(i).replace(rep);
298 }
299
300
301 bool InsetMathNest::contains(MathData const & ar) const
302 {
303         for (idx_type i = 0; i < nargs(); ++i)
304                 if (cell(i).contains(ar))
305                         return true;
306         return false;
307 }
308
309
310 bool InsetMathNest::lock() const
311 {
312         return lock_;
313 }
314
315
316 void InsetMathNest::lock(bool l)
317 {
318         lock_ = l;
319 }
320
321
322 bool InsetMathNest::isActive() const
323 {
324         return nargs() > 0;
325 }
326
327
328 MathData InsetMathNest::glue() const
329 {
330         MathData ar;
331         for (size_t i = 0; i < nargs(); ++i)
332                 ar.append(cell(i));
333         return ar;
334 }
335
336
337 void InsetMathNest::write(WriteStream & os) const
338 {
339         ModeSpecifier specifier(os, currentMode());
340         docstring const latex_name = name();
341         os << '\\' << latex_name;
342         for (size_t i = 0; i < nargs(); ++i)
343                 os << '{' << cell(i) << '}';
344         if (nargs() == 0)
345                 os.pendingSpace(true);
346         if (lock_ && !os.latex()) {
347                 os << "\\lyxlock";
348                 os.pendingSpace(true);
349         }
350 }
351
352
353 void InsetMathNest::normalize(NormalStream & os) const
354 {
355         os << '[' << name();
356         for (size_t i = 0; i < nargs(); ++i)
357                 os << ' ' << cell(i);
358         os << ']';
359 }
360
361
362 int InsetMathNest::latex(odocstream & os, OutputParams const & runparams) const
363 {
364         WriteStream wi(os, runparams.moving_arg, true, runparams.dryrun,
365                         runparams.encoding);
366         write(wi);
367         return wi.line();
368 }
369
370
371 bool InsetMathNest::setMouseHover(bool mouse_hover)
372 {
373         mouse_hover_ = mouse_hover;
374         return true;
375 }
376
377
378 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
379 {
380         // FIXME: look here
381 #if 0
382         MathData & ar = cur.cell();
383         // remove base-only "scripts"
384         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
385                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
386                 if (p && p->nargs() == 1) {
387                         MathData ar = p->nuc();
388                         erase(i);
389                         insert(i, ar);
390                         cur.adjust(i, ar.size() - 1);
391                 }
392         }
393
394         // glue adjacent font insets of the same kind
395         for (pos_type i = 0; i + 1 < size(); ++i) {
396                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
397                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
398                 if (p && q && p->name() == q->name()) {
399                         p->cell(0).append(q->cell(0));
400                         erase(i + 1);
401                         cur.adjust(i, -1);
402                 }
403         }
404 #endif
405         return false;
406 }
407
408
409 void InsetMathNest::handleFont
410         (Cursor & cur, docstring const & arg, char const * const font)
411 {
412         handleFont(cur, arg, from_ascii(font));
413 }
414
415
416 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
417         docstring const & font)
418 {
419         cur.recordUndoSelection();
420
421         // this whole function is a hack and won't work for incremental font
422         // changes...
423         if (cur.inset().asInsetMath()->name() == font)
424                 cur.handleFont(to_utf8(font));
425         else
426                 handleNest(cur, createInsetMath(font), arg);
427 }
428
429
430 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
431 {
432         handleNest(cur, nest, docstring());
433 }
434
435
436 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
437         docstring const & arg)
438 {
439         CursorSlice i1 = cur.selBegin();
440         CursorSlice i2 = cur.selEnd();
441         if (!i1.inset().asInsetMath())
442                 return;
443         if (i1.idx() == i2.idx()) {
444                 // the easy case where only one cell is selected
445                 cur.handleNest(nest);
446                 cur.insert(arg);
447                 return;
448         }
449         
450         // multiple selected cells in a simple non-grid inset
451         if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
452                 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
453                         // select cell
454                         cur.idx() = i;
455                         cur.pos() = 0;
456                         cur.resetAnchor();
457                         cur.pos() = cur.lastpos();
458                         cur.setSelection();
459                         
460                         // change font of cell
461                         cur.handleNest(nest);
462                         cur.insert(arg);
463                         
464                         // cur is in the font inset now. If the loop continues,
465                         // we need to get outside again for the next cell
466                         if (i + 1 <= i2.idx())
467                                 cur.pop_back();
468                 }
469                 return;
470         }
471         
472         // the complicated case with multiple selected cells in a grid
473         row_type r1, r2;
474         col_type c1, c2;
475         cap::region(i1, i2, r1, r2, c1, c2);
476         for (row_type row = r1; row <= r2; ++row) {
477                 for (col_type col = c1; col <= c2; ++col) {
478                         // select cell
479                         cur.idx() = i1.asInsetMath()->index(row, col);
480                         cur.pos() = 0;
481                         cur.resetAnchor();
482                         cur.pos() = cur.lastpos();
483                         cur.setSelection();
484                         
485                         // 
486                         cur.handleNest(nest);
487                         cur.insert(arg);
488                 
489                         // cur is in the font inset now. If the loop continues,
490                         // we need to get outside again for the next cell
491                         if (col + 1 <= c2 || row + 1 <= r2)
492                                 cur.pop_back();
493                 }
494         }
495 }
496
497
498 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
499 {
500         cur.recordUndoSelection();
501         Font font;
502         bool b;
503         font.fromString(to_utf8(arg), b);
504         if (font.fontInfo().color() != Color_inherit &&
505             font.fontInfo().color() != Color_ignore)
506                 handleNest(cur, MathAtom(new InsetMathColor(true, font.fontInfo().color())));
507         
508         // FIXME: support other font changes here as well?
509 }
510
511
512 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
513 {
514         //lyxerr << "InsetMathNest: request: " << cmd << endl;
515
516         switch (cmd.action) {
517
518         case LFUN_PASTE: {
519                 cur.recordUndoSelection();
520                 cur.message(_("Paste"));
521                 replaceSelection(cur);
522                 docstring topaste;
523                 if (cmd.argument().empty() && !theClipboard().isInternal())
524                         topaste = theClipboard().getAsText();
525                 else {
526                         size_t n = 0;
527                         idocstringstream is(cmd.argument());
528                         is >> n;
529                         topaste = cap::selection(n);
530                 }
531                 cur.niceInsert(topaste);
532                 cur.clearSelection(); // bug 393
533                 cur.finishUndo();
534                 break;
535         }
536
537         case LFUN_CUT:
538                 cur.recordUndo();
539                 cutSelection(cur, true, true);
540                 cur.message(_("Cut"));
541                 // Prevent stale position >= size crash
542                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
543                 cur.normalize();
544                 break;
545
546         case LFUN_COPY:
547                 copySelection(cur);
548                 cur.message(_("Copy"));
549                 break;
550
551         case LFUN_MOUSE_PRESS:
552                 lfunMousePress(cur, cmd);
553                 break;
554
555         case LFUN_MOUSE_MOTION:
556                 lfunMouseMotion(cur, cmd);
557                 break;
558
559         case LFUN_MOUSE_RELEASE:
560                 lfunMouseRelease(cur, cmd);
561                 break;
562
563         case LFUN_FINISHED_LEFT: // in math, left is backwards
564         case LFUN_FINISHED_BACKWARD:
565                 cur.bv().cursor() = cur;
566                 break;
567
568         case LFUN_FINISHED_RIGHT: // in math, right is forward
569         case LFUN_FINISHED_FORWARD:
570                 ++cur.pos();
571                 cur.bv().cursor() = cur;
572                 break;
573
574         case LFUN_CHAR_RIGHT:
575         case LFUN_CHAR_LEFT:
576         case LFUN_CHAR_BACKWARD:
577         case LFUN_CHAR_FORWARD:
578                 cur.updateFlags(Update::Decoration | Update::FitCursor);
579         case LFUN_CHAR_RIGHT_SELECT:
580         case LFUN_CHAR_LEFT_SELECT:
581         case LFUN_CHAR_BACKWARD_SELECT:
582         case LFUN_CHAR_FORWARD_SELECT: {
583                 // are we in a selection?
584                 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT 
585                                            || cmd.action == LFUN_CHAR_LEFT_SELECT
586                                            || cmd.action == LFUN_CHAR_BACKWARD_SELECT
587                                            || cmd.action == LFUN_CHAR_FORWARD_SELECT);
588                 // are we moving forward or backwards? 
589                 // If the command was RIGHT or LEFT, then whether we're moving forward
590                 // or backwards depends on the cursor movement mode (logical or visual):
591                 //  * in visual mode, since math is always LTR, right -> forward, 
592                 //    left -> backwards
593                 //  * in logical mode, the mapping is determined by the
594                 //    reverseDirectionNeeded() function
595                 
596                 bool forward;
597                 FuncCode finish_lfun;
598
599                 if (cmd.action == LFUN_CHAR_FORWARD 
600                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
601                         forward = true;
602                         finish_lfun = LFUN_FINISHED_FORWARD;
603                 }
604                 else if (cmd.action == LFUN_CHAR_BACKWARD
605                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
606                         forward = false;
607                         finish_lfun = LFUN_FINISHED_BACKWARD;
608                 }
609                 else {
610                         bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
611                                                   || cmd.action == LFUN_CHAR_RIGHT);
612                         if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
613                                 forward = right;
614                         else 
615                                 forward = !right;
616
617                         if (right)
618                                 finish_lfun = LFUN_FINISHED_RIGHT;
619                         else
620                                 finish_lfun = LFUN_FINISHED_LEFT;
621                 }
622                 // Now that we know exactly what we want to do, let's do it!
623                 cur.selHandle(select);
624                 cur.autocorrect() = false;
625                 cur.clearTargetX();
626                 cur.macroModeClose();
627                 // try moving forward or backwards as necessary...
628                 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
629                         // ... and if movement failed, then finish forward or backwards
630                         // as necessary
631                         cmd = FuncRequest(finish_lfun);
632                         cur.undispatched();
633                 }
634                 break;
635         }
636
637         case LFUN_DOWN:
638         case LFUN_UP:
639                 cur.updateFlags(Update::Decoration | Update::FitCursor);
640         case LFUN_DOWN_SELECT:
641         case LFUN_UP_SELECT: {
642                 // close active macro
643                 if (cur.inMacroMode()) {
644                         cur.macroModeClose();
645                         break;
646                 }
647                 
648                 // stop/start the selection
649                 bool select = cmd.action == LFUN_DOWN_SELECT ||
650                         cmd.action == LFUN_UP_SELECT;
651                 cur.selHandle(select);
652                 
653                 // go up/down
654                 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
655                 bool successful = cur.upDownInMath(up);
656                 if (successful)
657                         break;
658                 
659                 if (cur.fixIfBroken())
660                         // FIXME: Something bad happened. We pass the corrected Cursor
661                         // instead of letting things go worse.
662                         break;
663
664                 // We did not manage to move the cursor.
665                 cur.undispatched();
666                 break;
667         }
668
669         case LFUN_MOUSE_DOUBLE:
670         case LFUN_MOUSE_TRIPLE:
671         case LFUN_WORD_SELECT:
672                 cur.pos() = 0;
673                 cur.idx() = 0;
674                 cur.resetAnchor();
675                 cur.selection() = true;
676                 cur.pos() = cur.lastpos();
677                 cur.idx() = cur.lastidx();
678                 break;
679
680         case LFUN_PARAGRAPH_UP:
681         case LFUN_PARAGRAPH_DOWN:
682                 cur.updateFlags(Update::Decoration | Update::FitCursor);
683         case LFUN_PARAGRAPH_UP_SELECT:
684         case LFUN_PARAGRAPH_DOWN_SELECT:
685                 break;
686
687         case LFUN_LINE_BEGIN:
688         case LFUN_WORD_BACKWARD:
689         case LFUN_WORD_LEFT:
690                 cur.updateFlags(Update::Decoration | Update::FitCursor);
691         case LFUN_LINE_BEGIN_SELECT:
692         case LFUN_WORD_BACKWARD_SELECT:
693         case LFUN_WORD_LEFT_SELECT:
694                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
695                                 cmd.action == LFUN_WORD_LEFT_SELECT || 
696                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
697                 cur.macroModeClose();
698                 if (cur.pos() != 0) {
699                         cur.pos() = 0;
700                 } else if (cur.col() != 0) {
701                         cur.idx() -= cur.col();
702                         cur.pos() = 0;
703                 } else if (cur.idx() != 0) {
704                         cur.idx() = 0;
705                         cur.pos() = 0;
706                 } else {
707                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
708                         cur.undispatched();
709                 }
710                 break;
711
712         case LFUN_WORD_FORWARD:
713         case LFUN_WORD_RIGHT:
714         case LFUN_LINE_END:
715                 cur.updateFlags(Update::Decoration | Update::FitCursor);
716         case LFUN_WORD_FORWARD_SELECT:
717         case LFUN_WORD_RIGHT_SELECT:
718         case LFUN_LINE_END_SELECT:
719                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
720                                 cmd.action == LFUN_WORD_RIGHT_SELECT ||
721                                 cmd.action == LFUN_LINE_END_SELECT);
722                 cur.macroModeClose();
723                 cur.clearTargetX();
724                 if (cur.pos() != cur.lastpos()) {
725                         cur.pos() = cur.lastpos();
726                 } else if (ncols() && (cur.col() != cur.lastcol())) {
727                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
728                         cur.pos() = cur.lastpos();
729                 } else if (cur.idx() != cur.lastidx()) {
730                         cur.idx() = cur.lastidx();
731                         cur.pos() = cur.lastpos();
732                 } else {
733                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
734                         cur.undispatched();
735                 }
736                 break;
737
738         case LFUN_CELL_FORWARD:
739                 cur.updateFlags(Update::Decoration | Update::FitCursor);
740                 cur.inset().idxNext(cur);
741                 break;
742
743         case LFUN_CELL_BACKWARD:
744                 cur.updateFlags(Update::Decoration | Update::FitCursor);
745                 cur.inset().idxPrev(cur);
746                 break;
747
748         case LFUN_WORD_DELETE_BACKWARD:
749         case LFUN_CHAR_DELETE_BACKWARD:
750                 if (cur.pos() == 0)
751                         // May affect external cell:
752                         cur.recordUndoInset();
753                 else
754                         cur.recordUndoSelection();
755                 // if the inset can not be removed from within, delete it
756                 if (!cur.backspace()) {
757                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
758                         cur.innerText()->dispatch(cur, cmd);
759                 }
760                 break;
761
762         case LFUN_WORD_DELETE_FORWARD:
763         case LFUN_CHAR_DELETE_FORWARD:
764                 if (cur.pos() == cur.lastpos())
765                         // May affect external cell:
766                         cur.recordUndoInset();
767                 else
768                         cur.recordUndoSelection();
769                 // if the inset can not be removed from within, delete it
770                 if (!cur.erase()) {
771                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
772                         cur.innerText()->dispatch(cur, cmd);
773                 }
774                 break;
775
776         case LFUN_ESCAPE:
777                 if (cur.selection())
778                         cur.clearSelection();
779                 else  {
780                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
781                         cur.undispatched();
782                 }
783                 break;
784
785         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
786         // that is traversed by a single <CursorLeft>/<CursorRight>.
787         case LFUN_INSET_TOGGLE:
788                 cur.recordUndo();
789                 lock(!lock());
790                 cur.popForward();
791                 break;
792
793         case LFUN_SELF_INSERT:
794                 if (cmd.argument().size() != 1) {
795                         cur.recordUndoSelection();
796                         docstring const arg = cmd.argument();
797                         if (!interpretString(cur, arg))
798                                 cur.insert(arg);
799                         break;
800                 }
801                 // Don't record undo steps if we are in macro mode and
802                 // cmd.argument is the next character of the macro name.
803                 // Otherwise we'll get an invalid cursor if we undo after
804                 // the macro was finished and the macro is a known command,
805                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
806                 // the InsetMathUnknown with name "frac" by an empty
807                 // InsetMathFrac -> a pos value > 0 is invalid.
808                 // A side effect is that an undo before the macro is finished
809                 // undoes the complete macro, not only the last character.
810                 if (!cur.inMacroMode())
811                         cur.recordUndoSelection();
812
813                 // spacial handling of space. If we insert an inset
814                 // via macro mode, we want to put the cursor inside it
815                 // if relevant. Think typing "\frac<space>".
816                 if (cmd.argument()[0] == ' '
817                     && cur.inMacroMode() && cur.macroName() != "\\"
818                     && cur.macroModeClose()) {
819                         MathAtom const atom = cur.prevAtom();
820                         if (atom->asNestInset() && atom->isActive()) {
821                                 cur.posBackward();
822                                 cur.pushBackward(*cur.nextInset());
823                         }
824                 } else if (!interpretChar(cur, cmd.argument()[0])) {
825                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
826                         cur.undispatched();
827                 }
828                 break;
829
830         //case LFUN_SERVER_GET_XY:
831         //      sprintf(dispatch_buffer, "%d %d",);
832         //      break;
833
834         case LFUN_SERVER_SET_XY: {
835                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
836                 int x = 0;
837                 int y = 0;
838                 istringstream is(to_utf8(cmd.argument()));
839                 is >> x >> y;
840                 cur.setScreenPos(x, y);
841                 break;
842         }
843
844         // Special casing for superscript in case of LyX handling
845         // dead-keys:
846         case LFUN_ACCENT_CIRCUMFLEX:
847                 if (cmd.argument().empty()) {
848                         // do superscript if LyX handles
849                         // deadkeys
850                         cur.recordUndoSelection();
851                         script(cur, true, grabAndEraseSelection(cur));
852                 }
853                 break;
854
855         case LFUN_ACCENT_UMLAUT:
856         case LFUN_ACCENT_ACUTE:
857         case LFUN_ACCENT_GRAVE:
858         case LFUN_ACCENT_BREVE:
859         case LFUN_ACCENT_DOT:
860         case LFUN_ACCENT_MACRON:
861         case LFUN_ACCENT_CARON:
862         case LFUN_ACCENT_TILDE:
863         case LFUN_ACCENT_CEDILLA:
864         case LFUN_ACCENT_CIRCLE:
865         case LFUN_ACCENT_UNDERDOT:
866         case LFUN_ACCENT_TIE:
867         case LFUN_ACCENT_OGONEK:
868         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
869                 break;
870
871         //  Math fonts
872         case LFUN_TEXTSTYLE_APPLY:
873         case LFUN_TEXTSTYLE_UPDATE:
874                 handleFont2(cur, cmd.argument());
875                 break;
876
877         case LFUN_FONT_BOLD:
878                 if (currentMode() == TEXT_MODE)
879                         handleFont(cur, cmd.argument(), "textbf");
880                 else
881                         handleFont(cur, cmd.argument(), "boldsymbol");
882                 break;
883         case LFUN_FONT_SANS:
884                 if (currentMode() == TEXT_MODE)
885                         handleFont(cur, cmd.argument(), "textsf");
886                 else
887                         handleFont(cur, cmd.argument(), "mathsf");
888                 break;
889         case LFUN_FONT_EMPH:
890                 if (currentMode() == TEXT_MODE)
891                         handleFont(cur, cmd.argument(), "emph");
892                 else
893                         handleFont(cur, cmd.argument(), "mathcal");
894                 break;
895         case LFUN_FONT_ROMAN:
896                 if (currentMode() == TEXT_MODE)
897                         handleFont(cur, cmd.argument(), "textrm");
898                 else
899                         handleFont(cur, cmd.argument(), "mathrm");
900                 break;
901         case LFUN_FONT_TYPEWRITER:
902                 if (currentMode() == TEXT_MODE)
903                         handleFont(cur, cmd.argument(), "texttt");
904                 else
905                         handleFont(cur, cmd.argument(), "mathtt");
906                 break;
907         case LFUN_FONT_FRAK:
908                 handleFont(cur, cmd.argument(), "mathfrak");
909                 break;
910         case LFUN_FONT_ITAL:
911                 if (currentMode() == TEXT_MODE)
912                         handleFont(cur, cmd.argument(), "textit");
913                 else
914                         handleFont(cur, cmd.argument(), "mathit");
915                 break;
916         case LFUN_FONT_NOUN:
917                 if (currentMode() == TEXT_MODE)
918                         // FIXME: should be "noun"
919                         handleFont(cur, cmd.argument(), "textsc");
920                 else
921                         handleFont(cur, cmd.argument(), "mathbb");
922                 break;
923         case LFUN_FONT_DEFAULT:
924                 handleFont(cur, cmd.argument(), "textnormal");
925                 break;
926
927         case LFUN_MATH_MODE: {
928 #if 1
929                 // ignore math-mode on when already in math mode
930                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
931                         break;
932                 cur.macroModeClose();
933                 docstring const save_selection = grabAndEraseSelection(cur);
934                 selClearOrDel(cur);
935                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
936                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
937                 cur.posBackward();
938                 cur.pushBackward(*cur.nextInset());
939                 cur.niceInsert(save_selection);
940 #else
941                 if (currentMode() == Inset::TEXT_MODE) {
942                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
943                         cur.message(_("create new math text environment ($...$)"));
944                 } else {
945                         handleFont(cur, cmd.argument(), "textrm");
946                         cur.message(_("entered math text mode (textrm)"));
947                 }
948 #endif
949                 break;
950         }
951
952         case LFUN_MATH_SIZE: {
953                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
954                 doDispatch(cur, fr);
955                 break;
956         }
957
958         case LFUN_MATH_MATRIX: {
959                 cur.recordUndo();
960                 unsigned int m = 1;
961                 unsigned int n = 1;
962                 docstring v_align;
963                 docstring h_align;
964                 idocstringstream is(cmd.argument());
965                 is >> m >> n >> v_align >> h_align;
966                 if (m < 1)
967                         m = 1;
968                 if (n < 1)
969                         n = 1;
970                 v_align += 'c';
971                 cur.niceInsert(
972                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
973                 break;
974         }
975
976         case LFUN_MATH_DELIM: {
977                 docstring ls;
978                 docstring rs = split(cmd.argument(), ls, ' ');
979                 // Reasonable default values
980                 if (ls.empty())
981                         ls = '(';
982                 if (rs.empty())
983                         rs = ')';
984                 cur.recordUndo();
985                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
986                 break;
987         }
988
989         case LFUN_MATH_BIGDELIM: {
990                 docstring const lname  = from_utf8(cmd.getArg(0));
991                 docstring const ldelim = from_utf8(cmd.getArg(1));
992                 docstring const rname  = from_utf8(cmd.getArg(2));
993                 docstring const rdelim = from_utf8(cmd.getArg(3));
994                 latexkeys const * l = in_word_set(lname);
995                 bool const have_l = l && l->inset == "big" &&
996                                     InsetMathBig::isBigInsetDelim(ldelim);
997                 l = in_word_set(rname);
998                 bool const have_r = l && l->inset == "big" &&
999                                     InsetMathBig::isBigInsetDelim(rdelim);
1000                 // We mimic LFUN_MATH_DELIM in case we have an empty left
1001                 // or right delimiter.
1002                 if (have_l || have_r) {
1003                         cur.recordUndo();
1004                         docstring const selection = grabAndEraseSelection(cur);
1005                         selClearOrDel(cur);
1006                         if (have_l)
1007                                 cur.insert(MathAtom(new InsetMathBig(lname,
1008                                                                 ldelim)));
1009                         cur.niceInsert(selection);
1010                         if (have_r)
1011                                 cur.insert(MathAtom(new InsetMathBig(rname,
1012                                                                 rdelim)));
1013                 }
1014                 // Don't call cur.undispatched() if we did nothing, this would
1015                 // lead to infinite recursion via Text::dispatch().
1016                 break;
1017         }
1018
1019         case LFUN_SPACE_INSERT:
1020                 cur.recordUndoSelection();
1021                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1022                 break;
1023
1024         case LFUN_MATH_SPACE:
1025                 cur.recordUndoSelection();
1026                 if (cmd.argument().empty())
1027                         cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1028                 else
1029                         cur.insert(MathAtom(new InsetMathSpace(cmd.argument())));
1030                 break;
1031
1032         case LFUN_ERT_INSERT:
1033                 // interpret this as if a backslash was typed
1034                 cur.recordUndo();
1035                 interpretChar(cur, '\\');
1036                 break;
1037
1038         case LFUN_MATH_SUBSCRIPT:
1039                 // interpret this as if a _ was typed
1040                 cur.recordUndoSelection();
1041                 interpretChar(cur, '_');
1042                 break;
1043
1044         case LFUN_MATH_SUPERSCRIPT:
1045                 // interpret this as if a ^ was typed
1046                 cur.recordUndoSelection();
1047                 interpretChar(cur, '^');
1048                 break;
1049                 
1050         case LFUN_MATH_MACRO_FOLD:
1051         case LFUN_MATH_MACRO_UNFOLD: {
1052                 Cursor it = cur;
1053                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
1054                 bool found = findMacroToFoldUnfold(it, fold);
1055                 if (found) {
1056                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1057                         cur.recordUndoInset();
1058                         if (fold)
1059                                 macro->fold(cur);
1060                         else
1061                                 macro->unfold(cur);
1062                 }
1063                 break;
1064         }
1065
1066         case LFUN_QUOTE_INSERT:
1067                 // interpret this as if a straight " was typed
1068                 cur.recordUndoSelection();
1069                 interpretChar(cur, '\"');
1070                 break;
1071
1072 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1073 // handling such that "self-insert" works on "arbitrary stuff" too, and
1074 // math-insert only handles special math things like "matrix".
1075         case LFUN_MATH_INSERT: {
1076                 cur.recordUndoSelection();
1077                 if (cmd.argument() == "^" || cmd.argument() == "_")
1078                         interpretChar(cur, cmd.argument()[0]);
1079                 else {
1080                         MathData ar;
1081                         asArray(cmd.argument(), ar);
1082                         if (ar.size() == 1 && ar[0]->asNestInset()
1083                                         && ar[0]->asNestInset()->nargs() > 1)
1084                                 handleNest(cur, ar[0]);
1085                         else
1086                                 cur.niceInsert(cmd.argument());
1087                 }
1088                 break;
1089                 }
1090
1091         case LFUN_DIALOG_SHOW_NEW_INSET: {
1092                 docstring const & name = cmd.argument();
1093                 string data;
1094                 if (name == "ref") {
1095                         InsetMathRef tmp(name);
1096                         data = tmp.createDialogStr(to_utf8(name));
1097                 }
1098                 cur.bv().showDialog(to_utf8(name), data);
1099                 break;
1100         }
1101
1102         case LFUN_INSET_INSERT: {
1103                 MathData ar;
1104                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1105                         cur.recordUndoSelection();
1106                         cur.insert(ar);
1107                 } else
1108                         cur.undispatched();
1109                 break;
1110         }
1111         case LFUN_INSET_DISSOLVE:
1112                 if (!asHullInset()) {
1113                         cur.recordUndoInset();
1114                         cur.pullArg();
1115                 }
1116                 break;
1117
1118         default:
1119                 InsetMath::doDispatch(cur, cmd);
1120                 break;
1121         }
1122 }
1123
1124
1125 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1126         // look for macro to open/close, but stay in mathed
1127         for (; !it.empty(); it.pop_back()) {
1128                         
1129                 // go backward through the current cell
1130                 Inset * inset = it.nextInset();
1131                 while (inset && inset->asInsetMath()) {
1132                         MathMacro * macro = inset->asInsetMath()->asMacro();
1133                         if (macro) {
1134                                 // found the an macro to open/close?
1135                                 if (macro->folded() != fold)
1136                                         return true;
1137                                 
1138                                 // Wrong folding state.
1139                                 // If this was the first we see in this slice, look further left,
1140                                 // otherwise go up.
1141                                 if (inset != it.nextInset())
1142                                         break;
1143                         }
1144                         
1145                         // go up if this was the left most position
1146                         if (it.pos() == 0)
1147                                 break;
1148                         
1149                         // go left
1150                         it.pos()--;
1151                         inset = it.nextInset();
1152                 }
1153         }
1154         
1155         return false;
1156 }
1157
1158
1159 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1160                 FuncStatus & flag) const
1161 {
1162         // the font related toggles
1163         //string tc = "mathnormal";
1164         bool ret = true;
1165         string const arg = to_utf8(cmd.argument());
1166         switch (cmd.action) {
1167         case LFUN_TABULAR_FEATURE:
1168                 flag.setEnabled(false);
1169                 break;
1170 #if 0
1171         case LFUN_TABULAR_FEATURE:
1172                 // FIXME: check temporarily disabled
1173                 // valign code
1174                 char align = mathcursor::valign();
1175                 if (align == '\0') {
1176                         enable = false;
1177                         break;
1178                 }
1179                 if (cmd.argument().empty()) {
1180                         flag.clear();
1181                         break;
1182                 }
1183                 if (!contains("tcb", cmd.argument()[0])) {
1184                         enable = false;
1185                         break;
1186                 }
1187                 flag.setOnOff(cmd.argument()[0] == align);
1188                 break;
1189 #endif
1190         /// We have to handle them since 1.4 blocks all unhandled actions
1191         case LFUN_FONT_ITAL:
1192         case LFUN_FONT_BOLD:
1193         case LFUN_FONT_SANS:
1194         case LFUN_FONT_EMPH:
1195         case LFUN_FONT_TYPEWRITER:
1196         case LFUN_FONT_NOUN:
1197         case LFUN_FONT_ROMAN:
1198         case LFUN_FONT_DEFAULT:
1199                 flag.setEnabled(true);
1200                 break;
1201         case LFUN_MATH_MUTATE:
1202                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1203                 flag.setOnOff(false);
1204                 break;
1205
1206         // we just need to be in math mode to enable that
1207         case LFUN_MATH_SIZE:
1208         case LFUN_MATH_SPACE:
1209         case LFUN_MATH_LIMITS:
1210         case LFUN_MATH_EXTERN:
1211                 flag.setEnabled(true);
1212                 break;
1213
1214         case LFUN_FONT_FRAK:
1215                 flag.setEnabled(currentMode() != TEXT_MODE);
1216                 break;
1217
1218         case LFUN_MATH_INSERT: {
1219                 bool const textarg =
1220                         arg == "\\textbf"   || arg == "\\textsf" ||
1221                         arg == "\\textrm"   || arg == "\\textmd" ||
1222                         arg == "\\textit"   || arg == "\\textsc" ||
1223                         arg == "\\textsl"   || arg == "\\textup" ||
1224                         arg == "\\texttt"   || arg == "\\textbb" ||
1225                         arg == "\\textnormal";
1226                 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1227                 break;
1228         }
1229
1230         case LFUN_MATH_MATRIX:
1231                 flag.setEnabled(currentMode() == MATH_MODE);
1232                 break;
1233
1234         case LFUN_INSET_INSERT: {
1235                 // Don't test createMathInset_fromDialogStr(), since
1236                 // getStatus is not called with a valid reference and the
1237                 // dialog would not be applyable.
1238                 string const name = cmd.getArg(0);
1239                 flag.setEnabled(name == "ref");
1240                 break;
1241         }
1242
1243         case LFUN_MATH_DELIM:
1244         case LFUN_MATH_BIGDELIM:
1245                 // Don't do this with multi-cell selections
1246                 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1247                 break;
1248                 
1249         case LFUN_MATH_MACRO_FOLD:
1250         case LFUN_MATH_MACRO_UNFOLD: {
1251                 Cursor it = cur;
1252                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1253                 flag.setEnabled(found);
1254                 break;
1255         }
1256                 
1257         case LFUN_SPECIALCHAR_INSERT:
1258                 // FIXME: These would probably make sense in math-text mode
1259                 flag.setEnabled(false);
1260                 break;
1261
1262         case LFUN_INSET_DISSOLVE:
1263                 flag.setEnabled(!asHullInset());
1264                 break;
1265
1266         default:
1267                 ret = false;
1268                 break;
1269         }
1270         return ret;
1271 }
1272
1273
1274 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1275 {
1276         cur.push(*this);
1277         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1278                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1279         cur.idx() = enter_front ? 0 : cur.lastidx();
1280         cur.pos() = enter_front ? 0 : cur.lastpos();
1281         cur.resetAnchor();
1282         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1283 }
1284
1285
1286 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1287 {
1288         int idx_min = 0;
1289         int dist_min = 1000000;
1290         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1291                 int const d = cell(i).dist(cur.bv(), x, y);
1292                 if (d < dist_min) {
1293                         dist_min = d;
1294                         idx_min = i;
1295                 }
1296         }
1297         MathData & ar = cell(idx_min);
1298         cur.push(*this);
1299         cur.idx() = idx_min;
1300         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1301
1302         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1303         if (dist_min == 0) {
1304                 // hit inside cell
1305                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1306                         if (ar[i]->covers(cur.bv(), x, y))
1307                                 return ar[i].nucleus()->editXY(cur, x, y);
1308         }
1309         return this;
1310 }
1311
1312
1313 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1314 {
1315         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1316         BufferView & bv = cur.bv();
1317         bool do_selection = cmd.button() == mouse_button::button1
1318                 && cmd.argument() == "region-select";
1319         bv.mouseSetCursor(cur, do_selection);
1320         if (cmd.button() == mouse_button::button1) {
1321                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1322                 // Update the cursor update flags as needed:
1323                 //
1324                 // Update::Decoration: tells to update the decoration
1325                 //                     (visual box corners that define
1326                 //                     the inset)/
1327                 // Update::FitCursor: adjust the screen to the cursor
1328                 //                    position if needed
1329                 // cur.result().update(): don't overwrite previously set flags.
1330                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1331                                 | cur.result().update());
1332         } else if (cmd.button() == mouse_button::button2) {
1333                 if (cap::selection()) {
1334                         // See comment in Text::dispatch why we do this
1335                         cap::copySelectionToStack();
1336                         cmd = FuncRequest(LFUN_PASTE, "0");
1337                         doDispatch(bv.cursor(), cmd);
1338                 } else {
1339                         MathData ar;
1340                         asArray(theSelection().get(), ar);
1341                         bv.cursor().insert(ar);
1342                 }
1343         }
1344 }
1345
1346
1347 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1348 {
1349         // only select with button 1
1350         if (cmd.button() == mouse_button::button1) {
1351                 Cursor & bvcur = cur.bv().cursor();
1352                 if (bvcur.anchor_.hasPart(cur)) {
1353                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1354                         bvcur.setCursor(cur);
1355                         bvcur.selection() = true;
1356                         //lyxerr << "MOTION " << bvcur << endl;
1357                 } else
1358                         cur.undispatched();
1359         }
1360 }
1361
1362
1363 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1364 {
1365         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1366
1367         if (cmd.button() == mouse_button::button1) {
1368                 if (!cur.selection())
1369                         cur.noUpdate();
1370                 else {
1371                         Cursor & bvcur = cur.bv().cursor();
1372                         bvcur.selection() = true;
1373                 }
1374                 return;
1375         }
1376
1377         cur.undispatched();
1378 }
1379
1380
1381 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1382 {
1383         //lyxerr << "interpret 2: '" << c << "'" << endl;
1384         docstring save_selection;
1385         if (c == '^' || c == '_')
1386                 save_selection = grabAndEraseSelection(cur);
1387
1388         cur.clearTargetX();
1389
1390         // handle macroMode
1391         if (cur.inMacroMode()) {
1392                 docstring name = cur.macroName();
1393
1394                 /// are we currently typing '#1' or '#2' or...?
1395                 if (name == "\\#") {
1396                         cur.backspace();
1397                         int n = c - '0';
1398                         if (n >= 1 && n <= 9)
1399                                 cur.insert(new MathMacroArgument(n));
1400                         return true;
1401                 }
1402
1403                 // do not finish macro for known * commands
1404                 MathWordList const & mwl = mathedWordList();
1405                 bool star_macro = c == '*'
1406                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1407                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1408                 if (isAlphaASCII(c) || star_macro) {
1409                         cur.activeMacro()->setName(name + docstring(1, c));
1410                         return true;
1411                 }
1412
1413                 // handle 'special char' macros
1414                 if (name == "\\") {
1415                         // remove the '\\'
1416                         if (c == '\\') {
1417                                 cur.backspace();
1418                                 if (currentMode() == InsetMath::TEXT_MODE)
1419                                         cur.niceInsert(createInsetMath("textbackslash"));
1420                                 else
1421                                         cur.niceInsert(createInsetMath("backslash"));
1422                         } else if (c == '{') {
1423                                 cur.backspace();
1424                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1425                         } else if (c == '%') {
1426                                 cur.backspace();
1427                                 cur.niceInsert(MathAtom(new InsetMathComment));
1428                         } else if (c == '#') {
1429                                 LASSERT(cur.activeMacro(), /**/);
1430                                 cur.activeMacro()->setName(name + docstring(1, c));
1431                         } else {
1432                                 cur.backspace();
1433                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1434                         }
1435                         return true;
1436                 }
1437
1438                 // One character big delimiters. The others are handled in
1439                 // interpretString().
1440                 latexkeys const * l = in_word_set(name.substr(1));
1441                 if (name[0] == '\\' && l && l->inset == "big") {
1442                         docstring delim;
1443                         switch (c) {
1444                         case '{':
1445                                 delim = from_ascii("\\{");
1446                                 break;
1447                         case '}':
1448                                 delim = from_ascii("\\}");
1449                                 break;
1450                         default:
1451                                 delim = docstring(1, c);
1452                                 break;
1453                         }
1454                         if (InsetMathBig::isBigInsetDelim(delim)) {
1455                                 // name + delim ared a valid InsetMathBig.
1456                                 // We can't use cur.macroModeClose() because
1457                                 // it does not handle delim.
1458                                 InsetMathUnknown * p = cur.activeMacro();
1459                                 p->finalize();
1460                                 --cur.pos();
1461                                 cur.cell().erase(cur.pos());
1462                                 cur.plainInsert(MathAtom(
1463                                         new InsetMathBig(name.substr(1), delim)));
1464                                 return true;
1465                         }
1466                 }
1467
1468                 // leave macro mode and try again if necessary
1469                 cur.macroModeClose();
1470                 if (c == '{')
1471                         cur.niceInsert(MathAtom(new InsetMathBrace));
1472                 else if (c != ' ')
1473                         interpretChar(cur, c);
1474                 return true;
1475         }
1476
1477         // This is annoying as one has to press <space> far too often.
1478         // Disable it.
1479
1480 #if 0
1481                 // leave autocorrect mode if necessary
1482                 if (autocorrect() && c == ' ') {
1483                         autocorrect() = false;
1484                         return true;
1485                 }
1486 #endif
1487
1488         // just clear selection on pressing the space bar
1489         if (cur.selection() && c == ' ') {
1490                 cur.selection() = false;
1491                 return true;
1492         }
1493
1494         if (c == '\\') {
1495                 //lyxerr << "starting with macro" << endl;
1496                 bool reduced = cap::reduceSelectionToOneCell(cur);
1497                 if (reduced || !cur.selection()) {
1498                         docstring const safe = cap::grabAndEraseSelection(cur);
1499                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1500                 }
1501                 return true;
1502         }
1503
1504         selClearOrDel(cur);
1505
1506         if (c == '\n') {
1507                 if (currentMode() == InsetMath::TEXT_MODE)
1508                         cur.insert(c);
1509                 return true;
1510         }
1511
1512         if (c == ' ') {
1513                 if (currentMode() == InsetMath::TEXT_MODE) {
1514                         // insert spaces in text mode,
1515                         // but suppress direct insertion of two spaces in a row
1516                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1517                         // it is better than nothing...
1518                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1519                                 cur.insert(c);
1520                                 // FIXME: we have to enable full redraw here because of the
1521                                 // visual box corners that define the inset. If we know for
1522                                 // sure that we stay within the same cell we can optimize for
1523                                 // that using:
1524                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1525                         }
1526                         return true;
1527                 }
1528                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1529                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1530                         // FIXME: we have to enable full redraw here because of the
1531                         // visual box corners that define the inset. If we know for
1532                         // sure that we stay within the same cell we can optimize for
1533                         // that using:
1534                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1535                         return true;
1536                 }
1537
1538                 if (cur.popForward()) {
1539                         // FIXME: we have to enable full redraw here because of the
1540                         // visual box corners that define the inset. If we know for
1541                         // sure that we stay within the same cell we can optimize for
1542                         // that using:
1543                         //cur.updateFlags(Update::FitCursor);
1544                         return true;
1545                 }
1546
1547                 // if we are at the very end, leave the formula
1548                 return cur.pos() != cur.lastpos();
1549         }
1550
1551         // These shouldn't work in text mode:
1552         if (currentMode() != InsetMath::TEXT_MODE) {
1553                 if (c == '_') {
1554                         script(cur, false, save_selection);
1555                         return true;
1556                 }
1557                 if (c == '^') {
1558                         script(cur, true, save_selection);
1559                         return true;
1560                 }
1561                 if (c == '~') {
1562                         cur.niceInsert(createInsetMath("sim"));
1563                         return true;
1564                 }
1565         }
1566
1567         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1568             c == '%' || c == '_' || c == '^') {
1569                 cur.niceInsert(createInsetMath(docstring(1, c)));
1570                 return true;
1571         }
1572
1573
1574         // try auto-correction
1575         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1576         //      return true;
1577
1578         // no special circumstances, so insert the character without any fuss
1579         cur.insert(c);
1580         cur.autocorrect() = true;
1581         return true;
1582 }
1583
1584
1585 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1586 {
1587         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1588         // possible
1589         if (!cur.empty() && cur.pos() > 0 &&
1590             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1591                 if (InsetMathBig::isBigInsetDelim(str)) {
1592                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1593                         if (prev[0] == '\\') {
1594                                 prev = prev.substr(1);
1595                                 latexkeys const * l = in_word_set(prev);
1596                                 if (l && l->inset == "big") {
1597                                         cur.cell()[cur.pos() - 1] =
1598                                                 MathAtom(new InsetMathBig(prev, str));
1599                                         return true;
1600                                 }
1601                         }
1602                 }
1603         }
1604         return false;
1605 }
1606
1607
1608 bool InsetMathNest::script(Cursor & cur, bool up)
1609 {
1610         return script(cur, up, docstring());
1611 }
1612
1613
1614 bool InsetMathNest::script(Cursor & cur, bool up,
1615                 docstring const & save_selection)
1616 {
1617         // Hack to get \^ and \_ working
1618         //lyxerr << "handling script: up: " << up << endl;
1619         if (cur.inMacroMode() && cur.macroName() == "\\") {
1620                 if (up)
1621                         cur.niceInsert(createInsetMath("mathcircumflex"));
1622                 else
1623                         interpretChar(cur, '_');
1624                 return true;
1625         }
1626
1627         cur.macroModeClose();
1628         if (asScriptInset() && cur.idx() == 0) {
1629                 // we are in a nucleus of a script inset, move to _our_ script
1630                 InsetMathScript * inset = asScriptInset();
1631                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1632                 inset->ensure(up);
1633                 cur.idx() = inset->idxOfScript(up);
1634                 cur.pos() = 0;
1635         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1636                 --cur.pos();
1637                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1638                 cur.push(*inset);
1639                 inset->ensure(up);
1640                 cur.idx() = inset->idxOfScript(up);
1641                 cur.pos() = cur.lastpos();
1642         } else {
1643                 // convert the thing to our left to a scriptinset or create a new
1644                 // one if in the very first position of the array
1645                 if (cur.pos() == 0) {
1646                         //lyxerr << "new scriptinset" << endl;
1647                         cur.insert(new InsetMathScript(up));
1648                 } else {
1649                         //lyxerr << "converting prev atom " << endl;
1650                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1651                 }
1652                 --cur.pos();
1653                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1654                 // See comment in MathParser.cpp for special handling of {}-bases
1655
1656                 cur.push(*inset);
1657                 cur.idx() = 1;
1658                 cur.pos() = 0;
1659         }
1660         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1661         cur.niceInsert(save_selection);
1662         cur.resetAnchor();
1663         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1664         return true;
1665 }
1666
1667
1668 bool InsetMathNest::completionSupported(Cursor const & cur) const
1669 {
1670         return cur.inMacroMode();
1671 }
1672
1673
1674 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1675 {
1676         return cur.inMacroMode();
1677 }
1678
1679
1680 bool InsetMathNest::automaticInlineCompletion() const
1681 {
1682         return lyxrc.completion_inline_math;
1683 }
1684
1685
1686 bool InsetMathNest::automaticPopupCompletion() const
1687 {
1688         return lyxrc.completion_popup_math;
1689 }
1690
1691
1692 CompletionList const *
1693 InsetMathNest::createCompletionList(Cursor const & cur) const
1694 {
1695         if (!cur.inMacroMode())
1696                 return 0;
1697         
1698         return new MathCompletionList(cur);
1699 }
1700
1701
1702 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1703 {
1704         if (!cur.inMacroMode())
1705                 return docstring();
1706         
1707         return cur.activeMacro()->name();
1708 }
1709
1710
1711 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1712                                      bool finished)
1713 {
1714         if (!cur.inMacroMode())
1715                 return false;
1716
1717         // append completion to active macro
1718         InsetMathUnknown * inset = cur.activeMacro();
1719         inset->setName(inset->name() + s);
1720
1721         // finish macro
1722         if (finished) {
1723 #if 0
1724                 // FIXME: this creates duplicates in the completion popup
1725                 // which looks ugly. Moreover the changes the list lengths
1726                 // which seems to
1727                 confuse the popup as well.
1728                 MathCompletionList::addToFavorites(inset->name());
1729 #endif
1730                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1731         }
1732
1733         return true;
1734 }
1735
1736
1737 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1738                                         Dimension & dim) const
1739 {
1740         Inset const * inset = cur.activeMacro();
1741         if (!inset)
1742                 return;
1743
1744         // get inset dimensions
1745         dim = cur.bv().coordCache().insets().dim(inset);
1746         // FIXME: these 3 are no accurate, but should depend on the font.
1747         // Now the popup jumps down if you enter a char with descent > 0.
1748         dim.des += 3;
1749         dim.asc += 3;
1750
1751         // and position
1752         Point xy
1753         = cur.bv().coordCache().insets().xy(inset);
1754         x = xy.x_;
1755         y = xy.y_;
1756 }
1757
1758
1759 bool InsetMathNest::cursorMathForward(Cursor & cur)
1760 {
1761         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1762                 cur.pushBackward(*cur.nextAtom().nucleus());
1763                 cur.inset().idxFirst(cur);
1764                 return true;
1765         } 
1766         if (cur.posForward() || idxForward(cur))
1767                 return true;
1768         // try to pop forwards --- but don't pop out of math! leave that to
1769         // the FINISH lfuns
1770         int s = cur.depth() - 2;
1771         if (s >= 0 && cur[s].inset().asInsetMath())
1772                 return cur.popForward();
1773         return false;
1774 }
1775
1776
1777 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1778 {
1779         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1780                 cur.posBackward();
1781                 cur.push(*cur.nextAtom().nucleus());
1782                 cur.inset().idxLast(cur);
1783                 return true;
1784         } 
1785         if (cur.posBackward() || idxBackward(cur))
1786                 return true;
1787         // try to pop backwards --- but don't pop out of math! leave that to 
1788         // the FINISH lfuns
1789         int s = cur.depth() - 2;
1790         if (s >= 0 && cur[s].inset().asInsetMath())
1791                 return cur.popBackward();
1792         return false;
1793 }
1794
1795
1796 ////////////////////////////////////////////////////////////////////
1797
1798 MathCompletionList::MathCompletionList(Cursor const & cur)
1799 {
1800         // fill it with macros from the buffer
1801         MacroNameSet macros;
1802         cur.buffer().listMacroNames(macros);
1803         MacroNameSet::const_iterator it;
1804         for (it = macros.begin(); it != macros.end(); ++it) {
1805                 if (cur.buffer().getMacro(*it, cur, false))
1806                         locals.push_back("\\" + *it);
1807         }
1808         sort(locals.begin(), locals.end());
1809
1810         if (globals.size() > 0)
1811                 return;
1812
1813         // fill in global macros
1814         macros.clear();
1815         MacroTable::globalMacros().getMacroNames(macros);
1816         lyxerr << "Globals completion macros: ";
1817         for (it = macros.begin(); it != macros.end(); ++it) {
1818                 lyxerr << "\\" + *it << " ";
1819                 globals.push_back("\\" + *it);
1820         }
1821         lyxerr << std::endl;
1822
1823         // fill in global commands
1824         globals.push_back(from_ascii("\\boxed"));
1825         globals.push_back(from_ascii("\\fbox"));
1826         globals.push_back(from_ascii("\\framebox"));
1827         globals.push_back(from_ascii("\\makebox"));
1828         globals.push_back(from_ascii("\\kern"));
1829         globals.push_back(from_ascii("\\xrightarrow"));
1830         globals.push_back(from_ascii("\\xleftarrow"));
1831         globals.push_back(from_ascii("\\split"));
1832         globals.push_back(from_ascii("\\gathered"));
1833         globals.push_back(from_ascii("\\aligned"));
1834         globals.push_back(from_ascii("\\alignedat"));
1835         globals.push_back(from_ascii("\\cases"));
1836         globals.push_back(from_ascii("\\substack"));
1837         globals.push_back(from_ascii("\\subarray"));
1838         globals.push_back(from_ascii("\\array"));
1839         globals.push_back(from_ascii("\\sqrt"));
1840         globals.push_back(from_ascii("\\root"));
1841         globals.push_back(from_ascii("\\tabular"));
1842         globals.push_back(from_ascii("\\stackrel"));
1843         globals.push_back(from_ascii("\\binom"));
1844         globals.push_back(from_ascii("\\choose"));
1845         globals.push_back(from_ascii("\\brace"));
1846         globals.push_back(from_ascii("\\brack"));
1847         globals.push_back(from_ascii("\\frac"));
1848         globals.push_back(from_ascii("\\over"));
1849         globals.push_back(from_ascii("\\nicefrac"));
1850         globals.push_back(from_ascii("\\unitfrac"));
1851         globals.push_back(from_ascii("\\unitfracthree"));
1852         globals.push_back(from_ascii("\\unitone"));
1853         globals.push_back(from_ascii("\\unittwo"));
1854         globals.push_back(from_ascii("\\infer"));
1855         globals.push_back(from_ascii("\\atop"));
1856         globals.push_back(from_ascii("\\lefteqn"));
1857         globals.push_back(from_ascii("\\boldsymbol"));
1858         globals.push_back(from_ascii("\\bm"));
1859         globals.push_back(from_ascii("\\color"));
1860         globals.push_back(from_ascii("\\normalcolor"));
1861         globals.push_back(from_ascii("\\textcolor"));
1862         globals.push_back(from_ascii("\\dfrac"));
1863         globals.push_back(from_ascii("\\tfrac"));
1864         globals.push_back(from_ascii("\\dbinom"));
1865         globals.push_back(from_ascii("\\tbinom"));
1866         globals.push_back(from_ascii("\\hphantom"));
1867         globals.push_back(from_ascii("\\phantom"));
1868         globals.push_back(from_ascii("\\vphantom"));
1869         MathWordList const & words = mathedWordList();
1870         MathWordList::const_iterator it2;
1871         lyxerr << "Globals completion commands: ";
1872         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1873                 globals.push_back("\\" + (*it2).first);
1874                 lyxerr << "\\" + (*it2).first << " ";
1875         }
1876         lyxerr << std::endl;
1877         sort(globals.begin(), globals.end());
1878 }
1879
1880
1881 MathCompletionList::~MathCompletionList()
1882 {
1883 }
1884
1885
1886 size_type MathCompletionList::size() const
1887 {
1888         return locals.size() + globals.size();
1889 }
1890
1891
1892 docstring const & MathCompletionList::data(size_t idx) const
1893 {
1894         size_t lsize = locals.size();
1895         if (idx >= lsize)
1896                 return globals[idx - lsize];
1897         else
1898                 return locals[idx];
1899 }
1900
1901
1902 std::string MathCompletionList::icon(size_t idx) const 
1903 {
1904         // get the latex command
1905         docstring cmd;
1906         size_t lsize = locals.size();
1907         if (idx >= lsize)
1908                 cmd = globals[idx - lsize];
1909         else
1910                 cmd = locals[idx];
1911         
1912         // get the icon resource name by stripping the backslash
1913         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1914 }
1915
1916 std::vector<docstring> MathCompletionList::globals;
1917
1918 } // namespace lyx