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