]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathGrid.cpp
Rename files in src/mathed and src/graphics from .C to .cpp, step 2
[lyx.git] / src / mathed / InsetMathGrid.cpp
1 /**
2  * \file InsetMathGrid.cpp
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/Clipboard.h"
29 #include "frontends/Painter.h"
30
31 #include "insets/MailInset.h"
32
33 #include "support/lstrings.h"
34
35 #include <sstream>
36
37
38 namespace lyx {
39
40 using support::bformat;
41
42 using std::endl;
43 using std::max;
44 using std::min;
45 using std::swap;
46
47 using std::string;
48 using std::auto_ptr;
49 using std::istream;
50 using std::istringstream;
51 using std::vector;
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), allow_pagebreak_(true)
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 auto_ptr<InsetBase> InsetMathGrid::doClone() const
188 {
189         return auto_ptr<InsetBase>(new InsetMathGrid(*this));
190 }
191
192
193 InsetMath::idx_type InsetMathGrid::index(row_type row, col_type col) const
194 {
195         return col + ncols() * row;
196 }
197
198
199 void InsetMathGrid::setDefaults()
200 {
201         if (ncols() <= 0)
202                 lyxerr << "positive number of columns expected" << endl;
203         //if (nrows() <= 0)
204         //      lyxerr << "positive number of rows expected" << endl;
205         for (col_type col = 0; col < ncols(); ++col) {
206                 colinfo_[col].align_ = defaultColAlign(col);
207                 colinfo_[col].skip_  = defaultColSpace(col);
208         }
209 }
210
211
212 void InsetMathGrid::halign(docstring const & hh)
213 {
214         col_type col = 0;
215         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it) {
216                 char_type c = *it;
217                 if (c == '|') {
218                         colinfo_[col].lines_++;
219                 } else if (col >= ncols()) {
220                         // Only '|' is allowed in the last dummy column
221                         break;
222                 } else if (c == 'c' || c == 'l' || c == 'r') {
223                         colinfo_[col].align_ = (char)c;
224                         ++col;
225                         colinfo_[col].lines_ = 0;
226                 } else {
227                         lyxerr << "unknown column separator: '" << c << "'" << endl;
228                 }
229         }
230
231 /*
232         col_type n = hh.size();
233         if (n > ncols())
234                 n = ncols();
235         for (col_type col = 0; col < n; ++col)
236                 colinfo_[col].align_ = hh[col];
237 */
238 }
239
240
241 InsetMathGrid::col_type InsetMathGrid::guessColumns(docstring const & hh) const
242 {
243         col_type col = 0;
244         for (docstring::const_iterator it = hh.begin(); it != hh.end(); ++it)
245                 if (*it == 'c' || *it == 'l' || *it == 'r')
246                         ++col;
247         // let's have at least one column, even if we did not recognize its
248         // alignment
249         if (col == 0)
250                 col = 1;
251         return col;
252 }
253
254
255 void InsetMathGrid::halign(char h, col_type col)
256 {
257         colinfo_[col].align_ = h;
258 }
259
260
261 char InsetMathGrid::halign(col_type col) const
262 {
263         return colinfo_[col].align_;
264 }
265
266
267 docstring InsetMathGrid::halign() const
268 {
269         docstring res;
270         for (col_type col = 0; col < ncols(); ++col) {
271                 res += docstring(colinfo_[col].lines_, '|');
272                 res += colinfo_[col].align_;
273         }
274         return res + docstring(colinfo_[ncols()].lines_, '|');
275 }
276
277
278 void InsetMathGrid::valign(char c)
279 {
280         v_align_ = c;
281 }
282
283
284 char InsetMathGrid::valign() const
285 {
286         return v_align_;
287 }
288
289
290 InsetMathGrid::col_type InsetMathGrid::ncols() const
291 {
292         return colinfo_.size() - 1;
293 }
294
295
296 InsetMathGrid::row_type InsetMathGrid::nrows() const
297 {
298         return rowinfo_.size() - 1;
299 }
300
301
302 InsetMathGrid::col_type InsetMathGrid::col(idx_type idx) const
303 {
304         return idx % ncols();
305 }
306
307
308 InsetMathGrid::row_type InsetMathGrid::row(idx_type idx) const
309 {
310         return idx / ncols();
311 }
312
313
314 void InsetMathGrid::vcrskip(LyXLength const & crskip, row_type row)
315 {
316         rowinfo_[row].crskip_ = crskip;
317 }
318
319
320 LyXLength InsetMathGrid::vcrskip(row_type row) const
321 {
322         return rowinfo_[row].crskip_;
323 }
324
325
326 void InsetMathGrid::metrics(MetricsInfo & mi) const
327 {
328         // let the cells adjust themselves
329         InsetMathNest::metrics(mi);
330
331         // compute absolute sizes of vertical structure
332         for (row_type row = 0; row < nrows(); ++row) {
333                 int asc  = 0;
334                 int desc = 0;
335                 for (col_type col = 0; col < ncols(); ++col) {
336                         MathArray const & c = cell(index(row, col));
337                         asc  = max(asc,  c.ascent());
338                         desc = max(desc, c.descent());
339                 }
340                 rowinfo_[row].ascent_  = asc;
341                 rowinfo_[row].descent_ = desc;
342         }
343         rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
344         rowinfo_[nrows()].ascent_  = 0;
345         rowinfo_[nrows()].descent_ = 0;
346
347         // compute vertical offsets
348         rowinfo_[0].offset_ = 0;
349         for (row_type row = 1; row <= nrows(); ++row) {
350                 rowinfo_[row].offset_  =
351                         rowinfo_[row - 1].offset_  +
352                         rowinfo_[row - 1].descent_ +
353                         rowinfo_[row - 1].skipPixels() +
354                         rowsep() +
355                         rowinfo_[row].lines_ * hlinesep() +
356                         rowinfo_[row].ascent_;
357         }
358
359         // adjust vertical offset
360         int h = 0;
361         switch (v_align_) {
362                 case 't':
363                         h = 0;
364                         break;
365                 case 'b':
366                         h = rowinfo_[nrows() - 1].offset_;
367                         break;
368                 default:
369                         h = rowinfo_[nrows() - 1].offset_ / 2;
370         }
371         for (row_type row = 0; row <= nrows(); ++row)
372                 rowinfo_[row].offset_ -= h;
373
374
375         // compute absolute sizes of horizontal structure
376         for (col_type col = 0; col < ncols(); ++col) {
377                 int wid = 0;
378                 for (row_type row = 0; row < nrows(); ++row)
379                         wid = max(wid, cell(index(row, col)).width());
380                 colinfo_[col].width_ = wid;
381         }
382         colinfo_[ncols()].width_  = 0;
383
384         // compute horizontal offsets
385         colinfo_[0].offset_ = border();
386         for (col_type col = 1; col <= ncols(); ++col) {
387                 colinfo_[col].offset_ =
388                         colinfo_[col - 1].offset_ +
389                         colinfo_[col - 1].width_ +
390                         colinfo_[col - 1].skip_ +
391                         colsep() +
392                         colinfo_[col].lines_ * vlinesep();
393         }
394
395
396         dim_.wid   =   colinfo_[ncols() - 1].offset_
397                        + colinfo_[ncols() - 1].width_
398                  + vlinesep() * colinfo_[ncols()].lines_
399                        + border();
400
401         dim_.asc  = - rowinfo_[0].offset_
402                        + rowinfo_[0].ascent_
403                  + hlinesep() * rowinfo_[0].lines_
404                        + border();
405
406         dim_.des =   rowinfo_[nrows() - 1].offset_
407                        + rowinfo_[nrows() - 1].descent_
408                  + hlinesep() * rowinfo_[nrows()].lines_
409                        + border();
410
411
412 /*
413         // Increase ws_[i] for 'R' columns (except the first one)
414         for (int i = 1; i < nc_; ++i)
415                 if (align_[i] == 'R')
416                         ws_[i] += 10 * df_width;
417         // Increase ws_[i] for 'C' column
418         if (align_[0] == 'C')
419                 if (ws_[0] < 7 * workwidth / 8)
420                         ws_[0] = 7 * workwidth / 8;
421
422         // Adjust local tabs
423         width = colsep();
424         for (cxrow = row_.begin(); cxrow; ++cxrow) {
425                 int rg = COLSEP;
426                 int lf = 0;
427                 for (int i = 0; i < nc_; ++i) {
428                         bool isvoid = false;
429                         if (cxrow->getTab(i) <= 0) {
430                                 cxrow->setTab(i, df_width);
431                                 isvoid = true;
432                         }
433                         switch (align_[i]) {
434                         case 'l':
435                                 lf = 0;
436                                 break;
437                         case 'c':
438                                 lf = (ws_[i] - cxrow->getTab(i))/2;
439                                 break;
440                         case 'r':
441                         case 'R':
442                                 lf = ws_[i] - cxrow->getTab(i);
443                                 break;
444                         case 'C':
445                                 if (cxrow == row_.begin())
446                                         lf = 0;
447                                 else if (cxrow.is_last())
448                                         lf = ws_[i] - cxrow->getTab(i);
449                                 else
450                                         lf = (ws_[i] - cxrow->getTab(i))/2;
451                                 break;
452                         }
453                         int const ww = (isvoid) ? lf : lf + cxrow->getTab(i);
454                         cxrow->setTab(i, lf + rg);
455                         rg = ws_[i] - ww + colsep();
456                         if (cxrow == row_.begin())
457                                 width += ws_[i] + colsep();
458                 }
459                 cxrow->setBaseline(cxrow->getBaseline() - ascent);
460         }
461 */
462         metricsMarkers2(dim_);
463 }
464
465
466 bool InsetMathGrid::metrics(MetricsInfo & mi, Dimension & dim) const
467 {
468         dim = dim_;
469         metrics(mi);
470         if (dim_ == dim)
471                 return false;
472         dim = dim_;
473         return true;
474 }
475
476
477 void InsetMathGrid::draw(PainterInfo & pi, int x, int y) const
478 {
479         drawWithMargin(pi, x, y, 0, 0);
480 }
481
482 void InsetMathGrid::drawWithMargin(PainterInfo & pi, int x, int y,
483         int lmargin, int rmargin) const
484 {
485         for (idx_type idx = 0; idx < nargs(); ++idx)
486                 cell(idx).draw(pi, x + lmargin + cellXOffset(idx),
487                         y + cellYOffset(idx));
488
489         for (row_type row = 0; row <= nrows(); ++row)
490                 for (unsigned int i = 0; i < rowinfo_[row].lines_; ++i) {
491                         int yy = y + rowinfo_[row].offset_ - rowinfo_[row].ascent_
492                                 - i * hlinesep() - hlinesep()/2 - rowsep()/2;
493                         pi.pain.line(x + lmargin + 1, yy,
494                                      x + dim_.width() - rmargin - 1, yy,
495                                      LColor::foreground);
496                 }
497
498         for (col_type col = 0; col <= ncols(); ++col)
499                 for (unsigned int i = 0; i < colinfo_[col].lines_; ++i) {
500                         int xx = x + lmargin + colinfo_[col].offset_
501                                 - i * vlinesep() - vlinesep()/2 - colsep()/2;
502                         pi.pain.line(xx, y - dim_.ascent() + 1,
503                                      xx, y + dim_.descent() - 1,
504                                      LColor::foreground);
505                 }
506         drawMarkers2(pi, x, y);
507 }
508
509
510 void InsetMathGrid::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
511 {
512         // let the cells adjust themselves
513         //InsetMathNest::metrics(mi);
514         for (idx_type i = 0; i < nargs(); ++i)
515                 cell(i).metricsT(mi, dim);
516
517         // compute absolute sizes of vertical structure
518         for (row_type row = 0; row < nrows(); ++row) {
519                 int asc  = 0;
520                 int desc = 0;
521                 for (col_type col = 0; col < ncols(); ++col) {
522                         MathArray const & c = cell(index(row, col));
523                         asc  = max(asc,  c.ascent());
524                         desc = max(desc, c.descent());
525                 }
526                 rowinfo_[row].ascent_  = asc;
527                 rowinfo_[row].descent_ = desc;
528         }
529         //rowinfo_[0].ascent_       += hlinesep() * rowinfo_[0].lines_;
530         rowinfo_[nrows()].ascent_  = 0;
531         rowinfo_[nrows()].descent_ = 0;
532
533         // compute vertical offsets
534         rowinfo_[0].offset_ = 0;
535         for (row_type row = 1; row <= nrows(); ++row) {
536                 rowinfo_[row].offset_  =
537                         rowinfo_[row - 1].offset_  +
538                         rowinfo_[row - 1].descent_ +
539                         //rowinfo_[row - 1].skipPixels() +
540                         1 + //rowsep() +
541                         //rowinfo_[row].lines_ * hlinesep() +
542                         rowinfo_[row].ascent_;
543         }
544
545         // adjust vertical offset
546         int h = 0;
547         switch (v_align_) {
548                 case 't':
549                         h = 0;
550                         break;
551                 case 'b':
552                         h = rowinfo_[nrows() - 1].offset_;
553                         break;
554                 default:
555                         h = rowinfo_[nrows() - 1].offset_ / 2;
556         }
557         for (row_type row = 0; row <= nrows(); ++row)
558                 rowinfo_[row].offset_ -= h;
559
560
561         // compute absolute sizes of horizontal structure
562         for (col_type col = 0; col < ncols(); ++col) {
563                 int wid = 0;
564                 for (row_type row = 0; row < nrows(); ++row)
565                         wid = max(wid, cell(index(row, col)).width());
566                 colinfo_[col].width_ = wid;
567         }
568         colinfo_[ncols()].width_  = 0;
569
570         // compute horizontal offsets
571         colinfo_[0].offset_ = border();
572         for (col_type col = 1; col <= ncols(); ++col) {
573                 colinfo_[col].offset_ =
574                         colinfo_[col - 1].offset_ +
575                         colinfo_[col - 1].width_ +
576                         colinfo_[col - 1].skip_ +
577                         1 ; //colsep() +
578                         //colinfo_[col].lines_ * vlinesep();
579         }
580
581
582         dim.wid  =  colinfo_[ncols() - 1].offset_
583                        + colinfo_[ncols() - 1].width_
584                  //+ vlinesep() * colinfo_[ncols()].lines_
585                        + 2;
586
587         dim.asc  = -rowinfo_[0].offset_
588                        + rowinfo_[0].ascent_
589                  //+ hlinesep() * rowinfo_[0].lines_
590                        + 1;
591
592         dim.des  =  rowinfo_[nrows() - 1].offset_
593                        + rowinfo_[nrows() - 1].descent_
594                  //+ hlinesep() * rowinfo_[nrows()].lines_
595                        + 1;
596 }
597
598
599 void InsetMathGrid::drawT(TextPainter & pain, int x, int y) const
600 {
601         for (idx_type idx = 0; idx < nargs(); ++idx)
602                 cell(idx).drawT(pain, x + cellXOffset(idx), y + cellYOffset(idx));
603 }
604
605
606 docstring InsetMathGrid::eolString(row_type row, bool emptyline, bool fragile) const
607 {
608         docstring eol;
609
610         if (!rowinfo_[row].crskip_.zero())
611                 eol += '[' + from_utf8(rowinfo_[row].crskip_.asLatexString()) + ']';
612         else if(!rowinfo_[row].allow_pagebreak_)
613                 eol += '*';
614
615         // make sure an upcoming '[' does not break anything
616         if (row + 1 < nrows()) {
617                 MathArray const & c = cell(index(row + 1, 0));
618                 if (c.size() && c.front()->getChar() == '[')
619                         //eol += "[0pt]";
620                         eol += "{}";
621         }
622
623         // only add \\ if necessary
624         if (eol.empty() && row + 1 == nrows() && (nrows() == 1 || !emptyline))
625                 return docstring();
626
627         return (fragile ? "\\protect\\\\" : "\\\\") + eol;
628 }
629
630
631 docstring InsetMathGrid::eocString(col_type col, col_type lastcol) const
632 {
633         if (col + 1 == lastcol)
634                 return docstring();
635         return from_ascii(" & ");
636 }
637
638
639 void InsetMathGrid::addRow(row_type row)
640 {
641         rowinfo_.insert(rowinfo_.begin() + row + 1, RowInfo());
642         cells_.insert
643                 (cells_.begin() + (row + 1) * ncols(), ncols(), MathArray());
644         cellinfo_.insert
645                 (cellinfo_.begin() + (row + 1) * ncols(), ncols(), CellInfo());
646 }
647
648
649 void InsetMathGrid::appendRow()
650 {
651         rowinfo_.push_back(RowInfo());
652         //cells_.insert(cells_.end(), ncols(), MathArray());
653         for (col_type col = 0; col < ncols(); ++col) {
654                 cells_.push_back(cells_type::value_type());
655                 cellinfo_.push_back(CellInfo());
656         }
657 }
658
659
660 void InsetMathGrid::delRow(row_type row)
661 {
662         if (nrows() == 1)
663                 return;
664
665         cells_type::iterator it = cells_.begin() + row * ncols();
666         cells_.erase(it, it + ncols());
667
668         vector<CellInfo>::iterator jt = cellinfo_.begin() + row * ncols();
669         cellinfo_.erase(jt, jt + ncols());
670
671         rowinfo_.erase(rowinfo_.begin() + row);
672 }
673
674
675 void InsetMathGrid::copyRow(row_type row)
676 {
677         addRow(row);
678         for (col_type col = 0; col < ncols(); ++col)
679                 cells_[(row + 1) * ncols() + col] = cells_[row * ncols() + col];
680 }
681
682
683 void InsetMathGrid::swapRow(row_type row)
684 {
685         if (nrows() == 1)
686                 return;
687         if (row + 1 == nrows())
688                 --row;
689         for (col_type col = 0; col < ncols(); ++col)
690                 swap(cells_[row * ncols() + col], cells_[(row + 1) * ncols() + col]);
691 }
692
693
694 void InsetMathGrid::addCol(col_type newcol)
695 {
696         const col_type nc = ncols();
697         const row_type nr = nrows();
698         cells_type new_cells((nc + 1) * nr);
699         vector<CellInfo> new_cellinfo((nc + 1) * nr);
700
701         for (row_type row = 0; row < nr; ++row)
702                 for (col_type col = 0; col < nc; ++col) {
703                         new_cells[row * (nc + 1) + col + (col > newcol)]
704                                 = cells_[row * nc + col];
705                         new_cellinfo[row * (nc + 1) + col + (col > newcol)]
706                                 = cellinfo_[row * nc + col];
707                 }
708         swap(cells_, new_cells);
709         swap(cellinfo_, new_cellinfo);
710
711         ColInfo inf;
712         inf.skip_  = defaultColSpace(newcol);
713         inf.align_ = defaultColAlign(newcol);
714         colinfo_.insert(colinfo_.begin() + newcol, inf);
715 }
716
717
718 void InsetMathGrid::delCol(col_type col)
719 {
720         if (ncols() == 1)
721                 return;
722
723         cells_type tmpcells;
724         vector<CellInfo> tmpcellinfo;
725         for (col_type i = 0; i < nargs(); ++i)
726                 if (i % ncols() != col) {
727                         tmpcells.push_back(cells_[i]);
728                         tmpcellinfo.push_back(cellinfo_[i]);
729                 }
730         swap(cells_, tmpcells);
731         swap(cellinfo_, tmpcellinfo);
732
733         colinfo_.erase(colinfo_.begin() + col);
734 }
735
736
737 void InsetMathGrid::copyCol(col_type col)
738 {
739         addCol(col);
740         for (row_type row = 0; row < nrows(); ++row)
741                 cells_[row * ncols() + col + 1] = cells_[row * ncols() + col];
742 }
743
744
745 void InsetMathGrid::swapCol(col_type col)
746 {
747         if (ncols() == 1)
748                 return;
749         if (col + 1 == ncols())
750                 --col;
751         for (row_type row = 0; row < nrows(); ++row)
752                 swap(cells_[row * ncols() + col], cells_[row * ncols() + col + 1]);
753 }
754
755
756 int InsetMathGrid::cellXOffset(idx_type idx) const
757 {
758         col_type c = col(idx);
759         int x = colinfo_[c].offset_;
760         char align = colinfo_[c].align_;
761         if (align == 'r' || align == 'R')
762                 x += colinfo_[c].width_ - cell(idx).width();
763         if (align == 'c' || align == 'C')
764                 x += (colinfo_[c].width_ - cell(idx).width()) / 2;
765         return x;
766 }
767
768
769 int InsetMathGrid::cellYOffset(idx_type idx) const
770 {
771         return rowinfo_[row(idx)].offset_;
772 }
773
774
775 bool InsetMathGrid::idxUpDown(LCursor & cur, bool up) const
776 {
777         if (up) {
778                 if (cur.row() == 0)
779                         return false;
780                 cur.idx() -= ncols();
781         } else {
782                 if (cur.row() + 1 >= nrows())
783                         return false;
784                 cur.idx() += ncols();
785         }
786         cur.pos() = cur.cell().x2pos(cur.x_target() - cur.cell().xo(cur.bv()));
787         return true;
788 }
789
790
791 bool InsetMathGrid::idxLeft(LCursor & cur) const
792 {
793         // leave matrix if on the left hand edge
794         if (cur.col() == 0)
795                 return false;
796         --cur.idx();
797         cur.pos() = cur.lastpos();
798         return true;
799 }
800
801
802 bool InsetMathGrid::idxRight(LCursor & cur) const
803 {
804         // leave matrix if on the right hand edge
805         if (cur.col() + 1 == ncols())
806                 return false;
807         ++cur.idx();
808         cur.pos() = 0;
809         return true;
810 }
811
812
813 bool InsetMathGrid::idxFirst(LCursor & cur) const
814 {
815         switch (v_align_) {
816                 case 't':
817                         cur.idx() = 0;
818                         break;
819                 case 'b':
820                         cur.idx() = (nrows() - 1) * ncols();
821                         break;
822                 default:
823                         cur.idx() = ((nrows() - 1) / 2) * ncols();
824         }
825         cur.pos() = 0;
826         return true;
827 }
828
829
830 bool InsetMathGrid::idxLast(LCursor & cur) const
831 {
832         switch (v_align_) {
833                 case 't':
834                         cur.idx() = ncols() - 1;
835                         break;
836                 case 'b':
837                         cur.idx() = nargs() - 1;
838                         break;
839                 default:
840                         cur.idx() = ((nrows() - 1) / 2 + 1) * ncols() - 1;
841         }
842         cur.pos() = cur.lastpos();
843         return true;
844 }
845
846
847 bool InsetMathGrid::idxDelete(idx_type & idx)
848 {
849         // nothing to do if we have just one row
850         if (nrows() == 1)
851                 return false;
852
853         // nothing to do if we are in the middle of the last row of the inset
854         if (idx + ncols() > nargs())
855                 return false;
856
857         // try to delete entire sequence of ncols() empty cells if possible
858         for (idx_type i = idx; i < idx + ncols(); ++i)
859                 if (cell(i).size())
860                         return false;
861
862         // move cells if necessary
863         for (idx_type i = index(row(idx), 0); i < idx; ++i)
864                 swap(cell(i), cell(i + ncols()));
865
866         delRow(row(idx));
867
868         if (idx >= nargs())
869                 idx = nargs() - 1;
870
871         // undo effect of Ctrl-Tab (i.e. pull next cell)
872         //if (idx + 1 != nargs())
873         //      cell(idx).swap(cell(idx + 1));
874
875         // we handled the event..
876         return true;
877 }
878
879
880 // reimplement old behaviour when pressing Delete in the last position
881 // of a cell
882 void InsetMathGrid::idxGlue(idx_type idx)
883 {
884         col_type c = col(idx);
885         if (c + 1 == ncols()) {
886                 if (row(idx) + 1 != nrows()) {
887                         for (col_type cc = 0; cc < ncols(); ++cc)
888                                 cell(idx).append(cell(idx + cc + 1));
889                         delRow(row(idx) + 1);
890                 }
891         } else {
892                 cell(idx).append(cell(idx + 1));
893                 for (col_type cc = c + 2; cc < ncols(); ++cc)
894                         cell(idx - c + cc - 1) = cell(idx - c + cc);
895                 cell(idx - c + ncols() - 1).clear();
896         }
897 }
898
899
900 InsetMathGrid::RowInfo const & InsetMathGrid::rowinfo(row_type row) const
901 {
902         return rowinfo_[row];
903 }
904
905
906 InsetMathGrid::RowInfo & InsetMathGrid::rowinfo(row_type row)
907 {
908         return rowinfo_[row];
909 }
910
911
912 bool InsetMathGrid::idxBetween(idx_type idx, idx_type from, idx_type to) const
913 {
914         row_type const ri = row(idx);
915         row_type const r1 = min(row(from), row(to));
916         row_type const r2 = max(row(from), row(to));
917         col_type const ci = col(idx);
918         col_type const c1 = min(col(from), col(to));
919         col_type const c2 = max(col(from), col(to));
920         return r1 <= ri && ri <= r2 && c1 <= ci && ci <= c2;
921 }
922
923
924
925 void InsetMathGrid::normalize(NormalStream & os) const
926 {
927         os << "[grid ";
928         for (row_type row = 0; row < nrows(); ++row) {
929                 os << "[row ";
930                 for (col_type col = 0; col < ncols(); ++col)
931                         os << "[cell " << cell(index(row, col)) << ']';
932                 os << ']';
933         }
934         os << ']';
935 }
936
937
938 void InsetMathGrid::mathmlize(MathStream & os) const
939 {
940         os << MTag("mtable");
941         for (row_type row = 0; row < nrows(); ++row) {
942                 os << MTag("mtr");
943                 for (col_type col = 0; col < ncols(); ++col)
944                         os << cell(index(row, col));
945                 os << ETag("mtr");
946         }
947         os << ETag("mtable");
948 }
949
950
951 void InsetMathGrid::write(WriteStream & os) const
952 {
953         docstring eol;
954         for (row_type row = 0; row < nrows(); ++row) {
955                 os << verboseHLine(rowinfo_[row].lines_);
956                 // don't write & and empty cells at end of line
957                 col_type lastcol = 0;
958                 bool emptyline = true;
959                 for (col_type col = 0; col < ncols(); ++col)
960                         if (!cell(index(row, col)).empty()) {
961                                 lastcol = col + 1;
962                                 emptyline = false;
963                         }
964                 for (col_type col = 0; col < lastcol; ++col)
965                         os << cell(index(row, col)) << eocString(col, lastcol);
966                 eol = eolString(row, emptyline, os.fragile());
967                 os << eol;
968                 // append newline only if line wasn't completely empty
969                 // and this was not the last line in the grid
970                 if (!emptyline && row + 1 < nrows())
971                         os << "\n";
972         }
973         docstring const s = verboseHLine(rowinfo_[nrows()].lines_);
974         if (!s.empty()) {
975                 if (eol.empty()) {
976                         if (os.fragile())
977                                 os << "\\protect";
978                         os << "\\\\";
979                 }
980                 os << s;
981         }
982 }
983
984
985 int InsetMathGrid::colsep() const
986 {
987         return 6;
988 }
989
990
991 int InsetMathGrid::rowsep() const
992 {
993         return 6;
994 }
995
996
997 int InsetMathGrid::hlinesep() const
998 {
999         return 3;
1000 }
1001
1002
1003 int InsetMathGrid::vlinesep() const
1004 {
1005         return 3;
1006 }
1007
1008
1009 int InsetMathGrid::border() const
1010 {
1011         return 1;
1012 }
1013
1014
1015 void InsetMathGrid::splitCell(LCursor & cur)
1016 {
1017         if (cur.idx() == cur.lastidx())
1018                 return;
1019         MathArray ar = cur.cell();
1020         ar.erase(0, cur.pos());
1021         cur.cell().erase(cur.pos(), cur.lastpos());
1022         ++cur.idx();
1023         cur.pos() = 0;
1024         cur.cell().insert(0, ar);
1025 }
1026
1027
1028 void InsetMathGrid::doDispatch(LCursor & cur, FuncRequest & cmd)
1029 {
1030         //lyxerr << "*** InsetMathGrid: request: " << cmd << endl;
1031         switch (cmd.action) {
1032
1033         case LFUN_MOUSE_RELEASE:
1034                 //if (cmd.button() == mouse_button::button3) {
1035                 //      GridInsetMailer(*this).showDialog();
1036                 //      return DispatchResult(true, true);
1037                 //}
1038                 InsetMathNest::doDispatch(cur, cmd);
1039                 break;
1040
1041         case LFUN_INSET_DIALOG_UPDATE:
1042                 GridInsetMailer(*this).updateDialog(&cur.bv());
1043                 break;
1044
1045         // insert file functions
1046         case LFUN_LINE_DELETE:
1047                 // FIXME: We use recordUndoInset when a change reflects more
1048                 // than one cell, because recordUndo does not work for
1049                 // multiple cells. Unfortunately this puts the cursor in front
1050                 // of the inset after undo. This is (especilally for large
1051                 // grids) annoying.
1052                 recordUndoInset(cur);
1053                 //autocorrect_ = false;
1054                 //macroModeClose();
1055                 //if (selection_) {
1056                 //      selDel();
1057                 //      break;
1058                 //}
1059                 if (nrows() > 1)
1060                         delRow(cur.row());
1061                 if (cur.idx() > cur.lastidx())
1062                         cur.idx() = cur.lastidx();
1063                 if (cur.pos() > cur.lastpos())
1064                         cur.pos() = cur.lastpos();
1065                 break;
1066
1067         case LFUN_CELL_SPLIT:
1068                 recordUndo(cur);
1069                 splitCell(cur);
1070                 break;
1071
1072         case LFUN_CELL_BACKWARD:
1073                 // See below.
1074                 cur.selection() = false;
1075                 if (!idxPrev(cur)) {
1076                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
1077                         cur.undispatched();
1078                 }
1079                 break;
1080
1081         case LFUN_CELL_FORWARD:
1082                 // Can't handle selection by additional 'shift' as this is
1083                 // hard bound to LFUN_CELL_BACKWARD
1084                 cur.selection() = false;
1085                 if (!idxNext(cur)) {
1086                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
1087                         cur.undispatched();
1088                 }
1089                 break;
1090
1091         case LFUN_BREAK_LINE: {
1092                 recordUndoInset(cur);
1093                 row_type const r = cur.row();
1094                 addRow(r);
1095
1096                 // split line
1097                 for (col_type c = col(cur.idx()) + 1; c < ncols(); ++c)
1098                         swap(cell(index(r, c)), cell(index(r + 1, c)));
1099
1100                 // split cell
1101                 splitCell(cur);
1102                 swap(cell(cur.idx()), cell(cur.idx() + ncols() - 1));
1103                 if (cur.idx() > 0)
1104                         --cur.idx();
1105                 cur.pos() = cur.lastpos();
1106
1107                 //mathcursor->normalize();
1108                 //cmd = FuncRequest(LFUN_FINISHED_LEFT);
1109                 break;
1110         }
1111
1112         case LFUN_TABULAR_FEATURE: {
1113                 recordUndoInset(cur);
1114                 //lyxerr << "handling tabular-feature " << to_utf8(cmd.argument()) << endl;
1115                 istringstream is(to_utf8(cmd.argument()));
1116                 string s;
1117                 is >> s;
1118                 if (s == "valign-top")
1119                         valign('t');
1120                 else if (s == "valign-middle")
1121                         valign('c');
1122                 else if (s == "valign-bottom")
1123                         valign('b');
1124                 else if (s == "align-left")
1125                         halign('l', cur.col());
1126                 else if (s == "align-right")
1127                         halign('r', cur.col());
1128                 else if (s == "align-center")
1129                         halign('c', cur.col());
1130                 else if (s == "append-row")
1131                         for (int i = 0, n = extractInt(is); i < n; ++i)
1132                                 addRow(cur.row());
1133                 else if (s == "delete-row") {
1134                         for (int i = 0, n = extractInt(is); i < n; ++i) {
1135                                 delRow(cur.row());
1136                                 if (cur.idx() >= nargs())
1137                                         cur.idx() -= ncols();
1138                         }
1139                         cur.pos() = 0; // trick, see below
1140                 }
1141                 else if (s == "copy-row") {
1142                         // Here (as later) we save the cursor col/row
1143                         // in order to restore it after operation.
1144                         row_type const r = cur.row();
1145                         col_type const c = cur.col();
1146                         for (int i = 0, n = extractInt(is); i < n; ++i)
1147                                 copyRow(cur.row());
1148                         cur.idx() = index(r, c);
1149                 }
1150                 else if (s == "swap-row") {
1151                         swapRow(cur.row());
1152                         // Trick to suppress same-idx-means-different-cell
1153                         // assertion crash:
1154                         cur.pos() = 0;
1155                 }
1156                 else if (s == "add-hline-above")
1157                         rowinfo_[cur.row()].lines_++;
1158                 else if (s == "add-hline-below")
1159                         rowinfo_[cur.row()+1].lines_++;
1160                 else if (s == "delete-hline-above")
1161                         rowinfo_[cur.row()].lines_--;
1162                 else if (s == "delete-hline-below")
1163                         rowinfo_[cur.row()+1].lines_--;
1164                 else if (s == "append-column") {
1165                         row_type const r = cur.row();
1166                         col_type const c = cur.col();
1167                         for (int i = 0, n = extractInt(is); i < n; ++i)
1168                                 addCol(cur.col());
1169                         cur.idx() = index(r, c);
1170                 }
1171                 else if (s == "delete-column") {
1172                         row_type const r = cur.row();
1173                         col_type const c = cur.col();
1174                         for (int i = 0, n = extractInt(is); i < n; ++i)
1175                                 delCol(col(cur.idx()));
1176                         cur.idx() = index(r, min(c, cur.ncols() - 1));
1177                         cur.pos() = 0; // trick, see above
1178                 }
1179                 else if (s == "copy-column") {
1180                         row_type const r = cur.row();
1181                         col_type const c = cur.col();
1182                         copyCol(cur.col());
1183                         cur.idx() = index(r, c);
1184                 }
1185                 else if (s == "swap-column") {
1186                         swapCol(cur.col());
1187                         cur.pos() = 0; // trick, see above
1188                 }
1189                 else if (s == "add-vline-left")
1190                         colinfo_[cur.col()].lines_++;
1191                 else if (s == "add-vline-right")
1192                         colinfo_[cur.col()+1].lines_++;
1193                 else if (s == "delete-vline-left")
1194                         colinfo_[cur.col()].lines_--;
1195                 else if (s == "delete-vline-right")
1196                         colinfo_[cur.col()+1].lines_--;
1197                 else {
1198                         cur.undispatched();
1199                         break;
1200                 }
1201                 lyxerr << "returning FINISHED_LEFT" << endl;
1202                 break;
1203         }
1204
1205         case LFUN_PASTE: {
1206                 cur.message(_("Paste"));
1207                 cap::replaceSelection(cur);
1208                 docstring topaste;
1209                 if (cmd.argument().empty() && !theClipboard().isInternal())
1210                         topaste = theClipboard().getAsText();
1211                 else {
1212                         idocstringstream is(cmd.argument());
1213                         int n = 0;
1214                         is >> n;
1215                         topaste = cap::getSelection(cur.buffer(), n);
1216                 }
1217                 InsetMathGrid grid(1, 1);
1218                 if (!topaste.empty())
1219                         mathed_parse_normal(grid, topaste);
1220
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