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