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