]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.C
do not create invalid .lyx files when importing \i{}, \j{}, \l{} or \L{}.
[lyx.git] / src / mathed / InsetMathGrid.C
1 /**
2  * \file InsetMathGrid.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 "InsetMathGrid.h"
14 #include "MathData.h"
15 #include "MathStream.h"
16
17 #include "BufferView.h"
18 #include "CutAndPaste.h"
19 #include "FuncStatus.h"
20 #include "LColor.h"
21 #include "cursor.h"
22 #include "debug.h"
23 #include "funcrequest.h"
24 #include "gettext.h"
25 #include "undo.h"
26
27 #include "frontends/Painter.h"
28
29 #include "insets/mailinset.h"
30
31 #include "support/lstrings.h"
32
33 #include <sstream>
34
35
36 namespace lyx {
37
38 using support::bformat;
39
40 using std::endl;
41 using std::max;
42 using std::min;
43 using std::swap;
44
45 using std::string;
46 using std::auto_ptr;
47 using std::istream;
48 using std::istringstream;
49 using std::vector;
50
51
52 class GridInsetMailer : public MailInset {
53 public:
54         GridInsetMailer(InsetMathGrid & inset) : inset_(inset) {}
55         ///
56         virtual string const & name() const
57         {
58                 static string const theName = "tabular";
59                 return theName;
60         }
61         ///
62         virtual string const inset2string(Buffer const &) const
63         {
64                 odocstringstream data;
65                 //data << name() << " active_cell " << inset.getActCell() << '\n';
66                 data << from_utf8(name()) << " active_cell " << 0 << '\n';
67                 WriteStream ws(data);
68                 inset_.write(ws);
69                 return to_utf8(data.str());
70         }
71
72 protected:
73         InsetBase & inset() const { return inset_; }
74         InsetMathGrid & inset_;
75 };
76
77
78 void mathed_parse_normal(InsetMathGrid &, string const & argument);
79
80 namespace {
81
82 docstring verboseHLine(int n)
83 {
84         docstring res;
85         for (int i = 0; i < n; ++i)
86                 res += "\\hline";
87         if (n)
88                 res += ' ';
89         return res;
90 }
91
92
93 int extractInt(istream & is)
94 {
95         int num = 1;
96         is >> num;
97         return (num == 0) ? 1 : num;
98 }
99
100 }
101
102
103 //////////////////////////////////////////////////////////////
104
105
106 InsetMathGrid::CellInfo::CellInfo()
107         : dummy_(false)
108 {}
109
110
111
112
113 //////////////////////////////////////////////////////////////
114
115
116 InsetMathGrid::RowInfo::RowInfo()
117         : lines_(0), skip_(0)
118 {}
119
120
121
122 int InsetMathGrid::RowInfo::skipPixels() const
123 {
124         return crskip_.inBP();
125 }
126
127
128
129 //////////////////////////////////////////////////////////////
130
131
132 InsetMathGrid::ColInfo::ColInfo()
133         : align_('c'), lines_(0)
134 {}
135
136
137 //////////////////////////////////////////////////////////////
138
139
140 InsetMathGrid::InsetMathGrid(char v, docstring const & h)
141         : InsetMathNest(guessColumns(h)),
142           rowinfo_(2),
143           colinfo_(guessColumns(h) + 1),
144           cellinfo_(1 * guessColumns(h))
145 {
146         setDefaults();
147         valign(v);
148         halign(h);
149         //lyxerr << "created grid with " << ncols() << " columns" << endl;
150 }
151
152
153 InsetMathGrid::InsetMathGrid()
154         : InsetMathNest(1),
155           rowinfo_(1 + 1),
156                 colinfo_(1 + 1),
157                 cellinfo_(1),
158                 v_align_('c')
159 {
160         setDefaults();
161 }
162
163
164 InsetMathGrid::InsetMathGrid(col_type m, row_type n)
165         : InsetMathNest(m * n),
166           rowinfo_(n + 1),
167                 colinfo_(m + 1),
168                 cellinfo_(m * n),
169                 v_align_('c')
170 {
171         setDefaults();
172 }
173
174
175 InsetMathGrid::InsetMathGrid(col_type m, row_type n, char v, docstring const & h)
176         : InsetMathNest(m * n),
177           rowinfo_(n + 1),
178           colinfo_(m + 1),
179                 cellinfo_(m * n),
180                 v_align_(v)
181 {
182         setDefaults();
183         valign(v);
184         halign(h);
185 }
186
187
188 InsetMathGrid::~InsetMathGrid()
189 {
190         GridInsetMailer mailer(*this);
191         mailer.hideDialog();
192 }
193
194
195 auto_ptr<InsetBase> InsetMathGrid::doClone() const
196 {
197         return auto_ptr<InsetBase>(new InsetMathGrid(*this));
198 }
199
200
201 InsetMath::idx_type InsetMathGrid::index(row_type row, col_type col) const
202 {
203         return col + ncols() * row;
204 }
205
206
207 void InsetMathGrid::setDefaults()
208 {
209         if (ncols() <= 0)
210                 lyxerr << "positive number of columns expected" << endl;
211         //if (nrows() <= 0)
212         //      lyxerr << "positive number of rows expected" << endl;
213         for (col_type col = 0; col < ncols(); ++col) {
214                 colinfo_[col].align_ = defaultColAlign(col);
215                 colinfo_[col].skip_  = defaultColSpace(col);
216         }
217 }
218
219
220 void InsetMathGrid::halign(docstring const & hh)
221 {
222         col_type col = 0;
223         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it) {
224                 char_type c = *it;
225                 if (c == '|') {
226                         colinfo_[col].lines_++;
227                 } else if (col >= ncols()) {
228                         // Only '|' is allowed in the last dummy column
229                         break;
230                 } else if (c == 'c' || c == 'l' || c == 'r') {
231                         colinfo_[col].align_ = (char)c;
232                         ++col;
233                         colinfo_[col].lines_ = 0;
234                 } else {
235                         lyxerr << "unknown column separator: '" << c << "'" << endl;
236                 }
237         }
238
239 /*
240         col_type n = hh.size();
241         if (n > ncols())
242                 n = ncols();
243         for (col_type col = 0; col < n; ++col)
244                 colinfo_[col].align_ = hh[col];
245 */
246 }
247
248
249 InsetMathGrid::col_type InsetMathGrid::guessColumns(docstring const & hh) const
250 {
251         col_type col = 0;
252         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it)
253                 if (*it == 'c' || *it == 'l' || *it == 'r')
254                         ++col;
255         // let's have at least one column, even if we did not recognize its
256         // alignment
257         if (col == 0)
258                 col = 1;
259         return col;
260 }
261
262
263 void InsetMathGrid::halign(char h, col_type col)
264 {
265         colinfo_[col].align_ = h;
266 }
267
268
269 char InsetMathGrid::halign(col_type col) const
270 {
271         return colinfo_[col].align_;
272 }
273
274
275 docstring InsetMathGrid::halign() const
276 {
277         docstring res;
278         for (col_type col = 0; col < ncols(); ++col) {
279                 res += docstring(colinfo_[col].lines_, '|');
280                 res += colinfo_[col].align_;
281         }
282         return res + docstring(colinfo_[ncols()].lines_, '|');
283 }
284
285
286 void InsetMathGrid::valign(char c)
287 {
288         v_align_ = c;
289 }
290
291
292 char InsetMathGrid::valign() const
293 {
294         return v_align_;
295 }
296
297
298 InsetMathGrid::col_type InsetMathGrid::ncols() const
299 {
300         return colinfo_.size() - 1;
301 }
302
303
304 InsetMathGrid::row_type InsetMathGrid::nrows() const
305 {
306         return rowinfo_.size() - 1;
307 }
308
309
310 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
311 {
312         return idx % ncols();
313 }
314
315
316 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
317 {
318         return idx / ncols();
319 }
320
321
322 void InsetMathGrid::vcrskip(LyXLength const & crskip, row_type row)
323 {
324         rowinfo_[row].crskip_ = crskip;
325 }
326
327
328 LyXLength InsetMathGrid::vcrskip(row_type row) const
329 {
330         return rowinfo_[row].crskip_;
331 }
332
333
334 void InsetMathGrid::metrics(MetricsInfo & mi) const
335 {
336         // let the cells adjust themselves
337         InsetMathNest::metrics(mi);
338
339         // compute absolute sizes of vertical structure
340         for (row_type row = 0; row < nrows(); ++row) {
341                 int asc  = 0;
342                 int desc = 0;
343                 for (col_type col = 0; col < ncols(); ++col) {
344                         MathArray const & c = cell(index(row, col));
345                         asc  = max(asc,  c.ascent());
346                         desc = max(desc, c.descent());
347                 }
348                 rowinfo_[row].ascent_  = asc;
349                 rowinfo_[row].descent_ = desc;
350         }
351         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
352         rowinfo_[nrows()].ascent_  = 0;
353         rowinfo_[nrows()].descent_ = 0;
354
355         // compute vertical offsets
356         rowinfo_[0].offset_ = 0;
357         for (row_type row = 1; row <= nrows(); ++row) {
358                 rowinfo_[row].offset_  =
359                         rowinfo_[row - 1].offset_  +
360                         rowinfo_[row - 1].descent_ +
361                         rowinfo_[row - 1].skipPixels() +
362                         rowsep() +
363                         rowinfo_[row].lines_ * hlinesep() +
364                         rowinfo_[row].ascent_;
365         }
366
367         // adjust vertical offset
368         int h = 0;
369         switch (v_align_) {
370                 case 't':
371                         h = 0;
372                         break;
373                 case 'b':
374                         h = rowinfo_[nrows() - 1].offset_;
375                         break;
376                 default:
377                         h = rowinfo_[nrows() - 1].offset_ / 2;
378         }
379         for (row_type row = 0; row <= nrows(); ++row)
380                 rowinfo_[row].offset_ -= h;
381
382
383         // compute absolute sizes of horizontal structure
384         for (col_type col = 0; col < ncols(); ++col) {
385                 int wid = 0;
386                 for (row_type row = 0; row < nrows(); ++row)
387                         wid = max(wid, cell(index(row, col)).width());
388                 colinfo_[col].width_ = wid;
389         }
390         colinfo_[ncols()].width_  = 0;
391
392         // compute horizontal offsets
393         colinfo_[0].offset_ = border();
394         for (col_type col = 1; col <= ncols(); ++col) {
395                 colinfo_[col].offset_ =
396                         colinfo_[col - 1].offset_ +
397                         colinfo_[col - 1].width_ +
398                         colinfo_[col - 1].skip_ +
399                         colsep() +
400                         colinfo_[col].lines_ * vlinesep();
401         }
402
403
404         dim_.wid   =   colinfo_[ncols() - 1].offset_
405                        + colinfo_[ncols() - 1].width_
406                  + vlinesep() * colinfo_[ncols()].lines_
407                        + border();
408
409         dim_.asc  = - rowinfo_[0].offset_
410                        + rowinfo_[0].ascent_
411                  + hlinesep() * rowinfo_[0].lines_
412                        + border();
413
414         dim_.des =   rowinfo_[nrows() - 1].offset_
415                        + rowinfo_[nrows() - 1].descent_
416                  + hlinesep() * rowinfo_[nrows()].lines_
417                        + border();
418
419
420 /*
421         // Increase ws_[i] for 'R' columns (except the first one)
422         for (int i = 1; i < nc_; ++i)
423                 if (align_[i] == 'R')
424                         ws_[i] += 10 * df_width;
425         // Increase ws_[i] for 'C' column
426         if (align_[0] == 'C')
427                 if (ws_[0] < 7 * workwidth / 8)
428                         ws_[0] = 7 * workwidth / 8;
429
430         // Adjust local tabs
431         width = colsep();
432         for (cxrow = row_.begin(); cxrow; ++cxrow) {
433                 int rg = COLSEP;
434                 int lf = 0;
435                 for (int i = 0; i < nc_; ++i) {
436                         bool isvoid = false;
437                         if (cxrow->getTab(i) <= 0) {
438                                 cxrow->setTab(i, df_width);
439                                 isvoid = true;
440                         }
441                         switch (align_[i]) {
442                         case 'l':
443                                 lf = 0;
444                                 break;
445                         case 'c':
446                                 lf = (ws_[i] - cxrow->getTab(i))/2;
447                                 break;
448                         case 'r':
449                         case 'R':
450                                 lf = ws_[i] - cxrow->getTab(i);
451                                 break;
452                         case 'C':
453                                 if (cxrow == row_.begin())
454                                         lf = 0;
455                                 else if (cxrow.is_last())
456                                         lf = ws_[i] - cxrow->getTab(i);
457                                 else
458                                         lf = (ws_[i] - cxrow->getTab(i))/2;
459                                 break;
460                         }
461                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
462                         cxrow->setTab(i, lf + rg);
463                         rg = ws_[i] - ww + colsep();
464                         if (cxrow == row_.begin())
465                                 width += ws_[i] + colsep();
466                 }
467                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
468         }
469 */
470         metricsMarkers2(dim_);
471 }
472
473
474 bool InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
475 {
476         dim = dim_;
477         metrics(mi);
478         if (dim_ == dim)
479                 return false;
480         dim = dim_;
481         return true;
482 }
483
484
485 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
486 {
487         drawWithMargin(pi, x, y, 0, 0);
488 }
489
490 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
491         int lmargin, int rmargin) const
492 {
493         for (idx_type idx = 0; idx < nargs(); ++idx)
494                 cell(idx).draw(pi, x + lmargin + cellXOffset(idx),
495                         y + cellYOffset(idx));
496
497         for (row_type row = 0; row <= nrows(); ++row)
498                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
499                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
500                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
501                         pi.pain.line(x + lmargin + 1, yy,
502                                      x + dim_.width() - rmargin - 1, yy,
503                                      LColor::foreground);
504                 }
505
506         for (col_type col = 0; col <= ncols(); ++col)
507                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
508                         int xx = x + lmargin + colinfo_[col].offset_
509                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
510                         pi.pain.line(xx, y - dim_.ascent() + 1,
511                                      xx, y + dim_.descent() - 1,
512                                      LColor::foreground);
513                 }
514         drawMarkers2(pi, x, y);
515 }
516
517
518 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
519 {
520         // let the cells adjust themselves
521         //InsetMathNest::metrics(mi);
522         for (idx_type i = 0; i < nargs(); ++i)
523                 cell(i).metricsT(mi, dim);
524
525         // compute absolute sizes of vertical structure
526         for (row_type row = 0; row < nrows(); ++row) {
527                 int asc  = 0;
528                 int desc = 0;
529                 for (col_type col = 0; col < ncols(); ++col) {
530                         MathArray const & c = cell(index(row, col));
531                         asc  = max(asc,  c.ascent());
532                         desc = max(desc, c.descent());
533                 }
534                 rowinfo_[row].ascent_  = asc;
535                 rowinfo_[row].descent_ = desc;
536         }
537         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
538         rowinfo_[nrows()].ascent_  = 0;
539         rowinfo_[nrows()].descent_ = 0;
540
541         // compute vertical offsets
542         rowinfo_[0].offset_ = 0;
543         for (row_type row = 1; row <= nrows(); ++row) {
544                 rowinfo_[row].offset_  =
545                         rowinfo_[row - 1].offset_  +
546                         rowinfo_[row - 1].descent_ +
547                         //rowinfo_[row - 1].skipPixels() +
548                         1 + //rowsep() +
549                         //rowinfo_[row].lines_ * hlinesep() +
550                         rowinfo_[row].ascent_;
551         }
552
553         // adjust vertical offset
554         int h = 0;
555         switch (v_align_) {
556                 case 't':
557                         h = 0;
558                         break;
559                 case 'b':
560                         h = rowinfo_[nrows() - 1].offset_;
561                         break;
562                 default:
563                         h = rowinfo_[nrows() - 1].offset_ / 2;
564         }
565         for (row_type row = 0; row <= nrows(); ++row)
566                 rowinfo_[row].offset_ -= h;
567
568
569         // compute absolute sizes of horizontal structure
570         for (col_type col = 0; col < ncols(); ++col) {
571                 int wid = 0;
572                 for (row_type row = 0; row < nrows(); ++row)
573                         wid = max(wid, cell(index(row, col)).width());
574                 colinfo_[col].width_ = wid;
575         }
576         colinfo_[ncols()].width_  = 0;
577
578         // compute horizontal offsets
579         colinfo_[0].offset_ = border();
580         for (col_type col = 1; col <= ncols(); ++col) {
581                 colinfo_[col].offset_ =
582                         colinfo_[col - 1].offset_ +
583                         colinfo_[col - 1].width_ +
584                         colinfo_[col - 1].skip_ +
585                         1 ; //colsep() +
586                         //colinfo_[col].lines_ * vlinesep();
587         }
588
589
590         dim.wid  =  colinfo_[ncols() - 1].offset_
591                        + colinfo_[ncols() - 1].width_
592                  //+ vlinesep() * colinfo_[ncols()].lines_
593                        + 2;
594
595         dim.asc  = -rowinfo_[0].offset_
596                        + rowinfo_[0].ascent_
597                  //+ hlinesep() * rowinfo_[0].lines_
598                        + 1;
599
600         dim.des  =  rowinfo_[nrows() - 1].offset_
601                        + rowinfo_[nrows() - 1].descent_
602                  //+ hlinesep() * rowinfo_[nrows()].lines_
603                        + 1;
604 }
605
606
607 void InsetMathGrid::drawT(TextPainter & pain, int x, int y) const
608 {
609         for (idx_type idx = 0; idx < nargs(); ++idx)
610                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
611 }
612
613
614 docstring InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) const
615 {
616         docstring eol;
617
618         if (!rowinfo_[row].crskip_.zero())
619                 eol += '[' + from_utf8(rowinfo_[row].crskip_.asLatexString()) + ']';
620
621         // make sure an upcoming '[' does not break anything
622         if (row + 1 < nrows()) {
623                 MathArray const & c = cell(index(row + 1, 0));
624                 if (c.size() && c.front()->getChar() == '[')
625                         //eol += "[0pt]";
626                         eol += "{}";
627         }
628
629         // only add \\ if necessary
630         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !emptyline))
631                 return docstring();
632
633         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
634 }
635
636
637 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
638 {
639         if (col + 1 == lastcol)
640                 return docstring();
641         return from_ascii(" & ");
642 }
643
644
645 void InsetMathGrid::addRow(row_type row)
646 {
647         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
648         cells_.insert
649                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathArray());
650         cellinfo_.insert
651                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
652 }
653
654
655 void InsetMathGrid::appendRow()
656 {
657         rowinfo_.push_back(RowInfo());
658         //cells_.insert(cells_.end(), ncols(), MathArray());
659         for (col_type col = 0; col < ncols(); ++col) {
660                 cells_.push_back(cells_type::value_type());
661                 cellinfo_.push_back(CellInfo());
662         }
663 }
664
665
666 void InsetMathGrid::delRow(row_type row)
667 {
668         if (nrows() == 1)
669                 return;
670
671         cells_type::iterator it = cells_.begin() + row * ncols();
672         cells_.erase(it, it + ncols());
673
674         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
675         cellinfo_.erase(jt, jt + ncols());
676
677         rowinfo_.erase(rowinfo_.begin() + row);
678 }
679
680
681 void InsetMathGrid::copyRow(row_type row)
682 {
683         addRow(row);
684         for (col_type col = 0; col < ncols(); ++col)
685                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
686 }
687
688
689 void InsetMathGrid::swapRow(row_type row)
690 {
691         if (nrows() == 1)
692                 return;
693         if (row + 1 == nrows())
694                 --row;
695         for (col_type col = 0; col < ncols(); ++col)
696                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
697 }
698
699
700 void InsetMathGrid::addCol(col_type newcol)
701 {
702         const col_type nc = ncols();
703         const row_type nr = nrows();
704         cells_type new_cells((nc + 1) * nr);
705         vector<CellInfo> new_cellinfo((nc + 1) * nr);
706
707         for (row_type row = 0; row < nr; ++row)
708                 for (col_type col = 0; col < nc; ++col) {
709                         new_cells[row * (nc + 1) + col + (col > newcol)]
710                                 = cells_[row * nc + col];
711                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
712                                 = cellinfo_[row * nc + col];
713                 }
714         swap(cells_, new_cells);
715         swap(cellinfo_, new_cellinfo);
716
717         ColInfo inf;
718         inf.skip_  = defaultColSpace(newcol);
719         inf.align_ = defaultColAlign(newcol);
720         colinfo_.insert(colinfo_.begin() + newcol, inf);
721 }
722
723
724 void InsetMathGrid::delCol(col_type col)
725 {
726         if (ncols() == 1)
727                 return;
728
729         cells_type tmpcells;
730         vector<CellInfo> tmpcellinfo;
731         for (col_type i = 0; i < nargs(); ++i)
732                 if (i % ncols() != col) {
733                         tmpcells.push_back(cells_[i]);
734                         tmpcellinfo.push_back(cellinfo_[i]);
735                 }
736         swap(cells_, tmpcells);
737         swap(cellinfo_, tmpcellinfo);
738
739         colinfo_.erase(colinfo_.begin() + col);
740 }
741
742
743 void InsetMathGrid::copyCol(col_type col)
744 {
745         addCol(col);
746         for (row_type row = 0; row < nrows(); ++row)
747                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
748 }
749
750
751 void InsetMathGrid::swapCol(col_type col)
752 {
753         if (ncols() == 1)
754                 return;
755         if (col + 1 == ncols())
756                 --col;
757         for (row_type row = 0; row < nrows(); ++row)
758                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
759 }
760
761
762 int InsetMathGrid::cellXOffset(idx_type idx) const
763 {
764         col_type c = col(idx);
765         int x = colinfo_[c].offset_;
766         char align = colinfo_[c].align_;
767         if (align == 'r' || align == 'R')
768                 x += colinfo_[c].width_ - cell(idx).width();
769         if (align == 'c' || align == 'C')
770                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
771         return x;
772 }
773
774
775 int InsetMathGrid::cellYOffset(idx_type idx) const
776 {
777         return rowinfo_[row(idx)].offset_;
778 }
779
780
781 bool InsetMathGrid::idxUpDown(LCursor & cur, bool up) const
782 {
783         if (up) {
784                 if (cur.row() == 0)
785                         return false;
786                 cur.idx() -= ncols();
787         } else {
788                 if (cur.row() + 1 >= nrows())
789                         return false;
790                 cur.idx() += ncols();
791         }
792         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo(cur.bv()));
793         return true;
794 }
795
796
797 bool InsetMathGrid::idxLeft(LCursor & cur) const
798 {
799         // leave matrix if on the left hand edge
800         if (cur.col() == 0)
801                 return false;
802         --cur.idx();
803         cur.pos() = cur.lastpos();
804         return true;
805 }
806
807
808 bool InsetMathGrid::idxRight(LCursor & cur) const
809 {
810         // leave matrix if on the right hand edge
811         if (cur.col() + 1 == ncols())
812                 return false;
813         ++cur.idx();
814         cur.pos() = 0;
815         return true;
816 }
817
818
819 bool InsetMathGrid::idxFirst(LCursor & cur) const
820 {
821         switch (v_align_) {
822                 case 't':
823                         cur.idx() = 0;
824                         break;
825                 case 'b':
826                         cur.idx() = (nrows() - 1) * ncols();
827                         break;
828                 default:
829                         cur.idx() = ((nrows() - 1) / 2) * ncols();
830         }
831         cur.pos() = 0;
832         return true;
833 }
834
835
836 bool InsetMathGrid::idxLast(LCursor & cur) const
837 {
838         switch (v_align_) {
839                 case 't':
840                         cur.idx() = ncols() - 1;
841                         break;
842                 case 'b':
843                         cur.idx() = nargs() - 1;
844                         break;
845                 default:
846                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
847         }
848         cur.pos() = cur.lastpos();
849         return true;
850 }
851
852
853 bool InsetMathGrid::idxDelete(idx_type & idx)
854 {
855         // nothing to do if we have just one row
856         if (nrows() == 1)
857                 return false;
858
859         // nothing to do if we are in the middle of the last row of the inset
860         if (idx + ncols() > nargs())
861                 return false;
862
863         // try to delete entire sequence of ncols() empty cells if possible
864         for (idx_type i = idx; i < idx + ncols(); ++i)
865                 if (cell(i).size())
866                         return false;
867
868         // move cells if necessary
869         for (idx_type i = index(row(idx), 0); i < idx; ++i)
870                 swap(cell(i), cell(i + ncols()));
871
872         delRow(row(idx));
873
874         if (idx >= nargs())
875                 idx = nargs() - 1;
876
877         // undo effect of Ctrl-Tab (i.e. pull next cell)
878         //if (idx + 1 != nargs())
879         //      cell(idx).swap(cell(idx + 1));
880
881         // we handled the event..
882         return true;
883 }
884
885
886 // reimplement old behaviour when pressing Delete in the last position
887 // of a cell
888 void InsetMathGrid::idxGlue(idx_type idx)
889 {
890         col_type c = col(idx);
891         if (c + 1 == ncols()) {
892                 if (row(idx) + 1 != nrows()) {
893                         for (col_type cc = 0; cc < ncols(); ++cc)
894                                 cell(idx).append(cell(idx + cc + 1));
895                         delRow(row(idx) + 1);
896                 }
897         } else {
898                 cell(idx).append(cell(idx + 1));
899                 for (col_type cc = c + 2; cc < ncols(); ++cc)
900                         cell(idx - c + cc - 1) = cell(idx - c + cc);
901                 cell(idx - c + ncols() - 1).clear();
902         }
903 }
904
905
906 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
907 {
908         return rowinfo_[row];
909 }
910
911
912 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
913 {
914         return rowinfo_[row];
915 }
916
917
918 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
919 {
920         row_type const ri = row(idx);
921         row_type const r1 = min(row(from), row(to));
922         row_type const r2 = max(row(from), row(to));
923         col_type const ci = col(idx);
924         col_type const c1 = min(col(from), col(to));
925         col_type const c2 = max(col(from), col(to));
926         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
927 }
928
929
930
931 void InsetMathGrid::normalize(NormalStream & os) const
932 {
933         os << "[grid ";
934         for (row_type row = 0; row < nrows(); ++row) {
935                 os << "[row ";
936                 for (col_type col = 0; col < ncols(); ++col)
937                         os << "[cell " << cell(index(row, col)) << ']';
938                 os << ']';
939         }
940         os << ']';
941 }
942
943
944 void InsetMathGrid::mathmlize(MathStream & os) const
945 {
946         os << MTag("mtable");
947         for (row_type row = 0; row < nrows(); ++row) {
948                 os << MTag("mtr");
949                 for (col_type col = 0; col < ncols(); ++col)
950                         os << cell(index(row, col));
951                 os << ETag("mtr");
952         }
953         os << ETag("mtable");
954 }
955
956
957 void InsetMathGrid::write(WriteStream & os) const
958 {
959         docstring eol;
960         for (row_type row = 0; row < nrows(); ++row) {
961                 os << verboseHLine(rowinfo_[row].lines_);
962                 // don't write & and empty cells at end of line
963                 col_type lastcol = 0;
964                 bool emptyline = true;
965                 for (col_type col = 0; col < ncols(); ++col)
966                         if (!cell(index(row, col)).empty()) {
967                                 lastcol = col + 1;
968                                 emptyline = false;
969                         }
970                 for (col_type col = 0; col < lastcol; ++col)
971                         os << cell(index(row, col)) << eocString(col, lastcol);
972                 eol = eolString(row, emptyline, os.fragile());
973                 os << eol;
974                 // append newline only if line wasn't completely empty
975                 // and this was not the last line in the grid
976                 if (!emptyline && row + 1 < nrows())
977                         os << "\n";
978         }
979         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
980         if (!s.empty()) {
981                 if (eol.empty()) {
982                         if (os.fragile())
983                                 os << "\\protect";
984                         os << "\\\\";
985                 }
986                 os << s;
987         }
988 }
989
990
991 int InsetMathGrid::colsep() const
992 {
993         return 6;
994 }
995
996
997 int InsetMathGrid::rowsep() const
998 {
999         return 6;
1000 }
1001
1002
1003 int InsetMathGrid::hlinesep() const
1004 {
1005         return 3;
1006 }
1007
1008
1009 int InsetMathGrid::vlinesep() const
1010 {
1011         return 3;
1012 }
1013
1014
1015 int InsetMathGrid::border() const
1016 {
1017         return 1;
1018 }
1019
1020
1021 void InsetMathGrid::splitCell(LCursor & cur)
1022 {
1023         if (cur.idx() == cur.lastidx())
1024                 return;
1025         MathArray ar = cur.cell();
1026         ar.erase(0, cur.pos());
1027         cur.cell().erase(cur.pos(), cur.lastpos());
1028         ++cur.idx();
1029         cur.pos() = 0;
1030         cur.cell().insert(0, ar);
1031 }
1032
1033
1034 void InsetMathGrid::doDispatch(LCursor & cur, FuncRequest & cmd)
1035 {
1036         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1037         switch (cmd.action) {
1038
1039         case LFUN_MOUSE_RELEASE:
1040                 //if (cmd.button() == mouse_button::button3) {
1041                 //      GridInsetMailer(*this).showDialog();
1042                 //      return DispatchResult(true, true);
1043                 //}
1044                 InsetMathNest::doDispatch(cur, cmd);
1045                 break;
1046
1047         case LFUN_INSET_DIALOG_UPDATE:
1048                 GridInsetMailer(*this).updateDialog(&cur.bv());
1049                 break;
1050
1051         // insert file functions
1052         case LFUN_LINE_DELETE:
1053                 // FIXME: We use recordUndoInset when a change reflects more
1054                 // than one cell, because recordUndo does not work for
1055                 // multiple cells. Unfortunately this puts the cursor in front
1056                 // of the inset after undo. This is (especilally for large
1057                 // grids) annoying.
1058                 recordUndoInset(cur);
1059                 //autocorrect_ = false;
1060                 //macroModeClose();
1061                 //if (selection_) {
1062                 //      selDel();
1063                 //      break;
1064                 //}
1065                 if (nrows() > 1)
1066                         delRow(cur.row());
1067                 if (cur.idx() > cur.lastidx())
1068                         cur.idx() = cur.lastidx();
1069                 if (cur.pos() > cur.lastpos())
1070                         cur.pos() = cur.lastpos();
1071                 break;
1072
1073         case LFUN_CELL_SPLIT:
1074                 recordUndo(cur);
1075                 splitCell(cur);
1076                 break;
1077
1078         case LFUN_CELL_BACKWARD:
1079                 // See below.
1080                 cur.selection() = false;
1081                 if (!idxPrev(cur)) {
1082                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1083                         cur.undispatched();
1084                 }
1085                 break;
1086
1087         case LFUN_CELL_FORWARD:
1088                 // Can't handle selection by additional 'shift' as this is
1089                 // hard bound to LFUN_CELL_BACKWARD
1090                 cur.selection() = false;
1091                 if (!idxNext(cur)) {
1092                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1093                         cur.undispatched();
1094                 }
1095                 break;
1096
1097         case LFUN_BREAK_LINE: {
1098                 recordUndoInset(cur);
1099                 row_type const r = cur.row();
1100                 addRow(r);
1101
1102                 // split line
1103                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1104                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1105
1106                 // split cell
1107                 splitCell(cur);
1108                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1109                 if (cur.idx() > 0)
1110                         --cur.idx();
1111                 cur.pos() = cur.lastpos();
1112
1113                 //mathcursor->normalize();
1114                 //cmd = FuncRequest(LFUN_FINISHED_LEFT);
1115                 break;
1116         }
1117
1118         case LFUN_TABULAR_FEATURE: {
1119                 recordUndoInset(cur);
1120                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1121                 istringstream is(to_utf8(cmd.argument()));
1122                 string s;
1123                 is >> s;
1124                 if (s == "valign-top")
1125                         valign('t');
1126                 else if (s == "valign-middle")
1127                         valign('c');
1128                 else if (s == "valign-bottom")
1129                         valign('b');
1130                 else if (s == "align-left")
1131                         halign('l', cur.col());
1132                 else if (s == "align-right")
1133                         halign('r', cur.col());
1134                 else if (s == "align-center")
1135                         halign('c', cur.col());
1136                 else if (s == "append-row")
1137                         for (int i = 0, n = extractInt(is); i < n; ++i)
1138                                 addRow(cur.row());
1139                 else if (s == "delete-row") {
1140                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1141                                 delRow(cur.row());
1142                                 if (cur.idx() >= nargs())
1143                                         cur.idx() -= ncols();
1144                         }
1145                         cur.pos() = 0; // trick, see below
1146                 }
1147                 else if (s == "copy-row") {
1148                         // Here (as later) we save the cursor col/row
1149                         // in order to restore it after operation.
1150                         row_type const r = cur.row();
1151                         col_type const c = cur.col();
1152                         for (int i = 0, n = extractInt(is); i < n; ++i)
1153                                 copyRow(cur.row());
1154                         cur.idx() = index(r, c);
1155                 }
1156                 else if (s == "swap-row") {
1157                         swapRow(cur.row());
1158                         // Trick to suppress same-idx-means-different-cell
1159                         // assertion crash:
1160                         cur.pos() = 0;
1161                 }
1162                 else if (s == "add-hline-above")
1163                         rowinfo_[cur.row()].lines_++;
1164                 else if (s == "add-hline-below")
1165                         rowinfo_[cur.row()+1].lines_++;
1166                 else if (s == "delete-hline-above")
1167                         rowinfo_[cur.row()].lines_--;
1168                 else if (s == "delete-hline-below")
1169                         rowinfo_[cur.row()+1].lines_--;
1170                 else if (s == "append-column") {
1171                         row_type const r = cur.row();
1172                         col_type const c = cur.col();
1173                         for (int i = 0, n = extractInt(is); i < n; ++i)
1174                                 addCol(cur.col());
1175                         cur.idx() = index(r, c);
1176                 }
1177                 else if (s == "delete-column") {
1178                         row_type const r = cur.row();
1179                         col_type const c = cur.col();
1180                         for (int i = 0, n = extractInt(is); i < n; ++i)
1181                                 delCol(col(cur.idx()));
1182                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1183                         cur.pos() = 0; // trick, see above
1184                 }
1185                 else if (s == "copy-column") {
1186                         row_type const r = cur.row();
1187                         col_type const c = cur.col();
1188                         copyCol(cur.col());
1189                         cur.idx() = index(r, c);
1190                 }
1191                 else if (s == "swap-column") {
1192                         swapCol(cur.col());
1193                         cur.pos() = 0; // trick, see above
1194                 }
1195                 else if (s == "add-vline-left")
1196                         colinfo_[cur.col()].lines_++;
1197                 else if (s == "add-vline-right")
1198                         colinfo_[cur.col()+1].lines_++;
1199                 else if (s == "delete-vline-left")
1200                         colinfo_[cur.col()].lines_--;
1201                 else if (s == "delete-vline-right")
1202                         colinfo_[cur.col()+1].lines_--;
1203                 else {
1204                         cur.undispatched();
1205                         break;
1206                 }
1207                 lyxerr << "returning FINISHED_LEFT" << endl;
1208                 break;
1209         }
1210
1211         case LFUN_PASTE: {
1212                 cur.message(_("Paste"));
1213                 cap::replaceSelection(cur);
1214                 istringstream is(to_utf8(cmd.argument()));
1215                 int n = 0;
1216                 is >> n;
1217                 InsetMathGrid grid(1, 1);
1218                 // FIXME UNICODE
1219                 mathed_parse_normal(grid,
1220                         to_utf8(lyx::cap::getSelection(cur.buffer(), n)));
1221                 if (grid.nargs() == 1) {
1222                         // single cell/part of cell
1223                         recordUndo(cur);
1224                         cur.cell().insert(cur.pos(), grid.cell(0));
1225                         cur.pos() += grid.cell(0).size();
1226                 } else {
1227                         // multiple cells
1228                         recordUndoInset(cur);
1229                         col_type const numcols =
1230                                 min(grid.ncols(), ncols() - col(cur.idx()));
1231                         row_type const numrows =
1232                                 min(grid.nrows(), nrows() - cur.row());
1233                         for (row_type r = 0; r < numrows; ++r) {
1234                                 for (col_type c = 0; c < numcols; ++c) {
1235                                         idx_type i = index(r + cur.row(), c + col(cur.idx()));
1236                                         cell(i).insert(0, grid.cell(grid.index(r, c)));
1237                                 }
1238                                 // append the left over horizontal cells to the last column
1239                                 idx_type i = index(r + cur.row(), ncols() - 1);
1240                                 for (InsetMath::col_type c = numcols; c < grid.ncols(); ++c)
1241                                         cell(i).append(grid.cell(grid.index(r, c)));
1242                         }
1243                         // append the left over vertical cells to the last _cell_
1244                         idx_type i = nargs() - 1;
1245                         for (row_type r = numrows; r < grid.nrows(); ++r)
1246                                 for (col_type c = 0; c < grid.ncols(); ++c)
1247                                         cell(i).append(grid.cell(grid.index(r, c)));
1248                 }
1249                 cur.clearSelection(); // bug 393
1250                 cur.bv().switchKeyMap();
1251                 finishUndo();
1252                 break;
1253         }
1254
1255         case LFUN_LINE_BEGIN_SELECT:
1256         case LFUN_LINE_BEGIN:
1257         case LFUN_WORD_BACKWARD_SELECT:
1258         case LFUN_WORD_BACKWARD:
1259                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
1260                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
1261                 cur.macroModeClose();
1262                 if (cur.pos() != 0) {
1263                         cur.pos() = 0;
1264                 } else if (cur.idx() % cur.ncols() != 0) {
1265                         cur.idx() -= cur.idx() % cur.ncols();
1266                         cur.pos() = 0;
1267                 } else if (cur.idx() != 0) {
1268                         cur.idx() = 0;
1269                         cur.pos() = 0;
1270                 } else {
1271                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1272                         cur.undispatched();
1273                 }
1274                 break;
1275
1276         case LFUN_WORD_FORWARD_SELECT:
1277         case LFUN_WORD_FORWARD:
1278         case LFUN_LINE_END_SELECT:
1279         case LFUN_LINE_END:
1280                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
1281                                 cmd.action == LFUN_LINE_END_SELECT);
1282                 cur.macroModeClose();
1283                 cur.clearTargetX();
1284                 if (cur.pos() != cur.lastpos()) {
1285                         cur.pos() = cur.lastpos();
1286                 } else if ((cur.idx() + 1) % cur.ncols() != 0) {
1287                         cur.idx() += cur.ncols() - 1 - cur.idx() % cur.ncols();
1288                         cur.pos() = cur.lastpos();
1289                 } else if (cur.idx() != cur.lastidx()) {
1290                         cur.idx() = cur.lastidx();
1291                         cur.pos() = cur.lastpos();
1292                 } else {
1293                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1294                         cur.undispatched();
1295                 }
1296                 break;
1297
1298         default:
1299                 InsetMathNest::doDispatch(cur, cmd);
1300         }
1301 }
1302
1303
1304 bool InsetMathGrid::getStatus(LCursor & cur, FuncRequest const & cmd,
1305                 FuncStatus & status) const
1306 {
1307         switch (cmd.action) {
1308         case LFUN_TABULAR_FEATURE: {
1309                 string const s = to_utf8(cmd.argument());
1310                 if (nrows() <= 1 && (s == "delete-row" || s == "swap-row")) {
1311                         status.enabled(false);
1312                         status.message(from_utf8(N_("Only one row")));
1313                         return true;
1314                 }
1315                 if (ncols() <= 1 &&
1316                     (s == "delete-column" || s == "swap-column")) {
1317                         status.enabled(false);
1318                         status.message(from_utf8(N_("Only one column")));
1319                         return true;
1320                 }
1321                 if ((rowinfo_[cur.row()].lines_ == 0 &&
1322                      s == "delete-hline-above") ||
1323                     (rowinfo_[cur.row() + 1].lines_ == 0 &&
1324                      s == "delete-hline-below")) {
1325                         status.enabled(false);
1326                         status.message(from_utf8(N_("No hline to delete")));
1327                         return true;
1328                 }
1329
1330                 if ((colinfo_[cur.col()].lines_ == 0 &&
1331                      s == "delete-vline-left") ||
1332                     (colinfo_[cur.col() + 1].lines_ == 0 &&
1333                      s == "delete-vline-right")) {
1334                         status.enabled(false);
1335                         status.message(from_utf8(N_("No vline to delete")));
1336                         return true;
1337                 }
1338                 if (s == "valign-top" || s == "valign-middle" ||
1339                     s == "valign-bottom" || s == "align-left" ||
1340                     s == "align-right" || s == "align-center" ||
1341                     s == "append-row" || s == "delete-row" ||
1342                     s == "copy-row" || s == "swap-row" ||
1343                     s == "add-hline-above" || s == "add-hline-below" ||
1344                     s == "delete-hline-above" || s == "delete-hline-below" ||
1345                     s == "append-column" || s == "delete-column" ||
1346                     s == "copy-column" || s == "swap-column" ||
1347                     s == "add-vline-left" || s == "add-vline-right" ||
1348                     s == "delete-vline-left" || s == "delete-vline-right")
1349                         status.enabled(true);
1350                 else {
1351                         status.enabled(false);
1352                         status.message(bformat(
1353                                 from_utf8(N_("Unknown tabular feature '%1$s'")), lyx::from_ascii(s)));
1354                 }
1355
1356                 status.setOnOff(s == "align-left"    && halign(cur.col()) == 'l'
1357                            || s == "align-right"   && halign(cur.col()) == 'r'
1358                            || s == "align-center"  && halign(cur.col()) == 'c'
1359                            || s == "valign-top"    && valign() == 't'
1360                            || s == "valign-bottom" && valign() == 'b'
1361                            || s == "valign-middle" && valign() == 'm');
1362
1363 #if 0
1364                 // FIXME: What did this code do?
1365                 // Please check whether it is still needed!
1366                 // should be more precise
1367                 if (v_align_ == '\0') {
1368                         status.enable(true);
1369                         break;
1370                 }
1371                 if (cmd.argument().empty()) {
1372                         status.enable(false);
1373                         break;
1374                 }
1375                 if (!support::contains("tcb", cmd.argument()[0])) {
1376                         status.enable(false);
1377                         break;
1378                 }
1379                 status.setOnOff(cmd.argument()[0] == v_align_);
1380                 status.enabled(true);
1381 #endif
1382                 return true;
1383         }
1384
1385         case LFUN_CELL_SPLIT:
1386                 status.enabled(true);
1387                 return true;
1388
1389         case LFUN_CELL_BACKWARD:
1390         case LFUN_CELL_FORWARD:
1391                 status.enabled(true);
1392                 return true;
1393
1394         default:
1395                 return InsetMathNest::getStatus(cur, cmd, status);
1396         }
1397 }
1398
1399
1400 } // namespace lyx