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