]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
21d5af1a718c85955d64bd878649304885b62fe4
[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 "LyXFunc.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::updateLabels(ParIterator const & it, UpdateType utype)
177 {
178         for (idx_type i = 0, n = nargs(); i != n; ++i)
179                 cell(i).updateLabels(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/updateLabels calls
568                 cur.buffer()->updateLabels();
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/updateLabels calls
581                 cur.buffer()->updateLabels();
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/updateLabels calls
992                 cur.buffer()->updateLabels();
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                 } else if (name == "mathspace") {
1195                         InsetMathSpace tmp;
1196                         data = tmp.createDialogStr();
1197                 }
1198                 cur.bv().showDialog(to_utf8(name), data);
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/updateLabels calls
1208                         cur.buffer()->updateLabels();
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_TABULAR_FEATURE:
1270                 flag.setEnabled(false);
1271                 break;
1272 #if 0
1273         case LFUN_TABULAR_FEATURE:
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.anchor_.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
1892         = cur.bv().coordCache().insets().xy(inset);
1893         x = xy.x_;
1894         y = xy.y_;
1895 }
1896
1897
1898 bool InsetMathNest::cursorMathForward(Cursor & cur)
1899 {
1900         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1901                 cur.pushBackward(*cur.nextAtom().nucleus());
1902                 cur.inset().idxFirst(cur);
1903                 return true;
1904         }
1905         if (cur.posForward() || idxForward(cur))
1906                 return true;
1907         // try to pop forwards --- but don't pop out of math! leave that to
1908         // the FINISH lfuns
1909         int s = cur.depth() - 2;
1910         if (s >= 0 && cur[s].inset().asInsetMath())
1911                 return cur.popForward();
1912         return false;
1913 }
1914
1915
1916 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1917 {
1918         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1919                 cur.posBackward();
1920                 cur.push(*cur.nextAtom().nucleus());
1921                 cur.inset().idxLast(cur);
1922                 return true;
1923         }
1924         if (cur.posBackward() || idxBackward(cur))
1925                 return true;
1926         // try to pop backwards --- but don't pop out of math! leave that to
1927         // the FINISH lfuns
1928         int s = cur.depth() - 2;
1929         if (s >= 0 && cur[s].inset().asInsetMath())
1930                 return cur.popBackward();
1931         return false;
1932 }
1933
1934
1935 ////////////////////////////////////////////////////////////////////
1936
1937 MathCompletionList::MathCompletionList(Cursor const & cur)
1938 {
1939         // fill it with macros from the buffer
1940         MacroNameSet macros;
1941         cur.buffer()->listMacroNames(macros);
1942         MacroNameSet::const_iterator it;
1943         for (it = macros.begin(); it != macros.end(); ++it) {
1944                 if (cur.buffer()->getMacro(*it, cur, false))
1945                         locals.push_back("\\" + *it);
1946         }
1947         sort(locals.begin(), locals.end());
1948
1949         if (globals.size() > 0)
1950                 return;
1951
1952         // fill in global macros
1953         macros.clear();
1954         MacroTable::globalMacros().getMacroNames(macros);
1955         //lyxerr << "Globals completion macros: ";
1956         for (it = macros.begin(); it != macros.end(); ++it) {
1957                 //lyxerr << "\\" + *it << " ";
1958                 globals.push_back("\\" + *it);
1959         }
1960         //lyxerr << std::endl;
1961
1962         // fill in global commands
1963         globals.push_back(from_ascii("\\boxed"));
1964         globals.push_back(from_ascii("\\fbox"));
1965         globals.push_back(from_ascii("\\framebox"));
1966         globals.push_back(from_ascii("\\makebox"));
1967         globals.push_back(from_ascii("\\kern"));
1968         globals.push_back(from_ascii("\\xrightarrow"));
1969         globals.push_back(from_ascii("\\xleftarrow"));
1970         globals.push_back(from_ascii("\\split"));
1971         globals.push_back(from_ascii("\\gathered"));
1972         globals.push_back(from_ascii("\\aligned"));
1973         globals.push_back(from_ascii("\\alignedat"));
1974         globals.push_back(from_ascii("\\cases"));
1975         globals.push_back(from_ascii("\\substack"));
1976         globals.push_back(from_ascii("\\xymatrix"));
1977         globals.push_back(from_ascii("\\subarray"));
1978         globals.push_back(from_ascii("\\array"));
1979         globals.push_back(from_ascii("\\sqrt"));
1980         globals.push_back(from_ascii("\\root"));
1981         globals.push_back(from_ascii("\\tabular"));
1982         globals.push_back(from_ascii("\\stackrel"));
1983         globals.push_back(from_ascii("\\binom"));
1984         globals.push_back(from_ascii("\\choose"));
1985         globals.push_back(from_ascii("\\brace"));
1986         globals.push_back(from_ascii("\\brack"));
1987         globals.push_back(from_ascii("\\frac"));
1988         globals.push_back(from_ascii("\\over"));
1989         globals.push_back(from_ascii("\\nicefrac"));
1990         globals.push_back(from_ascii("\\unitfrac"));
1991         globals.push_back(from_ascii("\\unitfracthree"));
1992         globals.push_back(from_ascii("\\unitone"));
1993         globals.push_back(from_ascii("\\unittwo"));
1994         globals.push_back(from_ascii("\\infer"));
1995         globals.push_back(from_ascii("\\atop"));
1996         globals.push_back(from_ascii("\\lefteqn"));
1997         globals.push_back(from_ascii("\\boldsymbol"));
1998         globals.push_back(from_ascii("\\bm"));
1999         globals.push_back(from_ascii("\\color"));
2000         globals.push_back(from_ascii("\\normalcolor"));
2001         globals.push_back(from_ascii("\\textcolor"));
2002         globals.push_back(from_ascii("\\cfrac"));
2003         globals.push_back(from_ascii("\\cfracleft"));
2004         globals.push_back(from_ascii("\\cfracright"));
2005         globals.push_back(from_ascii("\\dfrac"));
2006         globals.push_back(from_ascii("\\tfrac"));
2007         globals.push_back(from_ascii("\\dbinom"));
2008         globals.push_back(from_ascii("\\tbinom"));
2009         globals.push_back(from_ascii("\\hphantom"));
2010         globals.push_back(from_ascii("\\phantom"));
2011         globals.push_back(from_ascii("\\vphantom"));
2012         MathWordList const & words = mathedWordList();
2013         MathWordList::const_iterator it2;
2014         //lyxerr << "Globals completion commands: ";
2015         for (it2 = words.begin(); it2 != words.end(); ++it2) {
2016                 globals.push_back("\\" + (*it2).first);
2017                 //lyxerr << "\\" + (*it2).first << " ";
2018         }
2019         //lyxerr << std::endl;
2020         sort(globals.begin(), globals.end());
2021 }
2022
2023
2024 MathCompletionList::~MathCompletionList()
2025 {
2026 }
2027
2028
2029 size_type MathCompletionList::size() const
2030 {
2031         return locals.size() + globals.size();
2032 }
2033
2034
2035 docstring const & MathCompletionList::data(size_t idx) const
2036 {
2037         size_t lsize = locals.size();
2038         if (idx >= lsize)
2039                 return globals[idx - lsize];
2040         else
2041                 return locals[idx];
2042 }
2043
2044
2045 std::string MathCompletionList::icon(size_t idx) const
2046 {
2047         // get the latex command
2048         docstring cmd;
2049         size_t lsize = locals.size();
2050         if (idx >= lsize)
2051                 cmd = globals[idx - lsize];
2052         else
2053                 cmd = locals[idx];
2054
2055         // get the icon resource name by stripping the backslash
2056         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
2057 }
2058
2059 std::vector<docstring> MathCompletionList::globals;
2060
2061 } // namespace lyx