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