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