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