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