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