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