]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
streamlining setter syntax. using mutable references seems a bit
[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.setSelection(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(), "mathbf");
882                 break;
883         case LFUN_FONT_BOLDSYMBOL:
884                 if (currentMode() == TEXT_MODE)
885                         handleFont(cur, cmd.argument(), "textbf");
886                 else
887                         handleFont(cur, cmd.argument(), "boldsymbol");
888                 break;
889         case LFUN_FONT_SANS:
890                 if (currentMode() == TEXT_MODE)
891                         handleFont(cur, cmd.argument(), "textsf");
892                 else
893                         handleFont(cur, cmd.argument(), "mathsf");
894                 break;
895         case LFUN_FONT_EMPH:
896                 if (currentMode() == TEXT_MODE)
897                         handleFont(cur, cmd.argument(), "emph");
898                 else
899                         handleFont(cur, cmd.argument(), "mathcal");
900                 break;
901         case LFUN_FONT_ROMAN:
902                 if (currentMode() == TEXT_MODE)
903                         handleFont(cur, cmd.argument(), "textrm");
904                 else
905                         handleFont(cur, cmd.argument(), "mathrm");
906                 break;
907         case LFUN_FONT_TYPEWRITER:
908                 if (currentMode() == TEXT_MODE)
909                         handleFont(cur, cmd.argument(), "texttt");
910                 else
911                         handleFont(cur, cmd.argument(), "mathtt");
912                 break;
913         case LFUN_FONT_FRAK:
914                 handleFont(cur, cmd.argument(), "mathfrak");
915                 break;
916         case LFUN_FONT_ITAL:
917                 if (currentMode() == TEXT_MODE)
918                         handleFont(cur, cmd.argument(), "textit");
919                 else
920                         handleFont(cur, cmd.argument(), "mathit");
921                 break;
922         case LFUN_FONT_NOUN:
923                 if (currentMode() == TEXT_MODE)
924                         // FIXME: should be "noun"
925                         handleFont(cur, cmd.argument(), "textsc");
926                 else
927                         handleFont(cur, cmd.argument(), "mathbb");
928                 break;
929         case LFUN_FONT_DEFAULT:
930                 handleFont(cur, cmd.argument(), "textnormal");
931                 break;
932
933         case LFUN_MATH_MODE: {
934 #if 1
935                 // ignore math-mode on when already in math mode
936                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
937                         break;
938                 cur.recordUndoSelection();
939                 cur.macroModeClose();
940                 docstring const save_selection = grabAndEraseSelection(cur);
941                 selClearOrDel(cur);
942                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
943                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
944                 cur.posBackward();
945                 cur.pushBackward(*cur.nextInset());
946                 cur.niceInsert(save_selection);
947 #else
948                 if (currentMode() == Inset::TEXT_MODE) {
949                         cur.recordUndoSelection();
950                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
951                         cur.message(_("create new math text environment ($...$)"));
952                 } else {
953                         handleFont(cur, cmd.argument(), "textrm");
954                         cur.message(_("entered math text mode (textrm)"));
955                 }
956 #endif
957                 break;
958         }
959
960         case LFUN_MATH_SIZE: {
961                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
962                 doDispatch(cur, fr);
963                 break;
964         }
965
966         case LFUN_MATH_MATRIX: {
967                 cur.recordUndo();
968                 unsigned int m = 1;
969                 unsigned int n = 1;
970                 docstring v_align;
971                 docstring h_align;
972                 idocstringstream is(cmd.argument());
973                 is >> m >> n >> v_align >> h_align;
974                 if (m < 1)
975                         m = 1;
976                 if (n < 1)
977                         n = 1;
978                 v_align += 'c';
979                 cur.niceInsert(
980                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
981                 break;
982         }
983
984         case LFUN_MATH_DELIM: {
985                 docstring ls;
986                 docstring rs = split(cmd.argument(), ls, ' ');
987                 // Reasonable default values
988                 if (ls.empty())
989                         ls = '(';
990                 if (rs.empty())
991                         rs = ')';
992                 cur.recordUndo();
993                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
994                 break;
995         }
996
997         case LFUN_MATH_BIGDELIM: {
998                 docstring const lname  = from_utf8(cmd.getArg(0));
999                 docstring const ldelim = from_utf8(cmd.getArg(1));
1000                 docstring const rname  = from_utf8(cmd.getArg(2));
1001                 docstring const rdelim = from_utf8(cmd.getArg(3));
1002                 latexkeys const * l = in_word_set(lname);
1003                 bool const have_l = l && l->inset == "big" &&
1004                                     InsetMathBig::isBigInsetDelim(ldelim);
1005                 l = in_word_set(rname);
1006                 bool const have_r = l && l->inset == "big" &&
1007                                     InsetMathBig::isBigInsetDelim(rdelim);
1008                 // We mimic LFUN_MATH_DELIM in case we have an empty left
1009                 // or right delimiter.
1010                 if (have_l || have_r) {
1011                         cur.recordUndo();
1012                         docstring const selection = grabAndEraseSelection(cur);
1013                         selClearOrDel(cur);
1014                         if (have_l)
1015                                 cur.insert(MathAtom(new InsetMathBig(lname,
1016                                                                 ldelim)));
1017                         cur.niceInsert(selection);
1018                         if (have_r)
1019                                 cur.insert(MathAtom(new InsetMathBig(rname,
1020                                                                 rdelim)));
1021                 }
1022                 // Don't call cur.undispatched() if we did nothing, this would
1023                 // lead to infinite recursion via Text::dispatch().
1024                 break;
1025         }
1026
1027         case LFUN_SPACE_INSERT:
1028                 cur.recordUndoSelection();
1029                 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1030                 break;
1031
1032         case LFUN_MATH_SPACE:
1033                 cur.recordUndoSelection();
1034                 if (cmd.argument().empty())
1035                         cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
1036                 else
1037                         cur.insert(MathAtom(new InsetMathSpace(cmd.argument())));
1038                 break;
1039
1040         case LFUN_ERT_INSERT:
1041                 // interpret this as if a backslash was typed
1042                 cur.recordUndo();
1043                 interpretChar(cur, '\\');
1044                 break;
1045
1046         case LFUN_MATH_SUBSCRIPT:
1047                 // interpret this as if a _ was typed
1048                 cur.recordUndoSelection();
1049                 interpretChar(cur, '_');
1050                 break;
1051
1052         case LFUN_MATH_SUPERSCRIPT:
1053                 // interpret this as if a ^ was typed
1054                 cur.recordUndoSelection();
1055                 interpretChar(cur, '^');
1056                 break;
1057                 
1058         case LFUN_MATH_MACRO_FOLD:
1059         case LFUN_MATH_MACRO_UNFOLD: {
1060                 Cursor it = cur;
1061                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
1062                 bool found = findMacroToFoldUnfold(it, fold);
1063                 if (found) {
1064                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1065                         cur.recordUndoInset();
1066                         if (fold)
1067                                 macro->fold(cur);
1068                         else
1069                                 macro->unfold(cur);
1070                 }
1071                 break;
1072         }
1073
1074         case LFUN_QUOTE_INSERT:
1075                 // interpret this as if a straight " was typed
1076                 cur.recordUndoSelection();
1077                 interpretChar(cur, '\"');
1078                 break;
1079
1080 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1081 // handling such that "self-insert" works on "arbitrary stuff" too, and
1082 // math-insert only handles special math things like "matrix".
1083         case LFUN_MATH_INSERT: {
1084                 cur.recordUndoSelection();
1085                 if (cmd.argument() == "^" || cmd.argument() == "_")
1086                         interpretChar(cur, cmd.argument()[0]);
1087                 else {
1088                         MathData ar;
1089                         asArray(cmd.argument(), ar);
1090                         if (ar.size() == 1 && ar[0]->asNestInset()
1091                                         && ar[0]->asNestInset()->nargs() > 1)
1092                                 handleNest(cur, ar[0]);
1093                         else
1094                                 cur.niceInsert(cmd.argument());
1095                 }
1096                 break;
1097                 }
1098
1099         case LFUN_DIALOG_SHOW_NEW_INSET: {
1100                 docstring const & name = cmd.argument();
1101                 string data;
1102                 if (name == "ref") {
1103                         InsetMathRef tmp(name);
1104                         data = tmp.createDialogStr(to_utf8(name));
1105                 }
1106                 cur.bv().showDialog(to_utf8(name), data);
1107                 break;
1108         }
1109
1110         case LFUN_INSET_INSERT: {
1111                 MathData ar;
1112                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1113                         cur.recordUndoSelection();
1114                         cur.insert(ar);
1115                 } else
1116                         cur.undispatched();
1117                 break;
1118         }
1119         case LFUN_INSET_DISSOLVE:
1120                 if (!asHullInset()) {
1121                         cur.recordUndoInset();
1122                         cur.pullArg();
1123                 }
1124                 break;
1125
1126         default:
1127                 InsetMath::doDispatch(cur, cmd);
1128                 break;
1129         }
1130 }
1131
1132
1133 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1134         // look for macro to open/close, but stay in mathed
1135         for (; !it.empty(); it.pop_back()) {
1136                         
1137                 // go backward through the current cell
1138                 Inset * inset = it.nextInset();
1139                 while (inset && inset->asInsetMath()) {
1140                         MathMacro * macro = inset->asInsetMath()->asMacro();
1141                         if (macro) {
1142                                 // found the an macro to open/close?
1143                                 if (macro->folded() != fold)
1144                                         return true;
1145                                 
1146                                 // Wrong folding state.
1147                                 // If this was the first we see in this slice, look further left,
1148                                 // otherwise go up.
1149                                 if (inset != it.nextInset())
1150                                         break;
1151                         }
1152                         
1153                         // go up if this was the left most position
1154                         if (it.pos() == 0)
1155                                 break;
1156                         
1157                         // go left
1158                         it.pos()--;
1159                         inset = it.nextInset();
1160                 }
1161         }
1162         
1163         return false;
1164 }
1165
1166
1167 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1168                 FuncStatus & flag) const
1169 {
1170         // the font related toggles
1171         //string tc = "mathnormal";
1172         bool ret = true;
1173         string const arg = to_utf8(cmd.argument());
1174         switch (cmd.action) {
1175         case LFUN_TABULAR_FEATURE:
1176                 flag.setEnabled(false);
1177                 break;
1178 #if 0
1179         case LFUN_TABULAR_FEATURE:
1180                 // FIXME: check temporarily disabled
1181                 // valign code
1182                 char align = mathcursor::valign();
1183                 if (align == '\0') {
1184                         enable = false;
1185                         break;
1186                 }
1187                 if (cmd.argument().empty()) {
1188                         flag.clear();
1189                         break;
1190                 }
1191                 if (!contains("tcb", cmd.argument()[0])) {
1192                         enable = false;
1193                         break;
1194                 }
1195                 flag.setOnOff(cmd.argument()[0] == align);
1196                 break;
1197 #endif
1198         /// We have to handle them since 1.4 blocks all unhandled actions
1199         case LFUN_FONT_ITAL:
1200         case LFUN_FONT_BOLD:
1201         case LFUN_FONT_BOLDSYMBOL:
1202         case LFUN_FONT_SANS:
1203         case LFUN_FONT_EMPH:
1204         case LFUN_FONT_TYPEWRITER:
1205         case LFUN_FONT_NOUN:
1206         case LFUN_FONT_ROMAN:
1207         case LFUN_FONT_DEFAULT:
1208                 flag.setEnabled(true);
1209                 break;
1210         case LFUN_MATH_MUTATE:
1211                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1212                 flag.setOnOff(false);
1213                 break;
1214
1215         // we just need to be in math mode to enable that
1216         case LFUN_MATH_SIZE:
1217         case LFUN_MATH_SPACE:
1218         case LFUN_MATH_LIMITS:
1219         case LFUN_MATH_EXTERN:
1220                 flag.setEnabled(true);
1221                 break;
1222
1223         case LFUN_FONT_FRAK:
1224                 flag.setEnabled(currentMode() != TEXT_MODE);
1225                 break;
1226
1227         case LFUN_MATH_INSERT: {
1228                 bool const textarg =
1229                         arg == "\\textbf"   || arg == "\\textsf" ||
1230                         arg == "\\textrm"   || arg == "\\textmd" ||
1231                         arg == "\\textit"   || arg == "\\textsc" ||
1232                         arg == "\\textsl"   || arg == "\\textup" ||
1233                         arg == "\\texttt"   || arg == "\\textbb" ||
1234                         arg == "\\textnormal";
1235                 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1236                 break;
1237         }
1238
1239         case LFUN_MATH_MATRIX:
1240                 flag.setEnabled(currentMode() == MATH_MODE);
1241                 break;
1242
1243         case LFUN_INSET_INSERT: {
1244                 // Don't test createMathInset_fromDialogStr(), since
1245                 // getStatus is not called with a valid reference and the
1246                 // dialog would not be applyable.
1247                 string const name = cmd.getArg(0);
1248                 flag.setEnabled(name == "ref");
1249                 break;
1250         }
1251
1252         case LFUN_MATH_DELIM:
1253         case LFUN_MATH_BIGDELIM:
1254                 // Don't do this with multi-cell selections
1255                 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1256                 break;
1257                 
1258         case LFUN_MATH_MACRO_FOLD:
1259         case LFUN_MATH_MACRO_UNFOLD: {
1260                 Cursor it = cur;
1261                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1262                 flag.setEnabled(found);
1263                 break;
1264         }
1265                 
1266         case LFUN_SPECIALCHAR_INSERT:
1267                 // FIXME: These would probably make sense in math-text mode
1268                 flag.setEnabled(false);
1269                 break;
1270
1271         case LFUN_INSET_DISSOLVE:
1272                 flag.setEnabled(!asHullInset());
1273                 break;
1274
1275         default:
1276                 ret = false;
1277                 break;
1278         }
1279         return ret;
1280 }
1281
1282
1283 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1284 {
1285         cur.push(*this);
1286         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1287                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1288         cur.idx() = enter_front ? 0 : cur.lastidx();
1289         cur.pos() = enter_front ? 0 : cur.lastpos();
1290         cur.resetAnchor();
1291         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1292 }
1293
1294
1295 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1296 {
1297         int idx_min = 0;
1298         int dist_min = 1000000;
1299         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1300                 int const d = cell(i).dist(cur.bv(), x, y);
1301                 if (d < dist_min) {
1302                         dist_min = d;
1303                         idx_min = i;
1304                 }
1305         }
1306         MathData & ar = cell(idx_min);
1307         cur.push(*this);
1308         cur.idx() = idx_min;
1309         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1310
1311         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1312         if (dist_min == 0) {
1313                 // hit inside cell
1314                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1315                         if (ar[i]->covers(cur.bv(), x, y))
1316                                 return ar[i].nucleus()->editXY(cur, x, y);
1317         }
1318         return this;
1319 }
1320
1321
1322 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1323 {
1324         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1325         BufferView & bv = cur.bv();
1326         bool do_selection = cmd.button() == mouse_button::button1
1327                 && cmd.argument() == "region-select";
1328         bv.mouseSetCursor(cur, do_selection);
1329         if (cmd.button() == mouse_button::button1) {
1330                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1331                 // Update the cursor update flags as needed:
1332                 //
1333                 // Update::Decoration: tells to update the decoration
1334                 //                     (visual box corners that define
1335                 //                     the inset)/
1336                 // Update::FitCursor: adjust the screen to the cursor
1337                 //                    position if needed
1338                 // cur.result().update(): don't overwrite previously set flags.
1339                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1340                                 | cur.result().update());
1341         } else if (cmd.button() == mouse_button::button2) {
1342                 if (cap::selection()) {
1343                         // See comment in Text::dispatch why we do this
1344                         cap::copySelectionToStack();
1345                         cmd = FuncRequest(LFUN_PASTE, "0");
1346                         doDispatch(bv.cursor(), cmd);
1347                 } else {
1348                         MathData ar;
1349                         asArray(theSelection().get(), ar);
1350                         bv.cursor().insert(ar);
1351                 }
1352         }
1353 }
1354
1355
1356 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1357 {
1358         // only select with button 1
1359         if (cmd.button() == mouse_button::button1) {
1360                 Cursor & bvcur = cur.bv().cursor();
1361                 if (bvcur.anchor_.hasPart(cur)) {
1362                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1363                         bvcur.setCursor(cur);
1364                         bvcur.setSelection(true);
1365                         //lyxerr << "MOTION " << bvcur << endl;
1366                 } else
1367                         cur.undispatched();
1368         }
1369 }
1370
1371
1372 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1373 {
1374         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1375
1376         if (cmd.button() == mouse_button::button1) {
1377                 if (!cur.selection())
1378                         cur.noUpdate();
1379                 else {
1380                         Cursor & bvcur = cur.bv().cursor();
1381                         bvcur.setSelection(true);
1382                 }
1383                 return;
1384         }
1385
1386         cur.undispatched();
1387 }
1388
1389
1390 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1391 {
1392         //lyxerr << "interpret 2: '" << c << "'" << endl;
1393         docstring save_selection;
1394         if (c == '^' || c == '_')
1395                 save_selection = grabAndEraseSelection(cur);
1396
1397         cur.clearTargetX();
1398
1399         // handle macroMode
1400         if (cur.inMacroMode()) {
1401                 docstring name = cur.macroName();
1402
1403                 /// are we currently typing '#1' or '#2' or...?
1404                 if (name == "\\#") {
1405                         cur.backspace();
1406                         int n = c - '0';
1407                         if (n >= 1 && n <= 9)
1408                                 cur.insert(new MathMacroArgument(n));
1409                         return true;
1410                 }
1411
1412                 // do not finish macro for known * commands
1413                 MathWordList const & mwl = mathedWordList();
1414                 bool star_macro = c == '*'
1415                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1416                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1417                 if (isAlphaASCII(c) || star_macro) {
1418                         cur.activeMacro()->setName(name + docstring(1, c));
1419                         return true;
1420                 }
1421
1422                 // handle 'special char' macros
1423                 if (name == "\\") {
1424                         // remove the '\\'
1425                         if (c == '\\') {
1426                                 cur.backspace();
1427                                 if (currentMode() == InsetMath::TEXT_MODE)
1428                                         cur.niceInsert(createInsetMath("textbackslash"));
1429                                 else
1430                                         cur.niceInsert(createInsetMath("backslash"));
1431                         } else if (c == '{') {
1432                                 cur.backspace();
1433                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1434                         } else if (c == '%') {
1435                                 cur.backspace();
1436                                 cur.niceInsert(MathAtom(new InsetMathComment));
1437                         } else if (c == '#') {
1438                                 LASSERT(cur.activeMacro(), /**/);
1439                                 cur.activeMacro()->setName(name + docstring(1, c));
1440                         } else {
1441                                 cur.backspace();
1442                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1443                         }
1444                         return true;
1445                 }
1446
1447                 // One character big delimiters. The others are handled in
1448                 // interpretString().
1449                 latexkeys const * l = in_word_set(name.substr(1));
1450                 if (name[0] == '\\' && l && l->inset == "big") {
1451                         docstring delim;
1452                         switch (c) {
1453                         case '{':
1454                                 delim = from_ascii("\\{");
1455                                 break;
1456                         case '}':
1457                                 delim = from_ascii("\\}");
1458                                 break;
1459                         default:
1460                                 delim = docstring(1, c);
1461                                 break;
1462                         }
1463                         if (InsetMathBig::isBigInsetDelim(delim)) {
1464                                 // name + delim ared a valid InsetMathBig.
1465                                 // We can't use cur.macroModeClose() because
1466                                 // it does not handle delim.
1467                                 InsetMathUnknown * p = cur.activeMacro();
1468                                 p->finalize();
1469                                 --cur.pos();
1470                                 cur.cell().erase(cur.pos());
1471                                 cur.plainInsert(MathAtom(
1472                                         new InsetMathBig(name.substr(1), delim)));
1473                                 return true;
1474                         }
1475                 }
1476
1477                 // leave macro mode and try again if necessary
1478                 cur.macroModeClose();
1479                 if (c == '{')
1480                         cur.niceInsert(MathAtom(new InsetMathBrace));
1481                 else if (c != ' ')
1482                         interpretChar(cur, c);
1483                 return true;
1484         }
1485
1486         // This is annoying as one has to press <space> far too often.
1487         // Disable it.
1488
1489 #if 0
1490                 // leave autocorrect mode if necessary
1491                 if (autocorrect() && c == ' ') {
1492                         autocorrect() = false;
1493                         return true;
1494                 }
1495 #endif
1496
1497         // just clear selection on pressing the space bar
1498         if (cur.selection() && c == ' ') {
1499                 cur.setSelection(false);
1500                 return true;
1501         }
1502
1503         if (c == '\\') {
1504                 //lyxerr << "starting with macro" << endl;
1505                 bool reduced = cap::reduceSelectionToOneCell(cur);
1506                 if (reduced || !cur.selection()) {
1507                         docstring const safe = cap::grabAndEraseSelection(cur);
1508                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1509                 }
1510                 return true;
1511         }
1512
1513         selClearOrDel(cur);
1514
1515         if (c == '\n') {
1516                 if (currentMode() == InsetMath::TEXT_MODE)
1517                         cur.insert(c);
1518                 return true;
1519         }
1520
1521         if (c == ' ') {
1522                 if (currentMode() == InsetMath::TEXT_MODE) {
1523                         // insert spaces in text mode,
1524                         // but suppress direct insertion of two spaces in a row
1525                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1526                         // it is better than nothing...
1527                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1528                                 cur.insert(c);
1529                                 // FIXME: we have to enable full redraw here because of the
1530                                 // visual box corners that define the inset. If we know for
1531                                 // sure that we stay within the same cell we can optimize for
1532                                 // that using:
1533                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1534                         }
1535                         return true;
1536                 }
1537                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1538                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
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::SinglePar | Update::FitCursor);
1544                         return true;
1545                 }
1546
1547                 if (cur.popForward()) {
1548                         // FIXME: we have to enable full redraw here because of the
1549                         // visual box corners that define the inset. If we know for
1550                         // sure that we stay within the same cell we can optimize for
1551                         // that using:
1552                         //cur.updateFlags(Update::FitCursor);
1553                         return true;
1554                 }
1555
1556                 // if we are at the very end, leave the formula
1557                 return cur.pos() != cur.lastpos();
1558         }
1559
1560         // These shouldn't work in text mode:
1561         if (currentMode() != InsetMath::TEXT_MODE) {
1562                 if (c == '_') {
1563                         script(cur, false, save_selection);
1564                         return true;
1565                 }
1566                 if (c == '^') {
1567                         script(cur, true, save_selection);
1568                         return true;
1569                 }
1570                 if (c == '~') {
1571                         cur.niceInsert(createInsetMath("sim"));
1572                         return true;
1573                 }
1574         }
1575
1576         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1577             c == '%' || c == '_' || c == '^') {
1578                 cur.niceInsert(createInsetMath(docstring(1, c)));
1579                 return true;
1580         }
1581
1582
1583         // try auto-correction
1584         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1585         //      return true;
1586
1587         // no special circumstances, so insert the character without any fuss
1588         cur.insert(c);
1589         cur.autocorrect() = true;
1590         return true;
1591 }
1592
1593
1594 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1595 {
1596         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1597         // possible
1598         if (!cur.empty() && cur.pos() > 0 &&
1599             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1600                 if (InsetMathBig::isBigInsetDelim(str)) {
1601                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1602                         if (prev[0] == '\\') {
1603                                 prev = prev.substr(1);
1604                                 latexkeys const * l = in_word_set(prev);
1605                                 if (l && l->inset == "big") {
1606                                         cur.cell()[cur.pos() - 1] =
1607                                                 MathAtom(new InsetMathBig(prev, str));
1608                                         return true;
1609                                 }
1610                         }
1611                 }
1612         }
1613         return false;
1614 }
1615
1616
1617 bool InsetMathNest::script(Cursor & cur, bool up)
1618 {
1619         return script(cur, up, docstring());
1620 }
1621
1622
1623 bool InsetMathNest::script(Cursor & cur, bool up,
1624                 docstring const & save_selection)
1625 {
1626         // Hack to get \^ and \_ working
1627         //lyxerr << "handling script: up: " << up << endl;
1628         if (cur.inMacroMode() && cur.macroName() == "\\") {
1629                 if (up)
1630                         cur.niceInsert(createInsetMath("mathcircumflex"));
1631                 else
1632                         interpretChar(cur, '_');
1633                 return true;
1634         }
1635
1636         cur.macroModeClose();
1637         if (asScriptInset() && cur.idx() == 0) {
1638                 // we are in a nucleus of a script inset, move to _our_ script
1639                 InsetMathScript * inset = asScriptInset();
1640                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1641                 inset->ensure(up);
1642                 cur.idx() = inset->idxOfScript(up);
1643                 cur.pos() = 0;
1644         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1645                 --cur.pos();
1646                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1647                 cur.push(*inset);
1648                 inset->ensure(up);
1649                 cur.idx() = inset->idxOfScript(up);
1650                 cur.pos() = cur.lastpos();
1651         } else {
1652                 // convert the thing to our left to a scriptinset or create a new
1653                 // one if in the very first position of the array
1654                 if (cur.pos() == 0) {
1655                         //lyxerr << "new scriptinset" << endl;
1656                         cur.insert(new InsetMathScript(up));
1657                 } else {
1658                         //lyxerr << "converting prev atom " << endl;
1659                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1660                 }
1661                 --cur.pos();
1662                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1663                 // See comment in MathParser.cpp for special handling of {}-bases
1664
1665                 cur.push(*inset);
1666                 cur.idx() = 1;
1667                 cur.pos() = 0;
1668         }
1669         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1670         cur.niceInsert(save_selection);
1671         cur.resetAnchor();
1672         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1673         return true;
1674 }
1675
1676
1677 bool InsetMathNest::completionSupported(Cursor const & cur) const
1678 {
1679         return cur.inMacroMode();
1680 }
1681
1682
1683 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1684 {
1685         return cur.inMacroMode();
1686 }
1687
1688
1689 bool InsetMathNest::automaticInlineCompletion() const
1690 {
1691         return lyxrc.completion_inline_math;
1692 }
1693
1694
1695 bool InsetMathNest::automaticPopupCompletion() const
1696 {
1697         return lyxrc.completion_popup_math;
1698 }
1699
1700
1701 CompletionList const *
1702 InsetMathNest::createCompletionList(Cursor const & cur) const
1703 {
1704         if (!cur.inMacroMode())
1705                 return 0;
1706         
1707         return new MathCompletionList(cur);
1708 }
1709
1710
1711 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1712 {
1713         if (!cur.inMacroMode())
1714                 return docstring();
1715         
1716         return cur.activeMacro()->name();
1717 }
1718
1719
1720 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1721                                      bool finished)
1722 {
1723         if (!cur.inMacroMode())
1724                 return false;
1725
1726         // append completion to active macro
1727         InsetMathUnknown * inset = cur.activeMacro();
1728         inset->setName(inset->name() + s);
1729
1730         // finish macro
1731         if (finished) {
1732 #if 0
1733                 // FIXME: this creates duplicates in the completion popup
1734                 // which looks ugly. Moreover the changes the list lengths
1735                 // which seems to
1736                 confuse the popup as well.
1737                 MathCompletionList::addToFavorites(inset->name());
1738 #endif
1739                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1740         }
1741
1742         return true;
1743 }
1744
1745
1746 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1747                                         Dimension & dim) const
1748 {
1749         Inset const * inset = cur.activeMacro();
1750         if (!inset)
1751                 return;
1752
1753         // get inset dimensions
1754         dim = cur.bv().coordCache().insets().dim(inset);
1755         // FIXME: these 3 are no accurate, but should depend on the font.
1756         // Now the popup jumps down if you enter a char with descent > 0.
1757         dim.des += 3;
1758         dim.asc += 3;
1759
1760         // and position
1761         Point xy
1762         = cur.bv().coordCache().insets().xy(inset);
1763         x = xy.x_;
1764         y = xy.y_;
1765 }
1766
1767
1768 bool InsetMathNest::cursorMathForward(Cursor & cur)
1769 {
1770         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1771                 cur.pushBackward(*cur.nextAtom().nucleus());
1772                 cur.inset().idxFirst(cur);
1773                 return true;
1774         } 
1775         if (cur.posForward() || idxForward(cur))
1776                 return true;
1777         // try to pop forwards --- but don't pop out of math! leave that to
1778         // the FINISH lfuns
1779         int s = cur.depth() - 2;
1780         if (s >= 0 && cur[s].inset().asInsetMath())
1781                 return cur.popForward();
1782         return false;
1783 }
1784
1785
1786 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1787 {
1788         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1789                 cur.posBackward();
1790                 cur.push(*cur.nextAtom().nucleus());
1791                 cur.inset().idxLast(cur);
1792                 return true;
1793         } 
1794         if (cur.posBackward() || idxBackward(cur))
1795                 return true;
1796         // try to pop backwards --- but don't pop out of math! leave that to 
1797         // the FINISH lfuns
1798         int s = cur.depth() - 2;
1799         if (s >= 0 && cur[s].inset().asInsetMath())
1800                 return cur.popBackward();
1801         return false;
1802 }
1803
1804
1805 ////////////////////////////////////////////////////////////////////
1806
1807 MathCompletionList::MathCompletionList(Cursor const & cur)
1808 {
1809         // fill it with macros from the buffer
1810         MacroNameSet macros;
1811         cur.buffer().listMacroNames(macros);
1812         MacroNameSet::const_iterator it;
1813         for (it = macros.begin(); it != macros.end(); ++it) {
1814                 if (cur.buffer().getMacro(*it, cur, false))
1815                         locals.push_back("\\" + *it);
1816         }
1817         sort(locals.begin(), locals.end());
1818
1819         if (globals.size() > 0)
1820                 return;
1821
1822         // fill in global macros
1823         macros.clear();
1824         MacroTable::globalMacros().getMacroNames(macros);
1825         //lyxerr << "Globals completion macros: ";
1826         for (it = macros.begin(); it != macros.end(); ++it) {
1827                 //lyxerr << "\\" + *it << " ";
1828                 globals.push_back("\\" + *it);
1829         }
1830         //lyxerr << std::endl;
1831
1832         // fill in global commands
1833         globals.push_back(from_ascii("\\boxed"));
1834         globals.push_back(from_ascii("\\fbox"));
1835         globals.push_back(from_ascii("\\framebox"));
1836         globals.push_back(from_ascii("\\makebox"));
1837         globals.push_back(from_ascii("\\kern"));
1838         globals.push_back(from_ascii("\\xrightarrow"));
1839         globals.push_back(from_ascii("\\xleftarrow"));
1840         globals.push_back(from_ascii("\\split"));
1841         globals.push_back(from_ascii("\\gathered"));
1842         globals.push_back(from_ascii("\\aligned"));
1843         globals.push_back(from_ascii("\\alignedat"));
1844         globals.push_back(from_ascii("\\cases"));
1845         globals.push_back(from_ascii("\\substack"));
1846         globals.push_back(from_ascii("\\xymatrix"));
1847         globals.push_back(from_ascii("\\subarray"));
1848         globals.push_back(from_ascii("\\array"));
1849         globals.push_back(from_ascii("\\sqrt"));
1850         globals.push_back(from_ascii("\\root"));
1851         globals.push_back(from_ascii("\\tabular"));
1852         globals.push_back(from_ascii("\\stackrel"));
1853         globals.push_back(from_ascii("\\binom"));
1854         globals.push_back(from_ascii("\\choose"));
1855         globals.push_back(from_ascii("\\brace"));
1856         globals.push_back(from_ascii("\\brack"));
1857         globals.push_back(from_ascii("\\frac"));
1858         globals.push_back(from_ascii("\\over"));
1859         globals.push_back(from_ascii("\\nicefrac"));
1860         globals.push_back(from_ascii("\\unitfrac"));
1861         globals.push_back(from_ascii("\\unitfracthree"));
1862         globals.push_back(from_ascii("\\unitone"));
1863         globals.push_back(from_ascii("\\unittwo"));
1864         globals.push_back(from_ascii("\\infer"));
1865         globals.push_back(from_ascii("\\atop"));
1866         globals.push_back(from_ascii("\\lefteqn"));
1867         globals.push_back(from_ascii("\\boldsymbol"));
1868         globals.push_back(from_ascii("\\bm"));
1869         globals.push_back(from_ascii("\\color"));
1870         globals.push_back(from_ascii("\\normalcolor"));
1871         globals.push_back(from_ascii("\\textcolor"));
1872         globals.push_back(from_ascii("\\dfrac"));
1873         globals.push_back(from_ascii("\\tfrac"));
1874         globals.push_back(from_ascii("\\dbinom"));
1875         globals.push_back(from_ascii("\\tbinom"));
1876         globals.push_back(from_ascii("\\hphantom"));
1877         globals.push_back(from_ascii("\\phantom"));
1878         globals.push_back(from_ascii("\\vphantom"));
1879         MathWordList const & words = mathedWordList();
1880         MathWordList::const_iterator it2;
1881         //lyxerr << "Globals completion commands: ";
1882         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1883                 globals.push_back("\\" + (*it2).first);
1884                 //lyxerr << "\\" + (*it2).first << " ";
1885         }
1886         //lyxerr << std::endl;
1887         sort(globals.begin(), globals.end());
1888 }
1889
1890
1891 MathCompletionList::~MathCompletionList()
1892 {
1893 }
1894
1895
1896 size_type MathCompletionList::size() const
1897 {
1898         return locals.size() + globals.size();
1899 }
1900
1901
1902 docstring const & MathCompletionList::data(size_t idx) const
1903 {
1904         size_t lsize = locals.size();
1905         if (idx >= lsize)
1906                 return globals[idx - lsize];
1907         else
1908                 return locals[idx];
1909 }
1910
1911
1912 std::string MathCompletionList::icon(size_t idx) const 
1913 {
1914         // get the latex command
1915         docstring cmd;
1916         size_t lsize = locals.size();
1917         if (idx >= lsize)
1918                 cmd = globals[idx - lsize];
1919         else
1920                 cmd = locals[idx];
1921         
1922         // get the icon resource name by stripping the backslash
1923         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1924 }
1925
1926 std::vector<docstring> MathCompletionList::globals;
1927
1928 } // namespace lyx