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