]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
When selecting math with the mouse, selection happens in the middle (#9748)
[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         bool do_selection = cmd.button() == mouse_button::button1
1585                 && cmd.modifier() == ShiftModifier;
1586         bv.mouseSetCursor(cur, do_selection);
1587         if (cmd.button() == mouse_button::button1) {
1588                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1589                 // Update the cursor update flags as needed:
1590                 //
1591                 // Update::Decoration: tells to update the decoration
1592                 //                     (visual box corners that define
1593                 //                     the inset)/
1594                 // Update::FitCursor: adjust the screen to the cursor
1595                 //                    position if needed
1596                 // cur.result().update(): don't overwrite previously set flags.
1597                 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1598                                 | cur.result().screenUpdate());
1599         } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1600                 if (cap::selection()) {
1601                         // See comment in Text::dispatch why we do this
1602                         cap::copySelectionToStack();
1603                         cmd = FuncRequest(LFUN_PASTE, "0");
1604                         doDispatch(bv.cursor(), cmd);
1605                 } else {
1606                         MathData ar;
1607                         asArray(theSelection().get(), ar);
1608                         bv.cursor().insert(ar);
1609                 }
1610         }
1611 }
1612
1613
1614 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1615 {
1616         // only select with button 1
1617         if (cmd.button() != mouse_button::button1)
1618                 return;
1619
1620         Cursor & bvcur = cur.bv().cursor();
1621
1622         // ignore motions deeper nested than the real anchor
1623         if (!bvcur.realAnchor().hasPart(cur)) {
1624                 cur.undispatched();
1625                 return;
1626         }
1627
1628         // set cursor after the inset if x is nearer to that position (bug 9748)
1629         if (Inset const * inset = cur.nextInset()) {
1630                 CoordCache::Insets const & insetCache =
1631                         cur.bv().coordCache().getInsets();
1632                 int const wid = insetCache.dim(inset).wid;
1633                 Point p = insetCache.xy(inset);
1634                 if (cmd.x() > p.x_ + (wid + 1) / 2)
1635                         cur.posForward();
1636         }
1637
1638         CursorSlice old = bvcur.top();
1639
1640         // We continue with our existing selection or start a new one, so don't
1641         // reset the anchor.
1642         bvcur.setCursor(cur);
1643         // Did we actually move?
1644         if (cur.top() == old)
1645                 // We didn't move one iota, so no need to change selection status
1646                 // or update the screen.
1647                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1648         else
1649                 bvcur.setSelection();
1650 }
1651
1652
1653 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1654 {
1655         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1656
1657         if (cmd.button() == mouse_button::button1) {
1658                 if (!cur.selection())
1659                         cur.noScreenUpdate();
1660                 else {
1661                         Cursor & bvcur = cur.bv().cursor();
1662                         bvcur.selection(true);
1663                 }
1664                 return;
1665         }
1666
1667         cur.undispatched();
1668 }
1669
1670
1671 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1672 {
1673         //lyxerr << "interpret 2: '" << c << "'" << endl;
1674         docstring save_selection;
1675         if (c == '^' || c == '_')
1676                 save_selection = grabAndEraseSelection(cur);
1677
1678         cur.clearTargetX();
1679         Buffer * buf = cur.buffer();
1680
1681         // handle macroMode
1682         if (cur.inMacroMode()) {
1683                 docstring name = cur.macroName();
1684
1685                 /// are we currently typing '#1' or '#2' or...?
1686                 if (name == "\\#") {
1687                         cur.backspace();
1688                         int n = c - '0';
1689                         if (n >= 1 && n <= 9)
1690                                 cur.insert(new MathMacroArgument(n));
1691                         return true;
1692                 }
1693
1694                 // do not finish macro for known * commands
1695                 bool star_macro = c == '*'
1696                         && (in_word_set(name.substr(1) + '*')
1697                             || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1698                 if (isAlphaASCII(c) || star_macro) {
1699                         cur.activeMacro()->setName(name + docstring(1, c));
1700                         return true;
1701                 }
1702
1703                 // handle 'special char' macros
1704                 if (name == "\\") {
1705                         // remove the '\\'
1706                         if (c == '\\') {
1707                                 cur.backspace();
1708                                 if (currentMode() != InsetMath::MATH_MODE)
1709                                         cur.niceInsert(createInsetMath("textbackslash", buf));
1710                                 else
1711                                         cur.niceInsert(createInsetMath("backslash", buf));
1712                         } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1713                                 cur.backspace();
1714                                 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1715                         } else if (c == '{' || c == '%') {
1716                                 //using the saved selection as argument
1717                                 InsetMathUnknown * p = cur.activeMacro();
1718                                 p->finalize();
1719                                 MathData sel(cur.buffer());
1720                                 asArray(p->selection(), sel);
1721                                 cur.backspace();
1722                                 if (c == '{')
1723                                         cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1724                                 else
1725                                         cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1726                         } else if (c == '#') {
1727                                 LASSERT(cur.activeMacro(), return false);
1728                                 cur.activeMacro()->setName(name + docstring(1, c));
1729                         } else {
1730                                 cur.backspace();
1731                                 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1732                         }
1733                         return true;
1734                 }
1735
1736                 // One character big delimiters. The others are handled in
1737                 // interpretString().
1738                 latexkeys const * l = in_word_set(name.substr(1));
1739                 if (name[0] == '\\' && l && l->inset == "big") {
1740                         docstring delim;
1741                         switch (c) {
1742                         case '{':
1743                                 delim = from_ascii("\\{");
1744                                 break;
1745                         case '}':
1746                                 delim = from_ascii("\\}");
1747                                 break;
1748                         default:
1749                                 delim = docstring(1, c);
1750                                 break;
1751                         }
1752                         if (InsetMathBig::isBigInsetDelim(delim)) {
1753                                 // name + delim ared a valid InsetMathBig.
1754                                 // We can't use cur.macroModeClose() because
1755                                 // it does not handle delim.
1756                                 InsetMathUnknown * p = cur.activeMacro();
1757                                 p->finalize();
1758                                 --cur.pos();
1759                                 cur.cell().erase(cur.pos());
1760                                 cur.plainInsert(MathAtom(
1761                                         new InsetMathBig(name.substr(1), delim)));
1762                                 return true;
1763                         }
1764                 } else if (name == "\\smash" && c == '[') {
1765                         // We can't use cur.macroModeClose() because
1766                         // it would create an InsetMathPhantom
1767                         InsetMathUnknown * p = cur.activeMacro();
1768                         p->finalize();
1769                         interpretChar(cur, c);
1770                         return true;
1771                 }
1772
1773                 // leave macro mode and try again if necessary
1774                 if (cur.macroModeClose()) {
1775                         MathAtom const atom = cur.prevAtom();
1776                         if (atom->asNestInset() && atom->isActive()) {
1777                                 cur.posBackward();
1778                                 cur.pushBackward(*cur.nextInset());
1779                         }
1780                 }
1781                 if (c == '{')
1782                         cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1783                 else if (c != ' ')
1784                         interpretChar(cur, c);
1785                 return true;
1786         }
1787
1788
1789         // leave autocorrect mode if necessary
1790         if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1791                 cur.autocorrect() = false;
1792                 cur.message(_("Autocorrect Off ('!' to enter)"));
1793                 return true;
1794         }
1795         if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1796                 cur.autocorrect() = true;
1797                 cur.message(_("Autocorrect On (<space> to exit)"));
1798                 return true;
1799         }
1800
1801         // just clear selection on pressing the space bar
1802         if (cur.selection() && c == ' ') {
1803                 cur.selection(false);
1804                 return true;
1805         }
1806
1807         if (c == '\\') {
1808                 //lyxerr << "starting with macro" << endl;
1809                 bool reduced = cap::reduceSelectionToOneCell(cur);
1810                 if (reduced || !cur.selection()) {
1811                         cur.recordUndoInset();
1812                         docstring const safe = cap::grabAndEraseSelection(cur);
1813                         if (!cur.inRegexped())
1814                                 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1815                         else
1816                                 cur.niceInsert(createInsetMath("backslash", buf));
1817                 }
1818                 return true;
1819         }
1820
1821         selClearOrDel(cur);
1822
1823         if (c == '\n') {
1824                 if (currentMode() != InsetMath::MATH_MODE)
1825                         cur.insert(c);
1826                 return true;
1827         }
1828
1829         if (c == ' ') {
1830                 if (currentMode() != InsetMath::MATH_MODE) {
1831                         // insert spaces in text or undecided mode,
1832                         // but suppress direct insertion of two spaces in a row
1833                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1834                         // it is better than nothing...
1835                         if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1836                                 cur.insert(c);
1837                                 // FIXME: we have to enable full redraw here because of the
1838                                 // visual box corners that define the inset. If we know for
1839                                 // sure that we stay within the same cell we can optimize for
1840                                 // that using:
1841                                 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1842                         }
1843                         return true;
1844                 }
1845                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1846                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1847                         // FIXME: we have to enable full redraw here because of the
1848                         // visual box corners that define the inset. If we know for
1849                         // sure that we stay within the same cell we can optimize for
1850                         // that using:
1851                         //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1852                         return true;
1853                 }
1854
1855                 if (cur.popForward()) {
1856                         // FIXME: we have to enable full redraw here because of the
1857                         // visual box corners that define the inset. If we know for
1858                         // sure that we stay within the same cell we can optimize for
1859                         // that using:
1860                         //cur.screenUpdateFlags(Update::FitCursor);
1861                         return true;
1862                 }
1863
1864                 // if we are at the very end, leave the formula
1865                 return cur.pos() != cur.lastpos();
1866         }
1867
1868         // These should be treated differently when not in text mode:
1869         if (cur.inRegexped()) {
1870                 switch (c) {
1871                 case '^':
1872                         cur.niceInsert(createInsetMath("mathcircumflex", buf));
1873                         break;
1874                 case '{':
1875                 case '}':
1876                 case '#':
1877                 case '%':
1878                 case '_':
1879                         cur.niceInsert(createInsetMath(docstring(1, c), buf));
1880                         break;
1881                 case '~':
1882                         cur.niceInsert(createInsetMath("sim", buf));
1883                         break;
1884                 default:
1885                         cur.insert(c);
1886                 }
1887                 return true;
1888         } else if (currentMode() != InsetMath::TEXT_MODE) {
1889                 if (c == '_') {
1890                         script(cur, false, save_selection);
1891                         return true;
1892                 }
1893                 if (c == '^') {
1894                         script(cur, true, save_selection);
1895                         return true;
1896                 }
1897                 if (c == '~') {
1898                         cur.niceInsert(createInsetMath("sim", buf));
1899                         return true;
1900                 }
1901                 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1902                         MathAtom at = createInsetMath("text", buf);
1903                         at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1904                         cur.niceInsert(at);
1905                         cur.posForward();
1906                         return true;
1907                 }
1908         } else {
1909                 if (c == '^') {
1910                         cur.niceInsert(createInsetMath("textasciicircum", buf));
1911                         return true;
1912                 }
1913                 if (c == '~') {
1914                         cur.niceInsert(createInsetMath("textasciitilde", buf));
1915                         return true;
1916                 }
1917         }
1918
1919         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1920             c == '%' || c == '_') {
1921                 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1922                 return true;
1923         }
1924
1925
1926         // try auto-correction
1927         if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1928                   && math_autocorrect(cur.prevAtom(), c))
1929                 return true;
1930
1931         // no special circumstances, so insert the character without any fuss
1932         cur.insert(c);
1933         if (lyxrc.autocorrection_math) {
1934                 if (!cur.autocorrect())
1935                         cur.message(_("Autocorrect Off ('!' to enter)"));
1936                 else
1937                         cur.message(_("Autocorrect On (<space> to exit)"));
1938         }
1939         return true;
1940 }
1941
1942
1943 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1944 {
1945         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1946         // possible
1947         if (!cur.empty() && cur.pos() > 0 &&
1948             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1949                 if (InsetMathBig::isBigInsetDelim(str)) {
1950                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1951                         if (prev[0] == '\\') {
1952                                 prev = prev.substr(1);
1953                                 latexkeys const * l = in_word_set(prev);
1954                                 if (l && l->inset == "big") {
1955                                         cur.cell()[cur.pos() - 1] =
1956                                                 MathAtom(new InsetMathBig(prev, str));
1957                                         return true;
1958                                 }
1959                         }
1960                 }
1961         }
1962         return false;
1963 }
1964
1965
1966 bool InsetMathNest::script(Cursor & cur, bool up)
1967 {
1968         return script(cur, up, docstring());
1969 }
1970
1971
1972 bool InsetMathNest::script(Cursor & cur, bool up,
1973                 docstring const & save_selection)
1974 {
1975         // Hack to get \^ and \_ working
1976         //lyxerr << "handling script: up: " << up << endl;
1977         if (cur.inMacroMode() && cur.macroName() == "\\") {
1978                 if (up)
1979                         cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1980                 else
1981                         interpretChar(cur, '_');
1982                 return true;
1983         }
1984
1985         cur.macroModeClose();
1986         if (asScriptInset() && cur.idx() == 0) {
1987                 // we are in a nucleus of a script inset, move to _our_ script
1988                 InsetMathScript * inset = asScriptInset();
1989                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1990                 inset->ensure(up);
1991                 cur.idx() = inset->idxOfScript(up);
1992                 cur.pos() = 0;
1993         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1994                 --cur.pos();
1995                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1996                 cur.push(*inset);
1997                 inset->ensure(up);
1998                 cur.idx() = inset->idxOfScript(up);
1999                 cur.pos() = cur.lastpos();
2000         } else {
2001                 // convert the thing to our left to a scriptinset or create a new
2002                 // one if in the very first position of the array
2003                 if (cur.pos() == 0) {
2004                         //lyxerr << "new scriptinset" << endl;
2005                         cur.insert(new InsetMathScript(buffer_, up));
2006                 } else {
2007                         //lyxerr << "converting prev atom " << endl;
2008                         cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
2009                 }
2010                 --cur.pos();
2011                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2012                 // See comment in MathParser.cpp for special handling of {}-bases
2013
2014                 cur.push(*inset);
2015                 cur.idx() = 1;
2016                 cur.pos() = 0;
2017         }
2018         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2019         cur.niceInsert(save_selection);
2020         cur.resetAnchor();
2021         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2022         return true;
2023 }
2024
2025
2026 bool InsetMathNest::completionSupported(Cursor const & cur) const
2027 {
2028         return cur.inMacroMode();
2029 }
2030
2031
2032 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2033 {
2034         return cur.inMacroMode();
2035 }
2036
2037
2038 bool InsetMathNest::automaticInlineCompletion() const
2039 {
2040         return lyxrc.completion_inline_math;
2041 }
2042
2043
2044 bool InsetMathNest::automaticPopupCompletion() const
2045 {
2046         return lyxrc.completion_popup_math;
2047 }
2048
2049
2050 CompletionList const *
2051 InsetMathNest::createCompletionList(Cursor const & cur) const
2052 {
2053         if (!cur.inMacroMode())
2054                 return 0;
2055
2056         return new MathCompletionList(cur);
2057 }
2058
2059
2060 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2061 {
2062         if (!cur.inMacroMode())
2063                 return docstring();
2064
2065         return cur.activeMacro()->name();
2066 }
2067
2068
2069 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2070                                      bool finished)
2071 {
2072         if (!cur.inMacroMode())
2073                 return false;
2074
2075         // append completion to active macro
2076         InsetMathUnknown * inset = cur.activeMacro();
2077         inset->setName(inset->name() + s);
2078
2079         // finish macro
2080         if (finished) {
2081 #if 0
2082                 // FIXME: this creates duplicates in the completion popup
2083                 // which looks ugly. Moreover the changes the list lengths
2084                 // which seems to
2085                 confuse the popup as well.
2086                 MathCompletionList::addToFavorites(inset->name());
2087 #endif
2088                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2089         }
2090
2091         return true;
2092 }
2093
2094
2095 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2096                                         Dimension & dim) const
2097 {
2098         Inset const * inset = cur.activeMacro();
2099         if (!inset)
2100                 return;
2101
2102         // get inset dimensions
2103         dim = cur.bv().coordCache().insets().dim(inset);
2104         // FIXME: these 3 are no accurate, but should depend on the font.
2105         // Now the popup jumps down if you enter a char with descent > 0.
2106         dim.des += 3;
2107         dim.asc += 3;
2108
2109         // and position
2110         Point xy = cur.bv().coordCache().insets().xy(inset);
2111         x = xy.x_;
2112         y = xy.y_;
2113 }
2114
2115
2116 ////////////////////////////////////////////////////////////////////
2117
2118 MathCompletionList::MathCompletionList(Cursor const & cur)
2119 {
2120         // fill it with macros from the buffer
2121         MacroNameSet macros;
2122         cur.buffer()->listMacroNames(macros);
2123         MacroNameSet::const_iterator it;
2124         for (it = macros.begin(); it != macros.end(); ++it) {
2125                 if (cur.buffer()->getMacro(*it, cur, false))
2126                         locals.push_back("\\" + *it);
2127         }
2128         sort(locals.begin(), locals.end());
2129
2130         if (!globals.empty())
2131                 return;
2132
2133         // fill in global macros
2134         macros.clear();
2135         MacroTable::globalMacros().getMacroNames(macros, false);
2136         //lyxerr << "Globals completion macros: ";
2137         for (it = macros.begin(); it != macros.end(); ++it) {
2138                 //lyxerr << "\\" + *it << " ";
2139                 globals.push_back("\\" + *it);
2140         }
2141         //lyxerr << std::endl;
2142
2143         // fill in global commands
2144         globals.push_back(from_ascii("\\boxed"));
2145         globals.push_back(from_ascii("\\fbox"));
2146         globals.push_back(from_ascii("\\framebox"));
2147         globals.push_back(from_ascii("\\makebox"));
2148         globals.push_back(from_ascii("\\kern"));
2149         globals.push_back(from_ascii("\\xhookrightarrow"));
2150         globals.push_back(from_ascii("\\xhookleftarrow"));
2151         globals.push_back(from_ascii("\\xrightarrow"));
2152         globals.push_back(from_ascii("\\xRightarrow"));
2153         globals.push_back(from_ascii("\\xrightharpoondown"));
2154         globals.push_back(from_ascii("\\xrightharpoonup"));
2155         globals.push_back(from_ascii("\\xrightleftharpoons"));
2156         globals.push_back(from_ascii("\\xleftarrow"));
2157         globals.push_back(from_ascii("\\xLeftarrow"));
2158         globals.push_back(from_ascii("\\xleftharpoondown"));
2159         globals.push_back(from_ascii("\\xleftharpoonup"));
2160         globals.push_back(from_ascii("\\xleftrightarrow"));
2161         globals.push_back(from_ascii("\\xLeftrightarrow"));
2162         globals.push_back(from_ascii("\\xleftrightharpoons"));
2163         globals.push_back(from_ascii("\\xmapsto"));
2164         globals.push_back(from_ascii("\\split"));
2165         globals.push_back(from_ascii("\\gathered"));
2166         globals.push_back(from_ascii("\\aligned"));
2167         globals.push_back(from_ascii("\\alignedat"));
2168         globals.push_back(from_ascii("\\cases"));
2169         globals.push_back(from_ascii("\\substack"));
2170         globals.push_back(from_ascii("\\xymatrix"));
2171         globals.push_back(from_ascii("\\Diagram"));
2172         globals.push_back(from_ascii("\\subarray"));
2173         globals.push_back(from_ascii("\\array"));
2174         globals.push_back(from_ascii("\\sqrt"));
2175         globals.push_back(from_ascii("\\root"));
2176         globals.push_back(from_ascii("\\tabular"));
2177         globals.push_back(from_ascii("\\sideset"));
2178         globals.push_back(from_ascii("\\stackrel"));
2179         globals.push_back(from_ascii("\\stackrelthree"));
2180         globals.push_back(from_ascii("\\binom"));
2181         globals.push_back(from_ascii("\\choose"));
2182         globals.push_back(from_ascii("\\brace"));
2183         globals.push_back(from_ascii("\\brack"));
2184         globals.push_back(from_ascii("\\frac"));
2185         globals.push_back(from_ascii("\\over"));
2186         globals.push_back(from_ascii("\\nicefrac"));
2187         globals.push_back(from_ascii("\\unitfrac"));
2188         globals.push_back(from_ascii("\\unitfracthree"));
2189         globals.push_back(from_ascii("\\unitone"));
2190         globals.push_back(from_ascii("\\unittwo"));
2191         globals.push_back(from_ascii("\\infer"));
2192         globals.push_back(from_ascii("\\atop"));
2193         globals.push_back(from_ascii("\\lefteqn"));
2194         globals.push_back(from_ascii("\\boldsymbol"));
2195         globals.push_back(from_ascii("\\bm"));
2196         globals.push_back(from_ascii("\\color"));
2197         globals.push_back(from_ascii("\\normalcolor"));
2198         globals.push_back(from_ascii("\\textcolor"));
2199         globals.push_back(from_ascii("\\cfrac"));
2200         globals.push_back(from_ascii("\\cfracleft"));
2201         globals.push_back(from_ascii("\\cfracright"));
2202         globals.push_back(from_ascii("\\dfrac"));
2203         globals.push_back(from_ascii("\\tfrac"));
2204         globals.push_back(from_ascii("\\dbinom"));
2205         globals.push_back(from_ascii("\\tbinom"));
2206         globals.push_back(from_ascii("\\hphantom"));
2207         globals.push_back(from_ascii("\\phantom"));
2208         globals.push_back(from_ascii("\\vphantom"));
2209         globals.push_back(from_ascii("\\cancel"));
2210         globals.push_back(from_ascii("\\bcancel"));
2211         globals.push_back(from_ascii("\\xcancel"));
2212         globals.push_back(from_ascii("\\cancelto"));
2213         globals.push_back(from_ascii("\\smash"));
2214         globals.push_back(from_ascii("\\mathclap"));
2215         globals.push_back(from_ascii("\\mathllap"));
2216         globals.push_back(from_ascii("\\mathrlap"));
2217         globals.push_back(from_ascii("\\ensuremath"));
2218         MathWordList const & words = mathedWordList();
2219         MathWordList::const_iterator it2;
2220         //lyxerr << "Globals completion commands: ";
2221         for (it2 = words.begin(); it2 != words.end(); ++it2) {
2222                 if (it2->second.inset != "macro" && !it2->second.hidden) {
2223                         // macros are already read from MacroTable::globalMacros()
2224                         globals.push_back('\\' + it2->first);
2225                         //lyxerr << '\\' + it2->first << ' ';
2226                 }
2227         }
2228         //lyxerr << std::endl;
2229         sort(globals.begin(), globals.end());
2230 }
2231
2232
2233 MathCompletionList::~MathCompletionList()
2234 {
2235 }
2236
2237
2238 size_type MathCompletionList::size() const
2239 {
2240         return locals.size() + globals.size();
2241 }
2242
2243
2244 docstring const & MathCompletionList::data(size_t idx) const
2245 {
2246         size_t lsize = locals.size();
2247         if (idx >= lsize)
2248                 return globals[idx - lsize];
2249         else
2250                 return locals[idx];
2251 }
2252
2253
2254 std::string MathCompletionList::icon(size_t idx) const
2255 {
2256         // get the latex command
2257         docstring cmd;
2258         size_t lsize = locals.size();
2259         if (idx >= lsize)
2260                 cmd = globals[idx - lsize];
2261         else
2262                 cmd = locals[idx];
2263
2264         // get the icon resource name by stripping the backslash
2265         docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2266         if (icon_name.empty())
2267                 return std::string();
2268         return "images/math/" + to_utf8(icon_name);
2269 }
2270
2271 std::vector<docstring> MathCompletionList::globals;
2272
2273 } // namespace lyx