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