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