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