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