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