]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
fb6e2a04b958619b35d4957a436a26e557f759c6
[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                 int cell(0);
815                 if (cmd.argument == "\\root")
816                         cell = 1;
817                 if (ar.size() == 1 && (ar[0].nucleus()->asNestInset())) {
818                         cur.handleNest(ar[0], cell);
819                 } else
820                         cur.niceInsert(cmd.argument);
821                 break;
822                 }
823
824         case LFUN_DIALOG_SHOW_NEW_INSET: {
825                 string const & name = cmd.argument;
826                 string data;
827 #if 0
828                 if (name == "ref") {
829                         RefInset tmp(name);
830                         data = tmp.createDialogStr(name);
831                 }
832 #endif
833                 cur.bv().owner()->getDialogs().show(name, data, 0);
834                 break;
835         }
836
837         case LFUN_INSET_APPLY: {
838                 string const name = cmd.getArg(0);
839                 InsetBase * base = cur.bv().owner()->getDialogs().getOpenInset(name);
840
841                 if (base) {
842                         FuncRequest fr(LFUN_INSET_MODIFY, cmd.argument);
843                         base->dispatch(cur, fr);
844                         break;
845                 }
846                 MathArray ar;
847                 if (createMathInset_fromDialogStr(cmd.argument, ar)) {
848                         cur.insert(ar);
849                         break;
850                 }
851                 cur.undispatched();
852                 break;
853         }
854
855         default:
856                 MathDimInset::doDispatch(cur, cmd);
857                 break;
858         }
859 }
860
861
862 bool MathNestInset::getStatus(LCursor & /*cur*/, FuncRequest const & cmd,
863                 FuncStatus & flag) const
864 {
865         // the font related toggles
866         //string tc = "mathnormal";
867         bool ret = true;
868         switch (cmd.action) {
869 #if 0
870         case LFUN_TABULAR_FEATURE:
871                 // FIXME: check temporarily disabled
872                 // valign code
873                 char align = mathcursor::valign();
874                 if (align == '\0') {
875                         enable = false;
876                         break;
877                 }
878                 if (cmd.argument.empty()) {
879                         flag.clear();
880                         break;
881                 }
882                 if (!contains("tcb", cmd.argument[0])) {
883                         enable = false;
884                         break;
885                 }
886                 flag.setOnOff(cmd.argument[0] == align);
887                 break;
888         case LFUN_BOLD:
889                 flag.setOnOff(tc == "mathbf");
890                 break;
891         case LFUN_SANS:
892                 flag.setOnOff(tc == "mathsf");
893                 break;
894         case LFUN_EMPH:
895                 flag.setOnOff(tc == "mathcal");
896                 break;
897         case LFUN_ROMAN:
898                 flag.setOnOff(tc == "mathrm");
899                 break;
900         case LFUN_CODE:
901                 flag.setOnOff(tc == "mathtt");
902                 break;
903         case LFUN_NOUN:
904                 flag.setOnOff(tc == "mathbb");
905                 break;
906         case LFUN_DEFAULT:
907                 flag.setOnOff(tc == "mathnormal");
908                 break;
909 #endif
910         case LFUN_MATH_MUTATE:
911                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
912                 flag.setOnOff(false);
913                 break;
914
915         // we just need to be in math mode to enable that
916         case LFUN_MATH_SIZE:
917         case LFUN_MATH_SPACE:
918         case LFUN_MATH_LIMITS:
919         case LFUN_MATH_NONUMBER:
920         case LFUN_MATH_NUMBER:
921         case LFUN_MATH_EXTERN:
922                 flag.enabled(true);
923                 break;
924
925         default:
926                 ret = false;
927                 break;
928         }
929         return ret;
930 }
931
932
933 void MathNestInset::edit(LCursor & cur, bool left)
934 {
935         cur.push(*this);
936         cur.idx() = left ? 0 : cur.lastidx();
937         cur.pos() = left ? 0 : cur.lastpos();
938         cur.resetAnchor();
939         lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
940 }
941
942
943 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y) const
944 {
945         int idx_min = 0;
946         int dist_min = 1000000;
947         for (idx_type i = 0; i < nargs(); ++i) {
948                 int d = cell(i).dist(x, y);
949                 if (d < dist_min) {
950                         dist_min = d;
951                         idx_min = i;
952                 }
953         }
954         MathArray const & ar = cell(idx_min);
955         cur.push(const_cast<MathNestInset&>(*this));
956         cur.idx() = idx_min;
957         cur.pos() = ar.x2pos(x - ar.xo());
958         lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
959         if (dist_min == 0) {
960                 // hit inside cell
961                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
962                         if (ar[i]->covers(x, y))
963                                 return ar[i].nucleus()->editXY(cur, x, y);
964         }
965         return const_cast<MathNestInset*>(this);
966 }
967
968
969 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
970 {
971         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
972         if (cmd.button() == mouse_button::button1) {
973                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
974                 cur.resetAnchor();
975                 cur.bv().cursor() = cur;
976         }
977
978         if (cmd.button() == mouse_button::button2) {
979                 cur.dispatch(FuncRequest(LFUN_PASTESELECTION));
980         }
981 }
982
983
984 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
985 {
986         // only select with button 1
987         if (cmd.button() == mouse_button::button1) {
988                 LCursor & bvcur = cur.bv().cursor();
989                 if (bvcur.anchor_.hasPart(cur)) {
990                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
991                         bvcur.setCursor(cur);
992                         bvcur.selection() = true;
993                         //lyxerr << "MOTION " << bvcur << endl;
994                 }
995                 else {
996                         cur.undispatched();
997                 }
998         }
999 }
1000
1001
1002 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1003 {
1004         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1005
1006         if (cmd.button() == mouse_button::button1) {
1007                 //cur.bv().stuffClipboard(cur.grabSelection());
1008                 return;
1009         }
1010
1011         if (cmd.button() == mouse_button::button2) {
1012                 MathArray ar;
1013                 asArray(cur.bv().getClipboard(), ar);
1014                 cur.clearSelection();
1015                 cur.setScreenPos(cmd.x, cmd.y);
1016                 cur.insert(ar);
1017                 cur.bv().update();
1018                 return;
1019         }
1020
1021         if (cmd.button() == mouse_button::button3) {
1022                 // try to dispatch to enclosed insets first
1023                 cur.bv().owner()->getDialogs().show("mathpanel");
1024                 return;
1025         }
1026
1027         cur.undispatched();
1028 }
1029
1030
1031 bool MathNestInset::interpret(LCursor & cur, char c)
1032 {
1033         lyxerr << "interpret 2: '" << c << "'" << endl;
1034         cur.clearTargetX();
1035
1036         // handle macroMode
1037         if (cur.inMacroMode()) {
1038                 string name = cur.macroName();
1039
1040                 /// are we currently typing '#1' or '#2' or...?
1041                 if (name == "\\#") {
1042                         cur.backspace();
1043                         int n = c - '0';
1044                         if (n >= 1 && n <= 9)
1045                                 cur.insert(new MathMacroArgument(n));
1046                         return true;
1047                 }
1048
1049                 if (isalpha(c)) {
1050                         cur.activeMacro()->setName(name + c);
1051                         return true;
1052                 }
1053
1054                 // handle 'special char' macros
1055                 if (name == "\\") {
1056                         // remove the '\\'
1057                         if (c == '\\') {
1058                                 cur.backspace();
1059                                 if (currentMode() == MathInset::TEXT_MODE)
1060                                         cur.niceInsert(createMathInset("textbackslash"));
1061                                 else
1062                                         cur.niceInsert(createMathInset("backslash"));
1063                         } else if (c == '{') {
1064                                 cur.backspace();
1065                                 cur.niceInsert(MathAtom(new MathBraceInset));
1066                         } else if (c == '%') {
1067                                 cur.backspace();
1068                                 cur.niceInsert(MathAtom(new MathCommentInset));
1069                         } else if (c == '#') {
1070                                 BOOST_ASSERT(cur.activeMacro());
1071                                 cur.activeMacro()->setName(name + c);
1072                         } else {
1073                                 cur.backspace();
1074                                 cur.niceInsert(createMathInset(string(1, c)));
1075                         }
1076                         return true;
1077                 }
1078
1079                 // leave macro mode and try again if necessary
1080                 cur.macroModeClose();
1081                 if (c == '{')
1082                         cur.niceInsert(MathAtom(new MathBraceInset));
1083                 else if (c != ' ')
1084                         interpret(cur, c);
1085                 return true;
1086         }
1087
1088         // This is annoying as one has to press <space> far too often.
1089         // Disable it.
1090
1091 #if 0
1092                 // leave autocorrect mode if necessary
1093                 if (autocorrect() && c == ' ') {
1094                         autocorrect() = false;
1095                         return true;
1096                 }
1097 #endif
1098
1099         // just clear selection on pressing the space bar
1100         if (cur.selection() && c == ' ') {
1101                 cur.selection() = false;
1102                 return true;
1103         }
1104
1105         selClearOrDel(cur);
1106
1107         if (c == '\\') {
1108                 //lyxerr << "starting with macro" << endl;
1109                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1110                 return true;
1111         }
1112
1113         if (c == '\n') {
1114                 if (currentMode() == MathInset::TEXT_MODE)
1115                         cur.insert(c);
1116                 return true;
1117         }
1118
1119         if (c == ' ') {
1120                 if (currentMode() == MathInset::TEXT_MODE) {
1121                         // insert spaces in text mode,
1122                         // but suppress direct insertion of two spaces in a row
1123                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1124                         // it is better than nothing...
1125                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1126                                 cur.insert(c);
1127                         return true;
1128                 }
1129                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1130                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1131                         return true;
1132                 }
1133                 if (cur.popRight())
1134                         return true;
1135                 // if are at the very end, leave the formula
1136                 return cur.pos() != cur.lastpos();
1137         }
1138
1139         if (c == '_') {
1140                 script(cur, false);
1141                 return true;
1142         }
1143
1144         if (c == '^') {
1145                 script(cur, true);
1146                 return true;
1147         }
1148
1149         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' || c == '%') {
1150                 cur.niceInsert(createMathInset(string(1, c)));
1151                 return true;
1152         }
1153
1154         if (c == '~') {
1155                 cur.niceInsert(createMathInset("sim"));
1156                 return true;
1157         }
1158
1159         // try auto-correction
1160         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1161         //      return true;
1162
1163         // no special circumstances, so insert the character without any fuss
1164         cur.insert(c);
1165         cur.autocorrect() = true;
1166         return true;
1167 }
1168
1169
1170 bool MathNestInset::script(LCursor & cur, bool up)
1171 {
1172         // Hack to get \^ and \_ working
1173         lyxerr << "handling script: up: " << up << endl;
1174         if (cur.inMacroMode() && cur.macroName() == "\\") {
1175                 if (up)
1176                         cur.niceInsert(createMathInset("mathcircumflex"));
1177                 else
1178                         interpret(cur, '_');
1179                 return true;
1180         }
1181
1182         cur.macroModeClose();
1183         string safe = grabAndEraseSelection(cur);
1184         if (asScriptInset() && cur.idx() == 0) {
1185                 // we are in a nucleus of a script inset, move to _our_ script
1186                 MathScriptInset * inset = asScriptInset();
1187                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1188                 inset->ensure(up);
1189                 cur.idx() = inset->idxOfScript(up);
1190                 cur.pos() = 0;
1191         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1192                 --cur.pos();
1193                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1194                 cur.push(*inset);
1195                 cur.idx() = inset->idxOfScript(up);
1196                 cur.pos() = cur.lastpos();
1197         } else {
1198                 // convert the thing to our left to a scriptinset or create a new
1199                 // one if in the very first position of the array
1200                 if (cur.pos() == 0) {
1201                         lyxerr << "new scriptinset" << endl;
1202                         cur.insert(new MathScriptInset(up));
1203                 } else {
1204                         lyxerr << "converting prev atom " << endl;
1205                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1206                 }
1207                 --cur.pos();
1208                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1209                 cur.push(*inset);
1210                 cur.idx() = 1;
1211                 cur.pos() = 0;
1212         }
1213         lyxerr << "pasting 1: safe:\n" << safe << endl;
1214         cur.paste(safe);
1215         cur.resetAnchor();
1216         lyxerr << "pasting 2: safe:\n" << safe << endl;
1217         return true;
1218 }