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