]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
Code cleanup of \bigl related stuff:
[lyx.git] / src / mathed / math_nestinset.C
1 /**
2  * \file math_nestinset.C
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 "math_nestinset.h"
14
15 #include "math_arrayinset.h"
16 #include "math_biginset.h"
17 #include "math_boxinset.h"
18 #include "math_braceinset.h"
19 #include "math_colorinset.h"
20 #include "math_commentinset.h"
21 #include "math_data.h"
22 #include "math_deliminset.h"
23 #include "math_factory.h"
24 #include "math_hullinset.h"
25 #include "math_mathmlstream.h"
26 #include "math_macroarg.h"
27 //#include "math_mboxinset.h"
28 #include "math_parser.h"
29 #include "math_scriptinset.h"
30 #include "math_spaceinset.h"
31 #include "math_symbolinset.h"
32 #include "math_support.h"
33 #include "math_unknowninset.h"
34 #include "ref_inset.h"
35
36 #include "BufferView.h"
37 #include "CutAndPaste.h"
38 #include "FuncStatus.h"
39 #include "LColor.h"
40 #include "bufferview_funcs.h"
41 #include "coordcache.h"
42 #include "cursor.h"
43 #include "debug.h"
44 #include "dispatchresult.h"
45 #include "funcrequest.h"
46 #include "gettext.h"
47 #include "outputparams.h"
48 #include "undo.h"
49
50 #include "support/lstrings.h"
51
52 #include "frontends/Dialogs.h"
53 #include "frontends/LyXView.h"
54 #include "frontends/Painter.h"
55 #include "frontends/nullpainter.h"
56
57 #include <sstream>
58
59 using lyx::cap::copySelection;
60 using lyx::cap::grabAndEraseSelection;
61 using lyx::cap::cutSelection;
62 using lyx::cap::replaceSelection;
63 using lyx::cap::selClearOrDel;
64
65 using std::endl;
66 using std::string;
67 using std::istringstream;
68
69
70 MathNestInset::MathNestInset(idx_type nargs)
71         : cells_(nargs), lock_(false)
72 {}
73
74
75 MathInset::idx_type MathNestInset::nargs() const
76 {
77         return cells_.size();
78 }
79
80
81 MathArray & MathNestInset::cell(idx_type i)
82 {
83         return cells_[i];
84 }
85
86
87 MathArray const & MathNestInset::cell(idx_type i) const
88 {
89         return cells_[i];
90 }
91
92
93 void MathNestInset::cursorPos(CursorSlice const & sl, bool /*boundary*/,
94         int & x, int & y) const
95 {
96 // FIXME: This is a hack. Ideally, the coord cache should not store
97 // absolute positions, but relative ones. This would mean to call
98 // setXY() not in MathArray::draw(), but in the parent insets' draw()
99 // with the correctly adjusted x,y values. But this means that we'd have
100 // to touch all (math)inset's draw() methods. Right now, we'll store
101 // absolute value, and make them here relative, only to make them
102 // absolute again when actually drawing the cursor. What a mess.
103         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
104         MathArray const & ar = sl.cell();
105         if (!theCoords.getArrays().has(&ar)) {
106                 // this can (semi-)legally happen if we just created this cell
107                 // and it never has been drawn before. So don't ASSERT.
108                 //lyxerr << "no cached data for array " << &ar << endl;
109                 x = 0;
110                 y = 0;
111                 return;
112         }
113         Point const pt = theCoords.getArrays().xy(&ar);
114         if (!theCoords.getInsets().has(this)) {
115                 // same as above
116                 //lyxerr << "no cached data for inset " << this << endl;
117                 x = 0;
118                 y = 0;
119                 return;
120         }
121         Point const pt2 = theCoords.getInsets().xy(this);
122         //lyxerr << "retrieving position cache for MathArray "
123         //      << pt.x_ << ' ' << pt.y_ << std::endl;
124         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
125         y = pt.y_ - pt2.y_;
126 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
127 //              << " asc: " << ascent() << "  des: " << descent()
128 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
129         // move cursor visually into empty cells ("blue rectangles");
130         if (ar.empty())
131                 x += 2;
132 }
133
134
135 void MathNestInset::metrics(MetricsInfo const & mi) const
136 {
137         MetricsInfo m = mi;
138         for (idx_type i = 0, n = nargs(); i != n; ++i)
139                 cell(i).metrics(m);
140 }
141
142
143 bool MathNestInset::idxNext(LCursor & cur) const
144 {
145         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
146         if (cur.idx() == cur.lastidx())
147                 return false;
148         ++cur.idx();
149         cur.pos() = 0;
150         return true;
151 }
152
153
154 bool MathNestInset::idxRight(LCursor & cur) const
155 {
156         return idxNext(cur);
157 }
158
159
160 bool MathNestInset::idxPrev(LCursor & cur) const
161 {
162         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
163         if (cur.idx() == 0)
164                 return false;
165         --cur.idx();
166         cur.pos() = cur.lastpos();
167         return true;
168 }
169
170
171 bool MathNestInset::idxLeft(LCursor & cur) const
172 {
173         return idxPrev(cur);
174 }
175
176
177 bool MathNestInset::idxFirst(LCursor & cur) const
178 {
179         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
180         if (nargs() == 0)
181                 return false;
182         cur.idx() = 0;
183         cur.pos() = 0;
184         return true;
185 }
186
187
188 bool MathNestInset::idxLast(LCursor & cur) const
189 {
190         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
191         if (nargs() == 0)
192                 return false;
193         cur.idx() = cur.lastidx();
194         cur.pos() = cur.lastpos();
195         return true;
196 }
197
198
199 void MathNestInset::dump() const
200 {
201         WriteStream os(lyxerr);
202         os << "---------------------------------------------\n";
203         write(os);
204         os << "\n";
205         for (idx_type i = 0, n = nargs(); i != n; ++i)
206                 os << cell(i) << "\n";
207         os << "---------------------------------------------\n";
208 }
209
210
211 void MathNestInset::draw(PainterInfo & pi, int x, int y) const
212 {
213 #if 0
214         if (lock_)
215                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
216                                         LColor::mathlockbg);
217 #endif
218         setPosCache(pi, x, y);
219 }
220
221
222 void MathNestInset::drawSelection(PainterInfo & pi, int x, int y) const
223 {
224         // this should use the x/y values given, not the cached values
225         LCursor & cur = pi.base.bv->cursor();
226         if (!cur.selection())
227                 return;
228         if (!ptr_cmp(&cur.inset(), this))
229                 return;
230
231         // FIXME: hack to get position cache warm
232         static NullPainter nop;
233         PainterInfo pinop(pi);
234         pinop.pain = nop;
235         draw(pinop, x, y);
236
237         CursorSlice s1 = cur.selBegin();
238         CursorSlice s2 = cur.selEnd();
239         //lyxerr << "MathNestInset::drawing selection: "
240         //      << " s1: " << s1 << " s2: " << s2 << endl;
241         if (s1.idx() == s2.idx()) {
242                 MathArray const & c = cell(s1.idx());
243                 int x1 = c.xo() + c.pos2x(s1.pos());
244                 int y1 = c.yo() - c.ascent();
245                 int x2 = c.xo() + c.pos2x(s2.pos());
246                 int y2 = c.yo() + c.descent();
247                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
248         //lyxerr << "MathNestInset::drawing selection 3: "
249         //      << " x1: " << x1 << " x2: " << x2
250         //      << " y1: " << y1 << " y2: " << y2 << endl;
251         } else {
252                 for (idx_type i = 0; i < nargs(); ++i) {
253                         if (idxBetween(i, s1.idx(), s2.idx())) {
254                                 MathArray const & c = cell(i);
255                                 int x1 = c.xo();
256                                 int y1 = c.yo() - c.ascent();
257                                 int x2 = c.xo() + c.width();
258                                 int y2 = c.yo() + c.descent();
259                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
260                         }
261                 }
262         }
263 }
264
265
266 void MathNestInset::validate(LaTeXFeatures & features) const
267 {
268         for (idx_type i = 0; i < nargs(); ++i)
269                 cell(i).validate(features);
270 }
271
272
273 void MathNestInset::replace(ReplaceData & rep)
274 {
275         for (idx_type i = 0; i < nargs(); ++i)
276                 cell(i).replace(rep);
277 }
278
279
280 bool MathNestInset::contains(MathArray const & ar) const
281 {
282         for (idx_type i = 0; i < nargs(); ++i)
283                 if (cell(i).contains(ar))
284                         return true;
285         return false;
286 }
287
288
289 bool MathNestInset::lock() const
290 {
291         return lock_;
292 }
293
294
295 void MathNestInset::lock(bool l)
296 {
297         lock_ = l;
298 }
299
300
301 bool MathNestInset::isActive() const
302 {
303         return nargs() > 0;
304 }
305
306
307 MathArray MathNestInset::glue() const
308 {
309         MathArray ar;
310         for (size_t i = 0; i < nargs(); ++i)
311                 ar.append(cell(i));
312         return ar;
313 }
314
315
316 void MathNestInset::write(WriteStream & os) const
317 {
318         os << '\\' << name().c_str();
319         for (size_t i = 0; i < nargs(); ++i)
320                 os << '{' << cell(i) << '}';
321         if (nargs() == 0)
322                 os.pendingSpace(true);
323         if (lock_ && !os.latex()) {
324                 os << "\\lyxlock";
325                 os.pendingSpace(true);
326         }
327 }
328
329
330 void MathNestInset::normalize(NormalStream & os) const
331 {
332         os << '[' << name().c_str();
333         for (size_t i = 0; i < nargs(); ++i)
334                 os << ' ' << cell(i);
335         os << ']';
336 }
337
338
339 int MathNestInset::latex(Buffer const &, std::ostream & os,
340                         OutputParams const & runparams) const
341 {
342         WriteStream wi(os, runparams.moving_arg, true);
343         write(wi);
344         return wi.line();
345 }
346
347
348 void MathNestInset::notifyCursorLeaves(LCursor & cur)
349 {
350 #ifdef WITH_WARNINGS
351 #warning look here
352 #endif
353 #if 0
354         MathArray & ar = cur.cell();
355         // remove base-only "scripts"
356         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
357                 MathScriptInset * p = operator[](i).nucleus()->asScriptInset();
358                 if (p && p->nargs() == 1) {
359                         MathArray ar = p->nuc();
360                         erase(i);
361                         insert(i, ar);
362                         cur.adjust(i, ar.size() - 1);
363                 }
364         }
365
366         // glue adjacent font insets of the same kind
367         for (pos_type i = 0; i + 1 < size(); ++i) {
368                 MathFontInset * p = operator[](i).nucleus()->asFontInset();
369                 MathFontInset const * q = operator[](i + 1)->asFontInset();
370                 if (p && q && p->name() == q->name()) {
371                         p->cell(0).append(q->cell(0));
372                         erase(i + 1);
373                         cur.adjust(i, -1);
374                 }
375         }
376 #endif
377 }
378
379
380 void MathNestInset::handleFont
381         (LCursor & cur, string const & arg, string const & font)
382 {
383         // this whole function is a hack and won't work for incremental font
384         // changes...
385         recordUndo(cur, Undo::ATOMIC);
386
387         if (cur.inset().asMathInset()->name() == font)
388                 cur.handleFont(font);
389         else {
390                 cur.handleNest(createMathInset(font));
391                 cur.insert(arg);
392         }
393 }
394
395
396 void MathNestInset::handleFont2(LCursor & cur, string const & arg)
397 {
398         recordUndo(cur, Undo::ATOMIC);
399         LyXFont font;
400         bool b;
401         bv_funcs::string2font(arg, font, b);
402         if (font.color() != LColor::inherit) {
403                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
404                 cur.handleNest(at, 0);
405         }
406 }
407
408
409 void MathNestInset::doDispatch(LCursor & cur, FuncRequest & cmd)
410 {
411         //lyxerr << "MathNestInset: request: " << cmd << std::endl;
412         //CursorSlice sl = cur.current();
413
414         switch (cmd.action) {
415
416         case LFUN_PASTE: {
417                 recordUndo(cur);
418                 cur.message(_("Paste"));
419                 replaceSelection(cur);
420                 size_t n = 0;
421                 istringstream is(cmd.argument);
422                 is >> n;
423                 string const selection = lyx::cap::getSelection(cur.buffer(), n);
424                 cur.niceInsert(selection);
425                 cur.clearSelection(); // bug 393
426                 cur.bv().switchKeyMap();
427                 finishUndo();
428                 break;
429         }
430
431         case LFUN_CUT:
432                 recordUndo(cur);
433                 cutSelection(cur, true, true);
434                 cur.message(_("Cut"));
435                 // Prevent stale position >= size crash
436                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
437                 cur.normalize();
438                 break;
439
440         case LFUN_COPY:
441                 copySelection(cur);
442                 cur.message(_("Copy"));
443                 break;
444
445         case LFUN_MOUSE_PRESS:
446                 lfunMousePress(cur, cmd);
447                 break;
448
449         case LFUN_MOUSE_MOTION:
450                 lfunMouseMotion(cur, cmd);
451                 break;
452
453         case LFUN_MOUSE_RELEASE:
454                 lfunMouseRelease(cur, cmd);
455                 break;
456
457         case LFUN_FINISHED_LEFT:
458                 cur.bv().cursor() = cur;
459                 break;
460
461         case LFUN_FINISHED_RIGHT:
462                 ++cur.pos();
463                 cur.bv().cursor() = cur;
464                 break;
465
466         case LFUN_FINISHED_UP:
467                 cur.bv().cursor() = cur;
468                 break;
469
470         case LFUN_FINISHED_DOWN:
471                 ++cur.pos();
472                 cur.bv().cursor() = cur;
473                 break;
474
475         case LFUN_RIGHTSEL:
476         case LFUN_RIGHT:
477                 cur.selHandle(cmd.action == LFUN_RIGHTSEL);
478                 cur.autocorrect() = false;
479                 cur.clearTargetX();
480                 cur.macroModeClose();
481                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
482                         cur.pushLeft(*cur.nextAtom().nucleus());
483                         cur.inset().idxFirst(cur);
484                 } else if (cur.posRight() || idxRight(cur)
485                         || cur.popRight() || cur.selection())
486                         ;
487                 else {
488                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
489                         cur.undispatched();
490                 }
491                 break;
492
493         case LFUN_LEFTSEL:
494         case LFUN_LEFT:
495                 cur.selHandle(cmd.action == LFUN_LEFTSEL);
496                 cur.autocorrect() = false;
497                 cur.clearTargetX();
498                 cur.macroModeClose();
499                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
500                         cur.posLeft();
501                         cur.push(*cur.nextAtom().nucleus());
502                         cur.inset().idxLast(cur);
503                 } else if (cur.posLeft() || idxLeft(cur)
504                         || cur.popLeft() || cur.selection())
505                         ;
506                 else {
507                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
508                         cur.undispatched();
509                 }
510                 break;
511
512         case LFUN_UPSEL:
513         case LFUN_UP:
514                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
515                 if (cur.inMacroMode()) {
516                         // Make Helge happy
517                         cur.macroModeClose();
518                         break;
519                 }
520                 cur.selHandle(cmd.action == LFUN_UPSEL);
521                 if (!cur.up()) {
522                         cmd = FuncRequest(LFUN_FINISHED_UP);
523                         cur.undispatched();
524                 }
525                 // fixes bug 1598. Please check!
526                 cur.normalize();
527                 break;
528
529         case LFUN_DOWNSEL:
530         case LFUN_DOWN:
531                 if (cur.inMacroMode()) {
532                         cur.macroModeClose();
533                         break;
534                 }
535                 cur.selHandle(cmd.action == LFUN_DOWNSEL);
536                 if (!cur.down()) {
537                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
538                         cur.undispatched();
539                 }
540                 // fixes bug 1598. Please check!
541                 cur.normalize();
542                 break;
543
544         case LFUN_MOUSE_DOUBLE:
545         case LFUN_MOUSE_TRIPLE:
546         case LFUN_WORDSEL:
547                 cur.pos() = 0;
548                 cur.idx() = 0;
549                 cur.resetAnchor();
550                 cur.selection() = true;
551                 cur.pos() = cur.lastpos();
552                 cur.idx() = cur.lastidx();
553                 break;
554
555         case LFUN_UP_PARAGRAPHSEL:
556         case LFUN_UP_PARAGRAPH:
557         case LFUN_DOWN_PARAGRAPHSEL:
558         case LFUN_DOWN_PARAGRAPH:
559                 break;
560
561         case LFUN_HOMESEL:
562         case LFUN_HOME:
563         case LFUN_WORDLEFTSEL:
564         case LFUN_WORDLEFT:
565                 cur.selHandle(cmd.action == LFUN_WORDLEFTSEL || cmd.action == LFUN_HOMESEL);
566                 cur.macroModeClose();
567                 if (cur.pos() != 0) {
568                         cur.pos() = 0;
569                 } else if (cur.col() != 0) {
570                         cur.idx() -= cur.col();
571                         cur.pos() = 0;
572                 } else if (cur.idx() != 0) {
573                         cur.idx() = 0;
574                         cur.pos() = 0;
575                 } else {
576                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
577                         cur.undispatched();
578                 }
579                 break;
580
581         case LFUN_WORDRIGHTSEL:
582         case LFUN_WORDRIGHT:
583         case LFUN_ENDSEL:
584         case LFUN_END:
585                 cur.selHandle(cmd.action == LFUN_WORDRIGHTSEL || cmd.action == LFUN_ENDSEL);
586                 cur.macroModeClose();
587                 cur.clearTargetX();
588                 if (cur.pos() != cur.lastpos()) {
589                         cur.pos() = cur.lastpos();
590                 } else if (ncols() && (cur.col() != cur.lastcol())) {
591                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
592                         cur.pos() = cur.lastpos();
593                 } else if (cur.idx() != cur.lastidx()) {
594                         cur.idx() = cur.lastidx();
595                         cur.pos() = cur.lastpos();
596                 } else {
597                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
598                         cur.undispatched();
599                 }
600                 break;
601
602         case LFUN_PRIORSEL:
603         case LFUN_PRIOR:
604                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
605                 cur.undispatched();
606                 break;
607
608         case LFUN_NEXTSEL:
609         case LFUN_NEXT:
610                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
611                 cur.undispatched();
612                 break;
613
614         case LFUN_CELL_FORWARD:
615                 cur.inset().idxNext(cur);
616                 break;
617
618         case LFUN_CELL_BACKWARD:
619                 cur.inset().idxPrev(cur);
620                 break;
621
622         case LFUN_DELETE_WORD_BACKWARD:
623         case LFUN_BACKSPACE:
624                 if (cur.pos() == 0)
625                         // May affect external cell:
626                         recordUndoInset(cur, Undo::ATOMIC);
627                 else
628                         recordUndo(cur, Undo::ATOMIC);
629                 cur.backspace();
630                 break;
631
632         case LFUN_DELETE_WORD_FORWARD:
633         case LFUN_DELETE:
634                 if (cur.pos() == cur.lastpos())
635                         // May affect external cell:
636                         recordUndoInset(cur, Undo::ATOMIC);
637                 else
638                         recordUndo(cur, Undo::ATOMIC);
639                 cur.erase();
640                 break;
641
642         case LFUN_ESCAPE:
643                 if (cur.selection())
644                         cur.clearSelection();
645                 else  {
646                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
647                         cur.undispatched();
648                 }
649                 break;
650
651         case LFUN_INSET_TOGGLE:
652                 recordUndo(cur);
653                 //lockToggle();
654                 if (cur.pos() != cur.lastpos()) {
655                         // toggle previous inset ...
656                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
657                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
658                         // ... or enclosing inset if we are in the last inset position
659                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
660                         ++cur.pos();
661                 }
662                 break;
663
664         case LFUN_SELFINSERT:
665                 if (cmd.argument.size() != 1) {
666                         recordUndo(cur);
667                         if (!interpret(cur, cmd.argument))
668                                 cur.insert(cmd.argument);
669                         break;
670                 }
671                 // Don't record undo steps if we are in macro mode and
672                 // cmd.argument is the next character of the macro name.
673                 // Otherwise we'll get an invalid cursor if we undo after
674                 // the macro was finished and the macro is a known command,
675                 // e.g. sqrt. LCursor::macroModeClose replaces in this case
676                 // the MathUnknownInset with name "frac" by an empty
677                 // MathFracInset -> a pos value > 0 is invalid.
678                 // A side effect is that an undo before the macro is finished
679                 // undoes the complete macro, not only the last character.
680                 if (!cur.inMacroMode())
681                         recordUndo(cur);
682
683                 // spacial handling of space. If we insert an inset
684                 // via macro mode, we want to put the cursor inside it
685                 // if relevant. Think typing "\frac<space>".
686                 if (cmd.argument[0] == ' '
687                     && cur.inMacroMode() && cur.macroName() != "\\"
688                     && cur.macroModeClose()) {
689                         MathAtom const atom = cur.prevAtom();
690                         if (atom->asNestInset() && atom->nargs() > 0) {
691                                 cur.posLeft();
692                                 cur.pushLeft(*cur.nextInset());
693                         }
694                 } else if (!interpret(cur, cmd.argument[0])) {
695                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
696                         cur.undispatched();
697                 }
698                 break;
699
700         //case LFUN_GETXY:
701         //      sprintf(dispatch_buffer, "%d %d",);
702         //      break;
703
704         case LFUN_SETXY: {
705                 lyxerr << "LFUN_SETXY broken!" << endl;
706                 int x = 0;
707                 int y = 0;
708                 istringstream is(cmd.argument);
709                 is >> x >> y;
710                 cur.setScreenPos(x, y);
711                 break;
712         }
713
714         // Special casing for superscript in case of LyX handling
715         // dead-keys:
716         case LFUN_CIRCUMFLEX:
717                 if (cmd.argument.empty()) {
718                         // do superscript if LyX handles
719                         // deadkeys
720                         recordUndo(cur, Undo::ATOMIC);
721                         script(cur, true, grabAndEraseSelection(cur));
722                 }
723                 break;
724
725         case LFUN_UMLAUT:
726         case LFUN_ACUTE:
727         case LFUN_GRAVE:
728         case LFUN_BREVE:
729         case LFUN_DOT:
730         case LFUN_MACRON:
731         case LFUN_CARON:
732         case LFUN_TILDE:
733         case LFUN_CEDILLA:
734         case LFUN_CIRCLE:
735         case LFUN_UNDERDOT:
736         case LFUN_TIE:
737         case LFUN_OGONEK:
738         case LFUN_HUNG_UMLAUT:
739                 break;
740
741         //  Math fonts
742         case LFUN_FREEFONT_APPLY:
743         case LFUN_FREEFONT_UPDATE:
744                 handleFont2(cur, cmd.argument);
745                 break;
746
747         case LFUN_BOLD:
748                 if (currentMode() == TEXT_MODE)
749                         handleFont(cur, cmd.argument, "textbf");
750                 else
751                         handleFont(cur, cmd.argument, "mathbf");
752                 break;
753         case LFUN_SANS:
754                 if (currentMode() == TEXT_MODE)
755                         handleFont(cur, cmd.argument, "textsf");
756                 else
757                         handleFont(cur, cmd.argument, "mathsf");
758                 break;
759         case LFUN_EMPH:
760                 if (currentMode() == TEXT_MODE)
761                         handleFont(cur, cmd.argument, "emph");
762                 else
763                         handleFont(cur, cmd.argument, "mathcal");
764                 break;
765         case LFUN_ROMAN:
766                 if (currentMode() == TEXT_MODE)
767                         handleFont(cur, cmd.argument, "textrm");
768                 else
769                         handleFont(cur, cmd.argument, "mathrm");
770                 break;
771         case LFUN_CODE:
772                 if (currentMode() == TEXT_MODE)
773                         handleFont(cur, cmd.argument, "texttt");
774                 else
775                         handleFont(cur, cmd.argument, "mathtt");
776                 break;
777         case LFUN_FRAK:
778                 handleFont(cur, cmd.argument, "mathfrak");
779                 break;
780         case LFUN_ITAL:
781                 if (currentMode() == TEXT_MODE)
782                         handleFont(cur, cmd.argument, "textit");
783                 else
784                         handleFont(cur, cmd.argument, "mathit");
785                 break;
786         case LFUN_NOUN:
787                 if (currentMode() == TEXT_MODE)
788                         // FIXME: should be "noun"
789                         handleFont(cur, cmd.argument, "textsc");
790                 else
791                         handleFont(cur, cmd.argument, "mathbb");
792                 break;
793         //case LFUN_FREEFONT_APPLY:
794                 handleFont(cur, cmd.argument, "textrm");
795                 break;
796         case LFUN_DEFAULT:
797                 handleFont(cur, cmd.argument, "textnormal");
798                 break;
799
800         case LFUN_MATH_MODE: {
801 #if 1
802                 // ignore math-mode on when already in math mode
803                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
804                         break;
805                 cur.macroModeClose();
806                 string const save_selection = grabAndEraseSelection(cur);
807                 selClearOrDel(cur);
808                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
809                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
810                 cur.posLeft();
811                 cur.pushLeft(*cur.nextInset());
812                 cur.niceInsert(save_selection);
813 #else
814                 if (currentMode() == InsetBase::TEXT_MODE) {
815                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
816                         cur.message(_("create new math text environment ($...$)"));
817                 } else {
818                         handleFont(cur, cmd.argument, "textrm");
819                         cur.message(_("entered math text mode (textrm)"));
820                 }
821 #endif
822                 break;
823         }
824
825         case LFUN_MATH_SIZE:
826 #if 0
827                 recordUndo(cur);
828                 cur.setSize(arg);
829 #endif
830                 break;
831
832         case LFUN_INSERT_MATRIX: {
833                 recordUndo(cur, Undo::ATOMIC);
834                 unsigned int m = 1;
835                 unsigned int n = 1;
836                 string v_align;
837                 string h_align;
838                 istringstream is(cmd.argument);
839                 is >> m >> n >> v_align >> h_align;
840                 if (m < 1)
841                         m = 1;
842                 if (n < 1)
843                         n = 1;
844                 v_align += 'c';
845                 cur.niceInsert(
846                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
847                 break;
848         }
849
850         case LFUN_MATH_DELIM: {
851                 lyxerr << "MathNestInset::LFUN_MATH_DELIM" << endl;
852                 string ls;
853                 string rs = lyx::support::split(cmd.argument, ls, ' ');
854                 // Reasonable default values
855                 if (ls.empty())
856                         ls = '(';
857                 if (rs.empty())
858                         rs = ')';
859                 recordUndo(cur, Undo::ATOMIC);
860                 // Don't do this with multi-cell selections
861                 if (cur.selBegin().idx() == cur.selEnd().idx())
862                         cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
863                 break;
864         }
865
866         case LFUN_SPACE_INSERT:
867         case LFUN_MATH_SPACE:
868                 recordUndo(cur, Undo::ATOMIC);
869                 cur.insert(MathAtom(new MathSpaceInset(",")));
870                 break;
871
872         case LFUN_INSET_ERT:
873                 // interpret this as if a backslash was typed
874                 recordUndo(cur, Undo::ATOMIC);
875                 interpret(cur, '\\');
876                 break;
877
878         case LFUN_SUBSCRIPT:
879                 // interpret this as if a _ was typed
880                 recordUndo(cur, Undo::ATOMIC);
881                 interpret(cur, '_');
882                 break;
883
884         case LFUN_SUPERSCRIPT:
885                 // interpret this as if a ^ was typed
886                 recordUndo(cur, Undo::ATOMIC);
887                 interpret(cur, '^');
888                 break;
889
890 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
891 // handling such that "self-insert" works on "arbitrary stuff" too, and
892 // math-insert only handles special math things like "matrix".
893         case LFUN_INSERT_MATH: {
894                 recordUndo(cur, Undo::ATOMIC);
895                 if (cmd.argument == "^" || cmd.argument == "_") {
896                         interpret(cur, cmd.argument[0]);
897                 } else
898                         cur.niceInsert(cmd.argument);
899                 break;
900                 }
901
902         case LFUN_DIALOG_SHOW_NEW_INSET: {
903                 string const & name = cmd.argument;
904                 string data;
905                 if (name == "ref") {
906                         RefInset tmp(name);
907                         data = tmp.createDialogStr(name);
908                 }
909                 cur.bv().owner()->getDialogs().show(name, data, 0);
910                 break;
911         }
912
913         default:
914                 MathDimInset::doDispatch(cur, cmd);
915                 break;
916         }
917 }
918
919
920 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
921                 FuncStatus & flag) const
922 {
923         // the font related toggles
924         //string tc = "mathnormal";
925         bool ret = true;
926         string const arg = cmd.argument;
927         switch (cmd.action) {
928         case LFUN_TABULAR_FEATURE:
929                 flag.enabled(false);
930                 break;
931 #if 0
932         case LFUN_TABULAR_FEATURE:
933                 // FIXME: check temporarily disabled
934                 // valign code
935                 char align = mathcursor::valign();
936                 if (align == '\0') {
937                         enable = false;
938                         break;
939                 }
940                 if (cmd.argument.empty()) {
941                         flag.clear();
942                         break;
943                 }
944                 if (!contains("tcb", cmd.argument[0])) {
945                         enable = false;
946                         break;
947                 }
948                 flag.setOnOff(cmd.argument[0] == align);
949                 break;
950 #endif
951         /// We have to handle them since 1.4 blocks all unhandled actions
952         case LFUN_ITAL:
953         case LFUN_BOLD:
954         case LFUN_SANS:
955         case LFUN_EMPH:
956         case LFUN_CODE:
957         case LFUN_NOUN:
958         case LFUN_ROMAN:
959         case LFUN_DEFAULT:
960                 flag.enabled(true);
961                 break;
962         case LFUN_MATH_MUTATE:
963                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
964                 flag.setOnOff(false);
965                 break;
966
967         // we just need to be in math mode to enable that
968         case LFUN_MATH_SIZE:
969         case LFUN_MATH_SPACE:
970         case LFUN_MATH_LIMITS:
971         case LFUN_MATH_NONUMBER:
972         case LFUN_MATH_NUMBER:
973         case LFUN_MATH_EXTERN:
974                 flag.enabled(true);
975                 break;
976
977         case LFUN_FRAK:
978                 flag.enabled(currentMode() != TEXT_MODE);
979                 break;
980
981         case LFUN_INSERT_MATH: {
982                 bool const textarg =
983                         arg == "\\textbf"   || arg == "\\textsf" ||
984                         arg == "\\textrm"   || arg == "\\textmd" ||
985                         arg == "\\textit"   || arg == "\\textsc" ||
986                         arg == "\\textsl"   || arg == "\\textup" ||
987                         arg == "\\texttt"   || arg == "\\textbb" ||
988                         arg == "\\textnormal";
989                 flag.enabled(currentMode() != TEXT_MODE || textarg);
990                 break;
991         }
992
993         case LFUN_INSERT_MATRIX:
994                 flag.enabled(currentMode() == MATH_MODE);
995                 break;
996         default:
997                 ret = false;
998                 break;
999         }
1000         return ret;
1001 }
1002
1003
1004 void MathNestInset::edit(LCursor & cur, bool left)
1005 {
1006         cur.push(*this);
1007         cur.idx() = left ? 0 : cur.lastidx();
1008         cur.pos() = left ? 0 : cur.lastpos();
1009         cur.resetAnchor();
1010         //lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
1011 }
1012
1013
1014 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y)
1015 {
1016         int idx_min = 0;
1017         int dist_min = 1000000;
1018         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1019                 int const d = cell(i).dist(x, y);
1020                 if (d < dist_min) {
1021                         dist_min = d;
1022                         idx_min = i;
1023                 }
1024         }
1025         MathArray & ar = cell(idx_min);
1026         cur.push(*this);
1027         cur.idx() = idx_min;
1028         cur.pos() = ar.x2pos(x - ar.xo());
1029         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1030         if (dist_min == 0) {
1031                 // hit inside cell
1032                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1033                         if (ar[i]->covers(x, y))
1034                                 return ar[i].nucleus()->editXY(cur, x, y);
1035         }
1036         return this;
1037 }
1038
1039
1040 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1041 {
1042         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1043         if (cmd.button() == mouse_button::button1) {
1044                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1045                 cur.bv().mouseSetCursor(cur);
1046         }
1047
1048         if (cmd.button() == mouse_button::button2) {
1049                 MathArray ar;
1050                 asArray(cur.bv().getClipboard(), ar);
1051                 cur.clearSelection();
1052                 editXY(cur, cmd.x, cmd.y);
1053                 cur.insert(ar);
1054                 cur.bv().update();
1055                 return;
1056         }
1057 }
1058
1059
1060 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1061 {
1062         // only select with button 1
1063         if (cmd.button() == mouse_button::button1) {
1064                 LCursor & bvcur = cur.bv().cursor();
1065                 if (bvcur.anchor_.hasPart(cur)) {
1066                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1067                         bvcur.setCursor(cur);
1068                         bvcur.selection() = true;
1069                         //lyxerr << "MOTION " << bvcur << endl;
1070                 }
1071                 else {
1072                         cur.undispatched();
1073                 }
1074         }
1075 }
1076
1077
1078 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1079 {
1080         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1081
1082         if (cmd.button() == mouse_button::button1) {
1083                 //cur.bv().stuffClipboard(cur.grabSelection());
1084                 return;
1085         }
1086
1087         if (cmd.button() == mouse_button::button3) {
1088                 // try to dispatch to enclosed insets first
1089                 cur.bv().owner()->getDialogs().show("mathpanel");
1090                 return;
1091         }
1092
1093         cur.undispatched();
1094 }
1095
1096
1097 bool MathNestInset::interpret(LCursor & cur, char c)
1098 {
1099         //lyxerr << "interpret 2: '" << c << "'" << endl;
1100         string save_selection;
1101         if (c == '^' || c == '_')
1102                 save_selection = grabAndEraseSelection(cur);
1103
1104         cur.clearTargetX();
1105
1106         // handle macroMode
1107         if (cur.inMacroMode()) {
1108                 string name = cur.macroName();
1109
1110                 /// are we currently typing '#1' or '#2' or...?
1111                 if (name == "\\#") {
1112                         cur.backspace();
1113                         int n = c - '0';
1114                         if (n >= 1 && n <= 9)
1115                                 cur.insert(new MathMacroArgument(n));
1116                         return true;
1117                 }
1118
1119                 if (isalpha(c)) {
1120                         cur.activeMacro()->setName(name + c);
1121                         return true;
1122                 }
1123
1124                 // handle 'special char' macros
1125                 if (name == "\\") {
1126                         // remove the '\\'
1127                         if (c == '\\') {
1128                                 cur.backspace();
1129                                 if (currentMode() == MathInset::TEXT_MODE)
1130                                         cur.niceInsert(createMathInset("textbackslash"));
1131                                 else
1132                                         cur.niceInsert(createMathInset("backslash"));
1133                         } else if (c == '{') {
1134                                 cur.backspace();
1135                                 cur.niceInsert(MathAtom(new MathBraceInset));
1136                         } else if (c == '%') {
1137                                 cur.backspace();
1138                                 cur.niceInsert(MathAtom(new MathCommentInset));
1139                         } else if (c == '#') {
1140                                 BOOST_ASSERT(cur.activeMacro());
1141                                 cur.activeMacro()->setName(name + c);
1142                         } else {
1143                                 cur.backspace();
1144                                 cur.niceInsert(createMathInset(string(1, c)));
1145                         }
1146                         return true;
1147                 }
1148
1149                 // One character big delimiters. The others are handled in
1150                 // the other interpret() method.
1151                 latexkeys const * l = in_word_set(name.substr(1));
1152                 if (name[0] == '\\' && l && l->inset == "big") {
1153                         string delim;
1154                         switch (c) {
1155                         case '{':
1156                                 delim = "\\{";
1157                                 break;
1158                         case '}':
1159                                 delim = "\\}";
1160                                 break;
1161                         default:
1162                                 delim = string(1, c);
1163                                 break;
1164                         }
1165                         if (MathBigInset::isBigInsetDelim(delim)) {
1166                                 // name + delim ared a valid MathBigInset.
1167                                 // We can't use cur.macroModeClose() because
1168                                 // it does not handle delim.
1169                                 MathUnknownInset * p = cur.activeMacro();
1170                                 p->finalize();
1171                                 --cur.pos();
1172                                 cur.cell().erase(cur.pos());
1173                                 cur.plainInsert(MathAtom(
1174                                         new MathBigInset(name.substr(1), delim)));
1175                                 return true;
1176                         }
1177                 }
1178
1179                 // leave macro mode and try again if necessary
1180                 cur.macroModeClose();
1181                 if (c == '{')
1182                         cur.niceInsert(MathAtom(new MathBraceInset));
1183                 else if (c != ' ')
1184                         interpret(cur, c);
1185                 return true;
1186         }
1187
1188         // This is annoying as one has to press <space> far too often.
1189         // Disable it.
1190
1191 #if 0
1192                 // leave autocorrect mode if necessary
1193                 if (autocorrect() && c == ' ') {
1194                         autocorrect() = false;
1195                         return true;
1196                 }
1197 #endif
1198
1199         // just clear selection on pressing the space bar
1200         if (cur.selection() && c == ' ') {
1201                 cur.selection() = false;
1202                 return true;
1203         }
1204
1205         selClearOrDel(cur);
1206
1207         if (c == '\\') {
1208                 //lyxerr << "starting with macro" << endl;
1209                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1210                 return true;
1211         }
1212
1213         if (c == '\n') {
1214                 if (currentMode() == MathInset::TEXT_MODE)
1215                         cur.insert(c);
1216                 return true;
1217         }
1218
1219         if (c == ' ') {
1220                 if (currentMode() == MathInset::TEXT_MODE) {
1221                         // insert spaces in text mode,
1222                         // but suppress direct insertion of two spaces in a row
1223                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1224                         // it is better than nothing...
1225                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1226                                 cur.insert(c);
1227                         return true;
1228                 }
1229                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1230                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1231                         return true;
1232                 }
1233                 if (cur.popRight())
1234                         return true;
1235                 // if are at the very end, leave the formula
1236                 return cur.pos() != cur.lastpos();
1237         }
1238
1239         // These shouldn't work in text mode:
1240         if (currentMode() != MathInset::TEXT_MODE) {
1241                 if (c == '_') {
1242                         script(cur, false, save_selection);
1243                         return true;
1244                 }
1245                 if (c == '^') {
1246                         script(cur, true, save_selection);
1247                         return true;
1248                 }
1249                 if (c == '~') {
1250                         cur.niceInsert(createMathInset("sim"));
1251                         return true;
1252                 }
1253         }
1254
1255         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1256             c == '%' || c == '_' || c == '^') {
1257                 cur.niceInsert(createMathInset(string(1, c)));
1258                 return true;
1259         }
1260
1261
1262         // try auto-correction
1263         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1264         //      return true;
1265
1266         // no special circumstances, so insert the character without any fuss
1267         cur.insert(c);
1268         cur.autocorrect() = true;
1269         return true;
1270 }
1271
1272
1273 bool MathNestInset::interpret(LCursor & cur, string const & str)
1274 {
1275         // Create a MathBigInset from cur.cell()[cur.pos() - 1] and t if
1276         // possible
1277         if (!cur.empty() && cur.pos() > 0 &&
1278             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1279                 if (MathBigInset::isBigInsetDelim(str)) {
1280                         string prev = asString(cur.cell()[cur.pos() - 1]);
1281                         if (prev[0] == '\\') {
1282                                 prev = prev.substr(1);
1283                                 latexkeys const * l = in_word_set(prev);
1284                                 if (l && l->inset == "big") {
1285                                         cur.cell()[cur.pos() - 1] =
1286                                                 MathAtom(new MathBigInset(prev, str));
1287                                         return true;
1288                                 }
1289                         }
1290                 }
1291         }
1292         return false;
1293 }
1294
1295
1296 bool MathNestInset::script(LCursor & cur, bool up, string const &
1297                 save_selection)
1298 {
1299         // Hack to get \^ and \_ working
1300         lyxerr << "handling script: up: " << up << endl;
1301         if (cur.inMacroMode() && cur.macroName() == "\\") {
1302                 if (up)
1303                         cur.niceInsert(createMathInset("mathcircumflex"));
1304                 else
1305                         interpret(cur, '_');
1306                 return true;
1307         }
1308
1309         cur.macroModeClose();
1310         if (asScriptInset() && cur.idx() == 0) {
1311                 // we are in a nucleus of a script inset, move to _our_ script
1312                 MathScriptInset * inset = asScriptInset();
1313                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1314                 inset->ensure(up);
1315                 cur.idx() = inset->idxOfScript(up);
1316                 cur.pos() = 0;
1317         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1318                 --cur.pos();
1319                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1320                 cur.push(*inset);
1321                 inset->ensure(up);
1322                 cur.idx() = inset->idxOfScript(up);
1323                 cur.pos() = cur.lastpos();
1324         } else {
1325                 // convert the thing to our left to a scriptinset or create a new
1326                 // one if in the very first position of the array
1327                 if (cur.pos() == 0) {
1328                         //lyxerr << "new scriptinset" << endl;
1329                         cur.insert(new MathScriptInset(up));
1330                 } else {
1331                         //lyxerr << "converting prev atom " << endl;
1332                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1333                 }
1334                 --cur.pos();
1335                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1336                 cur.push(*inset);
1337                 cur.idx() = 1;
1338                 cur.pos() = 0;
1339         }
1340         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1341         cur.niceInsert(save_selection);
1342         cur.resetAnchor();
1343         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1344         return true;
1345 }