]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Replace home made temp file creation with safer (and cleaner) Qt' solution. Should...
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "InsetTabular.h"
21
22 #include "buffer_funcs.h"
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Counters.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "Language.h"
34 #include "LaTeXFeatures.h"
35 #include "Lexer.h"
36 #include "LyXFunc.h"
37 #include "LyXRC.h"
38 #include "MetricsInfo.h"
39 #include "OutputParams.h"
40 #include "paragraph_funcs.h"
41 #include "Paragraph.h"
42 #include "ParagraphParameters.h"
43 #include "ParIterator.h"
44 #include "TextClass.h"
45 #include "TextMetrics.h"
46
47 #include "frontends/Application.h"
48 #include "frontends/alert.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
52
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/FileName.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h"
60
61 #include <boost/scoped_ptr.hpp>
62
63 #include <sstream>
64 #include <iostream>
65 #include <limits>
66 #include <cstring>
67
68 using namespace std;
69 using namespace lyx::support;
70
71 using boost::shared_ptr;
72 using boost::dynamic_pointer_cast;
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horiz space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103 };
104
105
106 TabularFeature tabularFeature[] =
107 {
108         { Tabular::APPEND_ROW, "append-row" },
109         { Tabular::APPEND_COLUMN, "append-column" },
110         { Tabular::DELETE_ROW, "delete-row" },
111         { Tabular::DELETE_COLUMN, "delete-column" },
112         { Tabular::COPY_ROW, "copy-row" },
113         { Tabular::COPY_COLUMN, "copy-column" },
114         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top" },
115         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom" },
116         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left" },
117         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right" },
118         { Tabular::ALIGN_LEFT, "align-left" },
119         { Tabular::ALIGN_RIGHT, "align-right" },
120         { Tabular::ALIGN_CENTER, "align-center" },
121         { Tabular::ALIGN_BLOCK, "align-block" },
122         { Tabular::VALIGN_TOP, "valign-top" },
123         { Tabular::VALIGN_BOTTOM, "valign-bottom" },
124         { Tabular::VALIGN_MIDDLE, "valign-middle" },
125         { Tabular::M_ALIGN_LEFT, "m-align-left" },
126         { Tabular::M_ALIGN_RIGHT, "m-align-right" },
127         { Tabular::M_ALIGN_CENTER, "m-align-center" },
128         { Tabular::M_VALIGN_TOP, "m-valign-top" },
129         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom" },
130         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle" },
131         { Tabular::MULTICOLUMN, "multicolumn" },
132         { Tabular::SET_ALL_LINES, "set-all-lines" },
133         { Tabular::UNSET_ALL_LINES, "unset-all-lines" },
134         { Tabular::SET_LONGTABULAR, "set-longtabular" },
135         { Tabular::UNSET_LONGTABULAR, "unset-longtabular" },
136         { Tabular::SET_PWIDTH, "set-pwidth" },
137         { Tabular::SET_MPWIDTH, "set-mpwidth" },
138         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular" },
139         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular" },
140         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular" },
141         { Tabular::SET_ROTATE_CELL, "set-rotate-cell" },
142         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell" },
143         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell" },
144         { Tabular::SET_USEBOX, "set-usebox" },
145         { Tabular::SET_LTHEAD, "set-lthead" },
146         { Tabular::UNSET_LTHEAD, "unset-lthead" },
147         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead" },
148         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead" },
149         { Tabular::SET_LTFOOT, "set-ltfoot" },
150         { Tabular::UNSET_LTFOOT, "unset-ltfoot" },
151         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot" },
152         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot" },
153         { Tabular::SET_LTNEWPAGE, "set-ltnewpage" },
154         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption" },
155         { Tabular::SET_SPECIAL_COLUMN, "set-special-column" },
156         { Tabular::SET_SPECIAL_MULTI, "set-special-multi" },
157         { Tabular::SET_BOOKTABS, "set-booktabs" },
158         { Tabular::UNSET_BOOKTABS, "unset-booktabs" },
159         { Tabular::SET_TOP_SPACE, "set-top-space" },
160         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space" },
161         { Tabular::SET_INTERLINE_SPACE, "set-interline-space" },
162         { Tabular::SET_BORDER_LINES, "set-border-lines" },
163         { Tabular::LAST_ACTION, "" }
164 };
165
166
167 class FeatureEqual : public unary_function<TabularFeature, bool> {
168 public:
169         FeatureEqual(Tabular::Feature feature)
170                 : feature_(feature) {}
171         bool operator()(TabularFeature const & tf) const {
172                 return tf.action == feature_;
173         }
174 private:
175         Tabular::Feature feature_;
176 };
177
178
179 template <class T>
180 string const write_attribute(string const & name, T const & t)
181 {
182         string const s = tostr(t);
183         return s.empty() ? s : " " + name + "=\"" + s + "\"";
184 }
185
186 template <>
187 string const write_attribute(string const & name, string const & t)
188 {
189         return t.empty() ? t : " " + name + "=\"" + t + "\"";
190 }
191
192
193 template <>
194 string const write_attribute(string const & name, docstring const & t)
195 {
196         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
197 }
198
199
200 template <>
201 string const write_attribute(string const & name, bool const & b)
202 {
203         // we write only true attribute values so we remove a bit of the
204         // file format bloat for tabulars.
205         return b ? write_attribute(name, convert<string>(b)) : string();
206 }
207
208
209 template <>
210 string const write_attribute(string const & name, int const & i)
211 {
212         // we write only true attribute values so we remove a bit of the
213         // file format bloat for tabulars.
214         return i ? write_attribute(name, convert<string>(i)) : string();
215 }
216
217
218 template <>
219 string const write_attribute(string const & name, Tabular::idx_type const & i)
220 {
221         // we write only true attribute values so we remove a bit of the
222         // file format bloat for tabulars.
223         return i ? write_attribute(name, convert<string>(i)) : string();
224 }
225
226
227 template <>
228 string const write_attribute(string const & name, Length const & value)
229 {
230         // we write only the value if we really have one same reson as above.
231         return value.zero() ? string() : write_attribute(name, value.asString());
232 }
233
234
235 string const tostr(LyXAlignment const & num)
236 {
237         switch (num) {
238         case LYX_ALIGN_NONE:
239                 return "none";
240         case LYX_ALIGN_BLOCK:
241                 return "block";
242         case LYX_ALIGN_LEFT:
243                 return "left";
244         case LYX_ALIGN_CENTER:
245                 return "center";
246         case LYX_ALIGN_RIGHT:
247                 return "right";
248         case LYX_ALIGN_LAYOUT:
249                 return "layout";
250         case LYX_ALIGN_SPECIAL:
251                 return "special";
252         }
253         return string();
254 }
255
256
257 string const tostr(Tabular::VAlignment const & num)
258 {
259         switch (num) {
260         case Tabular::LYX_VALIGN_TOP:
261                 return "top";
262         case Tabular::LYX_VALIGN_MIDDLE:
263                 return "middle";
264         case Tabular::LYX_VALIGN_BOTTOM:
265                 return "bottom";
266         }
267         return string();
268 }
269
270
271 string const tostr(Tabular::BoxType const & num)
272 {
273         switch (num) {
274         case Tabular::BOX_NONE:
275                 return "none";
276         case Tabular::BOX_PARBOX:
277                 return "parbox";
278         case Tabular::BOX_MINIPAGE:
279                 return "minipage";
280         }
281         return string();
282 }
283
284
285 // I would have liked a fromstr template a lot better. (Lgb)
286 bool string2type(string const str, LyXAlignment & num)
287 {
288         if (str == "none")
289                 num = LYX_ALIGN_NONE;
290         else if (str == "block")
291                 num = LYX_ALIGN_BLOCK;
292         else if (str == "left")
293                 num = LYX_ALIGN_LEFT;
294         else if (str == "center")
295                 num = LYX_ALIGN_CENTER;
296         else if (str == "right")
297                 num = LYX_ALIGN_RIGHT;
298         else
299                 return false;
300         return true;
301 }
302
303
304 bool string2type(string const str, Tabular::VAlignment & num)
305 {
306         if (str == "top")
307                 num = Tabular::LYX_VALIGN_TOP;
308         else if (str == "middle" )
309                 num = Tabular::LYX_VALIGN_MIDDLE;
310         else if (str == "bottom")
311                 num = Tabular::LYX_VALIGN_BOTTOM;
312         else
313                 return false;
314         return true;
315 }
316
317
318 bool string2type(string const str, Tabular::BoxType & num)
319 {
320         if (str == "none")
321                 num = Tabular::BOX_NONE;
322         else if (str == "parbox")
323                 num = Tabular::BOX_PARBOX;
324         else if (str == "minipage")
325                 num = Tabular::BOX_MINIPAGE;
326         else
327                 return false;
328         return true;
329 }
330
331
332 bool string2type(string const str, bool & num)
333 {
334         if (str == "true")
335                 num = true;
336         else if (str == "false")
337                 num = false;
338         else
339                 return false;
340         return true;
341 }
342
343
344 bool getTokenValue(string const & str, char const * token, string & ret)
345 {
346         ret.erase();
347         size_t token_length = strlen(token);
348         size_t pos = str.find(token);
349
350         if (pos == string::npos || pos + token_length + 1 >= str.length()
351                 || str[pos + token_length] != '=')
352                 return false;
353         pos += token_length + 1;
354         char ch = str[pos];
355         if (ch != '"' && ch != '\'') { // only read till next space
356                 ret += ch;
357                 ch = ' ';
358         }
359         while (pos < str.length() - 1 && str[++pos] != ch)
360                 ret += str[pos];
361
362         return true;
363 }
364
365
366 bool getTokenValue(string const & str, char const * token, docstring & ret)
367 {
368         string tmp;
369         bool const success = getTokenValue(str, token, tmp);
370         ret = from_utf8(tmp);
371         return success;
372 }
373
374
375 bool getTokenValue(string const & str, char const * token, int & num)
376 {
377         string tmp;
378         num = 0;
379         if (!getTokenValue(str, token, tmp))
380                 return false;
381         num = convert<int>(tmp);
382         return true;
383 }
384
385
386 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
387 {
388         string tmp;
389         return getTokenValue(str, token, tmp) && string2type(tmp, num);
390 }
391
392
393 bool getTokenValue(string const & str, char const * token,
394                                    Tabular::VAlignment & num)
395 {
396         string tmp;
397         return getTokenValue(str, token, tmp) && string2type(tmp, num);
398 }
399
400
401 bool getTokenValue(string const & str, char const * token,
402                                    Tabular::BoxType & num)
403 {
404         string tmp;
405         return getTokenValue(str, token, tmp) && string2type(tmp, num);
406 }
407
408
409 bool getTokenValue(string const & str, char const * token, bool & flag)
410 {
411         // set the flag always to false as this should be the default for bools
412         // not in the file-format.
413         flag = false;
414         string tmp;
415         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
416 }
417
418
419 bool getTokenValue(string const & str, char const * token, Length & len)
420 {
421         // set the length to be zero() as default as this it should be if not
422         // in the file format.
423         len = Length();
424         string tmp;
425         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
426 }
427
428
429 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
430 {
431         len = Length();
432         flag = false;
433         string tmp;
434         if (!getTokenValue(str, token, tmp))
435                 return false;
436         if (tmp == "default") {
437                 flag = true;
438                 return  true;
439         }
440         return isValidLength(tmp, &len);
441 }
442
443
444 void l_getline(istream & is, string & str)
445 {
446         str.erase();
447         while (str.empty()) {
448                 getline(is, str);
449                 if (!str.empty() && str[str.length() - 1] == '\r')
450                         str.erase(str.length() - 1);
451         }
452 }
453
454 } // namespace
455
456
457 string const featureAsString(Tabular::Feature feature)
458 {
459         TabularFeature * end = tabularFeature +
460                 sizeof(tabularFeature) / sizeof(TabularFeature);
461         TabularFeature * it = find_if(tabularFeature, end,
462                                            FeatureEqual(feature));
463         return (it == end) ? string() : it->feature;
464 }
465
466
467
468 /////////////////////////////////////////////////////////////////////
469 //
470 // Tabular
471 //
472 /////////////////////////////////////////////////////////////////////
473
474
475 Tabular::CellData::CellData(Buffer const & buf)
476         : cellno(0),
477           width(0),
478           multicolumn(Tabular::CELL_NORMAL),
479           alignment(LYX_ALIGN_CENTER),
480           valignment(LYX_VALIGN_TOP),
481           top_line(false),
482           bottom_line(false),
483           left_line(false),
484           right_line(false),
485           usebox(BOX_NONE),
486           rotate(false),
487           inset(new InsetTableCell(buf))
488 {
489         inset->setBuffer(const_cast<Buffer &>(buf));
490         inset->paragraphs().back().setLayout(buf.params().documentClass().emptyLayout());
491 }
492
493
494 Tabular::CellData::CellData(CellData const & cs)
495         : cellno(cs.cellno),
496           width(cs.width),
497           multicolumn(cs.multicolumn),
498           alignment(cs.alignment),
499           valignment(cs.valignment),
500           top_line(cs.top_line),
501           bottom_line(cs.bottom_line),
502           left_line(cs.left_line),
503           right_line(cs.right_line),
504           usebox(cs.usebox),
505           rotate(cs.rotate),
506           align_special(cs.align_special),
507           p_width(cs.p_width),
508           inset(dynamic_cast<InsetTableCell *>(cs.inset->clone()))
509 {}
510
511 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
512 {
513         swap(cs);
514         return *this;
515 }
516
517 void Tabular::CellData::swap(CellData & rhs)
518 {
519         std::swap(cellno, rhs.cellno);
520         std::swap(width, rhs.width);
521         std::swap(multicolumn, rhs.multicolumn);
522         std::swap(alignment, rhs.alignment);
523         std::swap(valignment, rhs.valignment);
524         std::swap(top_line, rhs.top_line);
525         std::swap(bottom_line, rhs.bottom_line);
526         std::swap(left_line, rhs.left_line);
527         std::swap(right_line, rhs.right_line);
528         std::swap(usebox, rhs.usebox);
529         std::swap(rotate, rhs.rotate);
530         std::swap(align_special, rhs.align_special);
531         p_width.swap(rhs.p_width);
532         inset.swap(rhs.inset);
533 }
534
535
536 Tabular::RowData::RowData()
537         : ascent(0),
538           descent(0),
539           top_space_default(false),
540           bottom_space_default(false),
541           interline_space_default(false),
542           endhead(false),
543           endfirsthead(false),
544           endfoot(false),
545           endlastfoot(false),
546           newpage(false),
547           caption(false)
548 {}
549
550
551 Tabular::ColumnData::ColumnData()
552         : alignment(LYX_ALIGN_CENTER),
553           valignment(LYX_VALIGN_TOP),
554           width(0)
555 {
556 }
557
558
559 Tabular::ltType::ltType()
560         : topDL(false),
561           bottomDL(false),
562           empty(false)
563 {}
564
565
566 Tabular::Tabular(Buffer const & buffer, row_type rows_arg, col_type columns_arg)
567 {
568         init(buffer, rows_arg, columns_arg);
569 }
570
571
572 // activates all lines and sets all widths to 0
573 void Tabular::init(Buffer const & buf, row_type rows_arg,
574                       col_type columns_arg)
575 {
576         buffer_ = &buf;
577         row_info = row_vector(rows_arg);
578         column_info = column_vector(columns_arg);
579         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
580         row_info.reserve(10);
581         column_info.reserve(10);
582         cell_info.reserve(100);
583         updateIndexes();
584         is_long_tabular = false;
585         rotate = false;
586         use_booktabs = false;
587         size_t row_count = row_info.size();
588         size_t column_count = column_info.size();
589         // set silly default lines
590         for (row_type i = 0; i < row_count; ++i)
591                 for (col_type j = 0; j < column_count; ++j) {
592                         cell_info[i][j].top_line = true;
593                         cell_info[i][j].left_line = true;
594                         cell_info[i][j].bottom_line = i == 0 || i == row_count - 1;
595                         cell_info[i][j].right_line = j == column_count - 1;
596                 }
597 }
598
599
600 void Tabular::appendRow(idx_type const cell)
601 {
602         BufferParams const & bp = buffer().params();
603         row_type const row = cellRow(cell);
604
605         row_vector::iterator rit = row_info.begin() + row;
606         row_info.insert(rit, RowData());
607         // now set the values of the row before
608         row_info[row] = row_info[row + 1];
609
610         row_type const nrows = row_info.size();
611         col_type const ncols = column_info.size();
612
613         cell_vvector old(nrows - 1);
614         for (row_type i = 0; i < nrows - 1; ++i)
615                 swap(cell_info[i], old[i]);
616
617         cell_info = cell_vvector(nrows, cell_vector(ncols, CellData(buffer())));
618
619         for (row_type i = 0; i <= row; ++i)
620                 swap(cell_info[i], old[i]);
621         for (row_type i = row + 2; i < nrows; ++i)
622                 swap(cell_info[i], old[i - 1]);
623
624         updateIndexes();
625         for (col_type c = 0; c < ncols; ++c) {
626                 // inherit line settings
627                 idx_type const i = cellIndex(row + 1, c);
628                 idx_type const j = cellIndex(row, c);
629                 setLeftLine(i, leftLine(j));
630                 setRightLine(i, rightLine(j));
631                 setTopLine(i, topLine(j));
632                 if (topLine(j) && bottomLine(j)) {
633                         setBottomLine(i, true);
634                         setBottomLine(j, false);
635                 }
636                 // mark track changes
637                 if (bp.trackChanges)
638                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
639         }
640 }
641
642
643 void Tabular::deleteRow(row_type const row)
644 {
645         // Not allowed to delete last row
646         if (row_info.size() == 1)
647                 return;
648
649         row_info.erase(row_info.begin() + row);
650         cell_info.erase(cell_info.begin() + row);
651         updateIndexes();
652 }
653
654
655 void Tabular::copyRow(row_type const row)
656 {
657         row_info.insert(row_info.begin() + row, row_info[row]);
658         cell_info.insert(cell_info.begin() + row, cell_info[row]);
659
660         if (buffer().params().trackChanges)
661                 for (col_type j = 0; j < column_info.size(); ++j)
662                         cell_info[row + 1][j].inset->setChange(Change(Change::INSERTED));
663
664         updateIndexes();
665 }
666
667
668 void Tabular::appendColumn(idx_type const cell)
669 {
670         col_type const c = cellColumn(cell);
671         column_vector::iterator cit = column_info.begin() + c + 1;
672         column_info.insert(cit, ColumnData());
673         row_type const nrows = row_info.size();
674         // set the column values of the column before
675         column_info[c + 1] = column_info[c];
676
677         for (row_type r = 0; r < nrows; ++r) {
678                 cell_info[r].insert(cell_info[r].begin() + c + 1, 
679                         CellData(buffer()));
680                 if (cell_info[r][c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
681                         cell_info[r][c + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
682                 else
683                         cell_info[r][c + 1].multicolumn = cell_info[r][c].multicolumn;
684         }
685         updateIndexes();
686         for (row_type r = 0; r < nrows; ++r) {
687                 // inherit line settings
688                 idx_type const i = cellIndex(r, c + 1);
689                 idx_type const j = cellIndex(r, c);
690                 setBottomLine(i, bottomLine(j));
691                 setTopLine(i, topLine(j));
692                 setLeftLine(i, leftLine(j));
693                 if (rightLine(j) && rightLine(j)) {
694                         setRightLine(i, true);
695                         setRightLine(j, false);
696                 }
697                 //
698                 cellInfo(i).inset->clear();
699                 if (buffer().params().trackChanges)
700                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
701         }
702 }
703
704
705 void Tabular::deleteColumn(col_type const column)
706 {
707         // Not allowed to delete last column
708         if (column_info.size() == 1)
709                 return;
710
711         column_info.erase(column_info.begin() + column);
712         size_t row_count = row_info.size();
713         for (row_type i = 0; i < row_count; ++i) {
714                 // Care about multicolumn cells
715                 if (column + 1 < column_info.size() &&
716                     cell_info[i][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
717                     cell_info[i][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
718                         cell_info[i][column + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
719                 }
720                 cell_info[i].erase(cell_info[i].begin() + column);
721         }
722         updateIndexes();
723 }
724
725
726 void Tabular::copyColumn(col_type const column)
727 {
728         BufferParams const & bp = buffer().params();
729         column_info.insert(column_info.begin() + column, column_info[column]);
730
731         size_t row_count = row_info.size();
732         for (row_type i = 0; i < row_count; ++i)
733                 cell_info[i].insert(cell_info[i].begin() + column, cell_info[i][column]);
734
735         if (bp.trackChanges)
736                 for (row_type i = 0; i < row_count; ++i)
737                         cell_info[i][column + 1].inset->setChange(Change(Change::INSERTED));
738         updateIndexes();
739 }
740
741
742 void Tabular::updateIndexes()
743 {
744         col_type ncols = column_info.size();
745         row_type nrows = row_info.size();
746         numberofcells = 0;
747         for (row_type row = 0; row < nrows; ++row)
748                 for (col_type column = 0; column < ncols; ++column) {
749                         if (!isPartOfMultiColumn(row, column))
750                                 ++numberofcells;
751                         cell_info[row][column].cellno = numberofcells - 1;
752                 }
753
754         rowofcell.resize(numberofcells);
755         columnofcell.resize(numberofcells);
756         idx_type i = 0;
757         for (row_type row = 0; row < nrows; ++row)
758                 for (col_type column = 0; column < ncols; ++column) {
759                         if (isPartOfMultiColumn(row, column))
760                                 continue;
761                         rowofcell[i] = row;
762                         columnofcell[i] = column;
763                         setFixedWidth(row, column);
764                         ++i;
765                 }
766 }
767
768
769 Tabular::idx_type Tabular::numberOfCellsInRow(idx_type const cell) const
770 {
771         row_type const row = cellRow(cell);
772         idx_type result = 0;
773         for (col_type i = 0; i < column_info.size(); ++i)
774                 if (cell_info[row][i].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
775                         ++result;
776         return result;
777 }
778
779
780 bool Tabular::topLine(idx_type const cell) const
781 {
782         return cellInfo(cell).top_line;
783 }
784
785
786 bool Tabular::bottomLine(idx_type const cell) const
787 {
788         return cellInfo(cell).bottom_line;
789 }
790
791
792 bool Tabular::leftLine(idx_type cell) const
793 {
794         if (use_booktabs)
795                 return false;
796         return cellInfo(cell).left_line;
797 }
798
799
800 bool Tabular::rightLine(idx_type cell) const
801 {
802         if (use_booktabs)
803                 return false;
804         return cellInfo(cell).right_line;
805 }
806
807
808 bool Tabular::topAlreadyDrawn(idx_type cell) const
809 {
810         row_type row = cellRow(cell);
811         if (row == 0)
812                 return false;
813         idx_type i = cellIndex(row - 1, cellColumn(cell));
814         return !rowTopLine(row) && bottomLine(i);
815 }
816
817
818 bool Tabular::leftAlreadyDrawn(idx_type cell) const
819 {
820         col_type col = cellColumn(cell);
821         if (col == 0)
822                 return false;
823         idx_type i = cellIndex(cellRow(cell), col - 1);
824         return rightLine(i) && !leftLine(cell);
825 }
826
827
828 bool Tabular::isLastRow(idx_type cell) const
829 {
830         return cellRow(cell) == row_info.size() - 1;
831 }
832
833
834 int Tabular::getAdditionalHeight(row_type row) const
835 {
836         if (!row || row >= row_info.size())
837                 return 0;
838
839         int const interline_space = row_info[row - 1].interline_space_default ?
840                 default_line_space :
841                 row_info[row - 1].interline_space.inPixels(width());
842         if (rowTopLine(row) && rowBottomLine(row - 1))
843                 return interline_space + WIDTH_OF_LINE;
844         return interline_space;
845 }
846
847
848 int Tabular::getAdditionalWidth(idx_type cell) const
849 {
850         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
851         if (rightLine(cell) 
852                 && nextcol < column_info.size() && leftLine(cellIndex(cellRow(cell), nextcol)))
853                 return WIDTH_OF_LINE;
854         return 0;
855 }
856
857
858 int Tabular::columnWidth(idx_type cell) const
859 {
860         int w = 0;
861         col_type const span = columnSpan(cell);
862         col_type const col = cellColumn(cell);
863         for(col_type c = col; c < col + span ; ++c)
864                 w += column_info[c].width;
865         return w;
866 }
867
868
869 bool Tabular::updateColumnWidths()
870 {
871         col_type const ncols = column_info.size();
872         row_type const nrows = row_info.size();
873         bool update = false;
874         // for each col get max of single col cells
875         for(col_type c = 0; c < ncols; ++c) {
876                 int new_width = 0;
877                 for(row_type r = 0; r < nrows; ++r) {
878                         idx_type const i = cellIndex(r, c);
879                         if (columnSpan(i) == 1)
880                                 new_width = max(new_width, cellInfo(i).width);
881                 }
882
883                 if (column_info[c].width != new_width) {
884                         column_info[c].width = new_width;
885                         update = true;
886                 }
887         }
888         // update col widths to fit merged cells
889         for(col_type c = 0; c < ncols; ++c)
890                 for(row_type r = 0; r < nrows; ++r) {
891                         idx_type const i = cellIndex(r, c);
892                         int const span = columnSpan(i);
893                         if (span == 1 || c > cellColumn(i))
894                                 continue;
895
896                         int old_width = 0;
897                         for(col_type j = c; j < c + span ; ++j)
898                                 old_width += column_info[j].width;
899
900                         if (cellInfo(i).width > old_width) {
901                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
902                                 update = true;
903                         }
904                 }
905
906         return update;
907 }
908
909
910 int Tabular::width() const
911 {
912         col_type const ncols = column_info.size();
913         int width = 0;
914         for (col_type i = 0; i < ncols; ++i)
915                 width += column_info[i].width;
916         return width;
917 }
918
919
920 void Tabular::setCellWidth(idx_type cell, int new_width)
921 {
922         cellInfo(cell).width = new_width + 2 * WIDTH_OF_LINE 
923                 + getAdditionalWidth(cell);
924 }
925
926
927 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
928                               bool onlycolumn)
929 {
930         if (!isMultiColumn(cell) || onlycolumn)
931                 column_info[cellColumn(cell)].alignment = align;
932         if (!onlycolumn)
933                 cellInfo(cell).alignment = align;
934 }
935
936
937 void Tabular::setVAlignment(idx_type cell, VAlignment align,
938                                bool onlycolumn)
939 {
940         if (!isMultiColumn(cell) || onlycolumn)
941                 column_info[cellColumn(cell)].valignment = align;
942         if (!onlycolumn)
943                 cellInfo(cell).valignment = align;
944 }
945
946
947 namespace {
948
949 /**
950  * Allow line and paragraph breaks for fixed width cells or disallow them,
951  * merge cell paragraphs and reset layout to standard for variable width
952  * cells.
953  */
954 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
955 {
956         inset->setAutoBreakRows(fixedWidth);
957         inset->toggleFixedWidth(fixedWidth);
958         if (fixedWidth)
959                 return;
960
961         // merge all paragraphs to one
962         BufferParams const & bp = cur.bv().buffer().params();
963         while (inset->paragraphs().size() > 1)
964                 mergeParagraph(bp, inset->paragraphs(), 0);
965
966         // reset layout
967         cur.push(*inset);
968         // undo information has already been recorded
969         inset->getText(0)->setLayout(cur.bv().buffer(), 0, cur.lastpit() + 1,
970                         bp.documentClass().emptyLayoutName());
971         cur.pop();
972 }
973
974 }
975
976
977 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
978                 Length const & width)
979 {
980         col_type const j = cellColumn(cell);
981
982         column_info[j].p_width = width;
983         for (row_type i = 0; i < row_info.size(); ++i) {
984                 idx_type const cell = cellIndex(i, j);
985                 // because of multicolumns
986                 toggleFixedWidth(cur, cellInset(cell).get(),
987                                  !getPWidth(cell).zero());
988         }
989         // cur paragraph can become invalid after paragraphs were merged
990         if (cur.pit() > cur.lastpit())
991                 cur.pit() = cur.lastpit();
992         // cur position can become invalid after newlines were removed
993         if (cur.pos() > cur.lastpos())
994                 cur.pos() = cur.lastpos();
995 }
996
997
998 bool Tabular::setFixedWidth(row_type r, col_type c)
999 {
1000         if (!column_info[c].p_width.zero() ||
1001                                 (cell_info[r][c].multicolumn != CELL_NORMAL && 
1002                                 !cell_info[r][c].p_width.zero())) {
1003                 cell_info[r][c].inset->toggleFixedWidth(true);
1004                 return true;
1005         }
1006         return false;
1007 }
1008
1009
1010 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1011                 Length const & width)
1012 {
1013         if (!isMultiColumn(cell))
1014                 return false;
1015
1016         cellInfo(cell).p_width = width;
1017         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1018         // cur paragraph can become invalid after paragraphs were merged
1019         if (cur.pit() > cur.lastpit())
1020                 cur.pit() = cur.lastpit();
1021         // cur position can become invalid after newlines were removed
1022         if (cur.pos() > cur.lastpos())
1023                 cur.pos() = cur.lastpos();
1024         return true;
1025 }
1026
1027
1028 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1029                                  Tabular::Feature what)
1030 {
1031         if (what == SET_SPECIAL_MULTI)
1032                 cellInfo(cell).align_special = special;
1033         else
1034                 column_info[cellColumn(cell)].align_special = special;
1035 }
1036
1037
1038 void Tabular::setAllLines(idx_type cell, bool line)
1039 {
1040         setTopLine(cell, line);
1041         setBottomLine(cell, line);
1042         setRightLine(cell, line);
1043         setLeftLine(cell, line);
1044 }
1045
1046
1047 void Tabular::setTopLine(idx_type i, bool line)
1048 {
1049         cellInfo(i).top_line = line;
1050 }
1051
1052
1053 void Tabular::setBottomLine(idx_type i, bool line)
1054 {
1055         cellInfo(i).bottom_line = line;
1056 }
1057
1058
1059 void Tabular::setLeftLine(idx_type cell, bool line)
1060 {
1061         cellInfo(cell).left_line = line;
1062 }
1063
1064
1065 void Tabular::setRightLine(idx_type cell, bool line)
1066 {
1067         cellInfo(cell).right_line = line;
1068 }
1069
1070 bool Tabular::rowTopLine(row_type r) const
1071 {
1072         idx_type i0 = getFirstCellInRow(r);
1073         idx_type i1 = getLastCellInRow(r);
1074         bool all_rows_set = true;
1075         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1076                 all_rows_set = cellInfo(j).top_line;
1077         return all_rows_set;
1078 }
1079
1080
1081 bool Tabular::rowBottomLine(row_type r) const
1082 {
1083         idx_type i0 = getFirstCellInRow(r);
1084         idx_type i1 = getLastCellInRow(r);
1085         bool all_rows_set = true;
1086         for (idx_type j = i0; all_rows_set && j <= i1; ++j)
1087                 all_rows_set = cellInfo(j).bottom_line;
1088         return all_rows_set;
1089 }
1090
1091
1092 bool Tabular::columnLeftLine(col_type c) const
1093 {
1094         if (use_booktabs)
1095                 return false;
1096
1097         int nrows_left = 0;
1098         int total = 0;
1099         row_type const nrows = row_info.size();
1100         for (row_type r = 0; r < nrows; ++r) {
1101                 idx_type i = cellIndex(r, c);
1102                 if (c == cellColumn(i)) {
1103                         ++total;
1104                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1105                         if (cellInfo(i).left_line || right)
1106                                 ++nrows_left;
1107                 }
1108         }
1109         return 2 * nrows_left >= total;
1110 }
1111
1112
1113 bool Tabular::columnRightLine(col_type c) const
1114 {
1115         if (use_booktabs)
1116                 return false;
1117
1118         int nrows_right = 0;
1119         int total = 0;
1120         row_type const nrows = row_info.size();
1121         for (row_type r = 0; r < nrows; ++r) {
1122                 idx_type i = cellIndex(r, c);
1123                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1124                         ++total;
1125                         bool left = c + 1 < column_info.size() 
1126                                 && cellInfo(cellIndex(r, c + 1)).left_line
1127                                 || c + 1 == column_info.size();
1128                         if (cellInfo(i).right_line && left)
1129                                 ++nrows_right;
1130                 }
1131         }
1132         return 2 * nrows_right >= total;
1133 }
1134
1135
1136 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1137 {
1138         if (!onlycolumn && isMultiColumn(cell))
1139                 return cellInfo(cell).alignment;
1140         return column_info[cellColumn(cell)].alignment;
1141 }
1142
1143
1144 Tabular::VAlignment
1145 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1146 {
1147         if (!onlycolumn && isMultiColumn(cell))
1148                 return cellInfo(cell).valignment;
1149         return column_info[cellColumn(cell)].valignment;
1150 }
1151
1152
1153 Length const Tabular::getPWidth(idx_type cell) const
1154 {
1155         if (isMultiColumn(cell))
1156                 return cellInfo(cell).p_width;
1157         return column_info[cellColumn(cell)].p_width;
1158 }
1159
1160
1161 int Tabular::cellWidth(idx_type cell) const
1162 {
1163         return cellInfo(cell).width;
1164 }
1165
1166
1167 int Tabular::getBeginningOfTextInCell(idx_type cell) const
1168 {
1169         int x = 0;
1170
1171         switch (getAlignment(cell)) {
1172         case LYX_ALIGN_CENTER:
1173                 x += (columnWidth(cell) - cellWidth(cell)) / 2;
1174                 break;
1175         case LYX_ALIGN_RIGHT:
1176                 x += columnWidth(cell) - cellWidth(cell);
1177                 // + getAdditionalWidth(cell);
1178                 break;
1179         default:
1180                 // LYX_ALIGN_LEFT: nothing :-)
1181                 break;
1182         }
1183
1184         // the LaTeX Way :-(
1185         x += WIDTH_OF_LINE;
1186         return x;
1187 }
1188
1189
1190 bool Tabular::isFirstCellInRow(idx_type cell) const
1191 {
1192         return cellColumn(cell) == 0;
1193 }
1194
1195
1196 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1197 {
1198         if (row > row_info.size() - 1)
1199                 row = row_info.size() - 1;
1200         return cell_info[row][0].cellno;
1201 }
1202
1203
1204 bool Tabular::isLastCellInRow(idx_type cell) const
1205 {
1206         return cellRightColumn(cell) == column_info.size() - 1;
1207 }
1208
1209
1210 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1211 {
1212         if (row > row_info.size() - 1)
1213                 row = row_info.size() - 1;
1214         return cell_info[row][column_info.size() - 1].cellno;
1215 }
1216
1217
1218 Tabular::row_type Tabular::cellRow(idx_type cell) const
1219 {
1220         if (cell >= numberofcells)
1221                 return row_info.size() - 1;
1222         if (cell == npos)
1223                 return 0;
1224         return rowofcell[cell];
1225 }
1226
1227
1228 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1229 {
1230         if (cell >= numberofcells)
1231                 return column_info.size() - 1;
1232         if (cell == npos)
1233                 return 0;       
1234         return columnofcell[cell];
1235 }
1236
1237
1238 Tabular::col_type Tabular::cellRightColumn(idx_type cell) const
1239 {
1240         row_type const row = cellRow(cell);
1241         col_type column = cellColumn(cell);
1242         while (column < column_info.size() - 1 &&
1243                    cell_info[row][column + 1].multicolumn == CELL_PART_OF_MULTICOLUMN)
1244                 ++column;
1245         return column;
1246 }
1247
1248
1249 void Tabular::write(ostream & os) const
1250 {
1251         // header line
1252         os << "<lyxtabular"
1253            << write_attribute("version", 3)
1254            << write_attribute("rows", row_info.size())
1255            << write_attribute("columns", column_info.size())
1256            << ">\n";
1257         // global longtable options
1258         os << "<features"
1259            << write_attribute("rotate", rotate)
1260            << write_attribute("booktabs", use_booktabs)
1261            << write_attribute("islongtable", is_long_tabular)
1262            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1263            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1264            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1265            << write_attribute("headTopDL", endhead.topDL)
1266            << write_attribute("headBottomDL", endhead.bottomDL)
1267            << write_attribute("footTopDL", endfoot.topDL)
1268            << write_attribute("footBottomDL", endfoot.bottomDL)
1269            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1270            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1271            << write_attribute("lastFootEmpty", endlastfoot.empty)
1272            << ">\n";
1273         for (col_type j = 0; j < column_info.size(); ++j) {
1274                 os << "<column"
1275                    << write_attribute("alignment", column_info[j].alignment)
1276                    << write_attribute("valignment", column_info[j].valignment)
1277                    << write_attribute("width", column_info[j].p_width.asString())
1278                    << write_attribute("special", column_info[j].align_special)
1279                    << ">\n";
1280         }
1281         for (row_type i = 0; i < row_info.size(); ++i) {
1282                 static const string def("default");
1283                 os << "<row";
1284                 if (row_info[i].top_space_default)
1285                         os << write_attribute("topspace", def);
1286                 else
1287                         os << write_attribute("topspace", row_info[i].top_space);
1288                 if (row_info[i].bottom_space_default)
1289                         os << write_attribute("bottomspace", def);
1290                 else
1291                         os << write_attribute("bottomspace", row_info[i].bottom_space);
1292                 if (row_info[i].interline_space_default)
1293                         os << write_attribute("interlinespace", def);
1294                 else
1295                         os << write_attribute("interlinespace", row_info[i].interline_space);
1296                 os << write_attribute("endhead", row_info[i].endhead)
1297                    << write_attribute("endfirsthead", row_info[i].endfirsthead)
1298                    << write_attribute("endfoot", row_info[i].endfoot)
1299                    << write_attribute("endlastfoot", row_info[i].endlastfoot)
1300                    << write_attribute("newpage", row_info[i].newpage)
1301                    << write_attribute("caption", row_info[i].caption)
1302                    << ">\n";
1303                 for (col_type j = 0; j < column_info.size(); ++j) {
1304                         os << "<cell"
1305                            << write_attribute("multicolumn", cell_info[i][j].multicolumn)
1306                            << write_attribute("alignment", cell_info[i][j].alignment)
1307                            << write_attribute("valignment", cell_info[i][j].valignment)
1308                            << write_attribute("topline", cell_info[i][j].top_line)
1309                            << write_attribute("bottomline", cell_info[i][j].bottom_line)
1310                            << write_attribute("leftline", cell_info[i][j].left_line)
1311                            << write_attribute("rightline", cell_info[i][j].right_line)
1312                            << write_attribute("rotate", cell_info[i][j].rotate)
1313                            << write_attribute("usebox", cell_info[i][j].usebox)
1314                            << write_attribute("width", cell_info[i][j].p_width)
1315                            << write_attribute("special", cell_info[i][j].align_special)
1316                            << ">\n";
1317                         os << "\\begin_inset ";
1318                         cell_info[i][j].inset->write(os);
1319                         os << "\n\\end_inset\n"
1320                            << "</cell>\n";
1321                 }
1322                 os << "</row>\n";
1323         }
1324         os << "</lyxtabular>\n";
1325 }
1326
1327
1328 void Tabular::read(Lexer & lex)
1329 {
1330         string line;
1331         istream & is = lex.getStream();
1332
1333         l_getline(is, line);
1334         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1335                 LASSERT(false, /**/);
1336                 return;
1337         }
1338
1339         int version;
1340         if (!getTokenValue(line, "version", version))
1341                 return;
1342         LASSERT(version >= 2, /**/);
1343
1344         int rows_arg;
1345         if (!getTokenValue(line, "rows", rows_arg))
1346                 return;
1347         int columns_arg;
1348         if (!getTokenValue(line, "columns", columns_arg))
1349                 return;
1350         init(buffer(), rows_arg, columns_arg);
1351         l_getline(is, line);
1352         if (!prefixIs(line, "<features")) {
1353                 lyxerr << "Wrong tabular format (expected <features ...> got"
1354                        << line << ')' << endl;
1355                 return;
1356         }
1357         getTokenValue(line, "rotate", rotate);
1358         getTokenValue(line, "booktabs", use_booktabs);
1359         getTokenValue(line, "islongtable", is_long_tabular);
1360         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1361         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1362         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1363         getTokenValue(line, "headTopDL", endhead.topDL);
1364         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1365         getTokenValue(line, "footTopDL", endfoot.topDL);
1366         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1367         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1368         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1369         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1370
1371         for (col_type j = 0; j < column_info.size(); ++j) {
1372                 l_getline(is,line);
1373                 if (!prefixIs(line,"<column")) {
1374                         lyxerr << "Wrong tabular format (expected <column ...> got"
1375                                << line << ')' << endl;
1376                         return;
1377                 }
1378                 getTokenValue(line, "alignment", column_info[j].alignment);
1379                 getTokenValue(line, "valignment", column_info[j].valignment);
1380                 getTokenValue(line, "width", column_info[j].p_width);
1381                 getTokenValue(line, "special", column_info[j].align_special);
1382         }
1383
1384         for (row_type i = 0; i < row_info.size(); ++i) {
1385                 l_getline(is, line);
1386                 if (!prefixIs(line, "<row")) {
1387                         lyxerr << "Wrong tabular format (expected <row ...> got"
1388                                << line << ')' << endl;
1389                         return;
1390                 }
1391                 getTokenValue(line, "topspace", row_info[i].top_space,
1392                               row_info[i].top_space_default);
1393                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1394                               row_info[i].bottom_space_default);
1395                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1396                               row_info[i].interline_space_default);
1397                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1398                 getTokenValue(line, "endhead", row_info[i].endhead);
1399                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1400                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1401                 getTokenValue(line, "newpage", row_info[i].newpage);
1402                 getTokenValue(line, "caption", row_info[i].caption);
1403                 for (col_type j = 0; j < column_info.size(); ++j) {
1404                         l_getline(is, line);
1405                         if (!prefixIs(line, "<cell")) {
1406                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1407                                        << line << ')' << endl;
1408                                 return;
1409                         }
1410                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1411                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1412                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1413                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1414                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1415                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1416                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1417                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1418                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1419                         getTokenValue(line, "width", cell_info[i][j].p_width);
1420                         setFixedWidth(i,j);
1421                         getTokenValue(line, "special", cell_info[i][j].align_special);
1422                         l_getline(is, line);
1423                         if (prefixIs(line, "\\begin_inset")) {
1424                                 cell_info[i][j].inset->read(lex);
1425                                 l_getline(is, line);
1426                         }
1427                         if (!prefixIs(line, "</cell>")) {
1428                                 lyxerr << "Wrong tabular format (expected </cell> got"
1429                                        << line << ')' << endl;
1430                                 return;
1431                         }
1432                 }
1433                 l_getline(is, line);
1434                 if (!prefixIs(line, "</row>")) {
1435                         lyxerr << "Wrong tabular format (expected </row> got"
1436                                << line << ')' << endl;
1437                         return;
1438                 }
1439         }
1440         while (!prefixIs(line, "</lyxtabular>")) {
1441                 l_getline(is, line);
1442         }
1443         updateIndexes();
1444 }
1445
1446
1447 bool Tabular::isMultiColumn(idx_type cell) const
1448 {
1449         return cellInfo(cell).multicolumn != CELL_NORMAL;
1450 }
1451
1452
1453 bool Tabular::isMultiColumnReal(idx_type cell) const
1454 {
1455         return cellColumn(cell) != cellRightColumn(cell) &&
1456                         cellInfo(cell).multicolumn != CELL_NORMAL;
1457 }
1458
1459
1460 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1461 {
1462         return cell_info[cellRow(cell)][cellColumn(cell)];
1463 }
1464
1465
1466 void Tabular::setMultiColumn(idx_type cell, idx_type number)
1467 {
1468         CellData & cs = cellInfo(cell);
1469         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1470         cs.alignment = column_info[cellColumn(cell)].alignment;
1471         setRightLine(cell, rightLine(cell + number - 1));
1472         for (idx_type i = 1; i < number; ++i) {
1473                 CellData & cs1 = cellInfo(cell + i);
1474                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1475                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1476                 cs1.inset->clear();
1477         }
1478         updateIndexes();
1479 }
1480
1481
1482 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1483 {
1484         row_type const row = cellRow(cell);
1485         col_type const ncols = column_info.size();
1486         idx_type result = 1;
1487         col_type column = cellColumn(cell) + 1;
1488         while (column < ncols && isPartOfMultiColumn(row, column)) {
1489                 ++result;
1490                 ++column;
1491         }
1492         return result;
1493 }
1494
1495
1496 Tabular::idx_type Tabular::unsetMultiColumn(idx_type cell)
1497 {
1498         row_type const row = cellRow(cell);
1499         col_type column = cellColumn(cell);
1500
1501         idx_type result = 0;
1502
1503         if (cell_info[row][column].multicolumn == CELL_BEGIN_OF_MULTICOLUMN) {
1504                 cell_info[row][column].multicolumn = CELL_NORMAL;
1505                 ++column;
1506                 while (column < column_info.size() &&
1507                            cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN)
1508                 {
1509                         cell_info[row][column].multicolumn = CELL_NORMAL;
1510                         ++column;
1511                         ++result;
1512                 }
1513         }
1514         updateIndexes();
1515         return result;
1516 }
1517
1518
1519 void Tabular::setRotateCell(idx_type cell, bool flag)
1520 {
1521         cellInfo(cell).rotate = flag;
1522 }
1523
1524
1525 bool Tabular::getRotateCell(idx_type cell) const
1526 {
1527         return cellInfo(cell).rotate;
1528 }
1529
1530
1531 bool Tabular::needRotating() const
1532 {
1533         if (rotate)
1534                 return true;
1535         for (row_type i = 0; i < row_info.size(); ++i)
1536                 for (col_type j = 0; j < column_info.size(); ++j)
1537                         if (cell_info[i][j].rotate)
1538                                 return true;
1539         return false;
1540 }
1541
1542
1543 bool Tabular::isLastCell(idx_type cell) const
1544 {
1545         if (cell + 1 < numberofcells)
1546                 return false;
1547         return true;
1548 }
1549
1550
1551 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1552 {
1553         if (cellRow(cell) > 0)
1554                 return cell_info[cellRow(cell)-1][cellColumn(cell)].cellno;
1555         return cell;
1556 }
1557
1558
1559 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1560 {
1561         if (cellRow(cell) + 1 < row_info.size())
1562                 return cell_info[cellRow(cell)+1][cellColumn(cell)].cellno;
1563         return cell;
1564 }
1565
1566
1567 Tabular::idx_type Tabular::cellIndex(row_type row,
1568                                                col_type column) const
1569 {
1570         BOOST_ASSERT(column != npos && column < column_info.size()
1571                 && row != npos && row < row_info.size());
1572         return cell_info[row][column].cellno;
1573 }
1574
1575
1576 void Tabular::setUsebox(idx_type cell, BoxType type)
1577 {
1578         cellInfo(cell).usebox = type;
1579 }
1580
1581
1582 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1583 // adds line breaks, see bug 4886.
1584 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1585 {
1586         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1587                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1588                 return BOX_NONE;
1589         if (cellInfo(cell).usebox > 1)
1590                 return cellInfo(cell).usebox;
1591         return useParbox(cell);
1592 }
1593
1594
1595 ///
1596 //  This are functions used for the longtable support
1597 ///
1598 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1599                            bool first)
1600 {
1601         if (first) {
1602                 endfirsthead = hd;
1603                 if (hd.set)
1604                         row_info[row].endfirsthead = flag;
1605         } else {
1606                 endhead = hd;
1607                 if (hd.set)
1608                         row_info[row].endhead = flag;
1609         }
1610 }
1611
1612
1613 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1614 {
1615         hd = endhead;
1616         hd.set = haveLTHead();
1617         return row_info[row].endhead;
1618 }
1619
1620
1621 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1622 {
1623         hd = endfirsthead;
1624         hd.set = haveLTFirstHead();
1625         return row_info[row].endfirsthead;
1626 }
1627
1628
1629 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1630                            bool last)
1631 {
1632         if (last) {
1633                 endlastfoot = fd;
1634                 if (fd.set)
1635                         row_info[row].endlastfoot = flag;
1636         } else {
1637                 endfoot = fd;
1638                 if (fd.set)
1639                         row_info[row].endfoot = flag;
1640         }
1641 }
1642
1643
1644 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1645 {
1646         fd = endfoot;
1647         fd.set = haveLTFoot();
1648         return row_info[row].endfoot;
1649 }
1650
1651
1652 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1653 {
1654         fd = endlastfoot;
1655         fd.set = haveLTLastFoot();
1656         return row_info[row].endlastfoot;
1657 }
1658
1659
1660 void Tabular::setLTNewPage(row_type row, bool what)
1661 {
1662         row_info[row].newpage = what;
1663 }
1664
1665
1666 bool Tabular::getLTNewPage(row_type row) const
1667 {
1668         return row_info[row].newpage;
1669 }
1670
1671
1672 bool Tabular::haveLTHead() const
1673 {
1674         for (row_type i = 0; i < row_info.size(); ++i)
1675                 if (row_info[i].endhead)
1676                         return true;
1677         return false;
1678 }
1679
1680
1681 bool Tabular::haveLTFirstHead() const
1682 {
1683         if (endfirsthead.empty)
1684                 return false;
1685         for (row_type i = 0; i < row_info.size(); ++i)
1686                 if (row_info[i].endfirsthead)
1687                         return true;
1688         return false;
1689 }
1690
1691
1692 bool Tabular::haveLTFoot() const
1693 {
1694         for (row_type i = 0; i < row_info.size(); ++i)
1695                 if (row_info[i].endfoot)
1696                         return true;
1697         return false;
1698 }
1699
1700
1701 bool Tabular::haveLTLastFoot() const
1702 {
1703         if (endlastfoot.empty)
1704                 return false;
1705         for (row_type i = 0; i < row_info.size(); ++i)
1706                 if (row_info[i].endlastfoot)
1707                         return true;
1708         return false;
1709 }
1710
1711
1712 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1713 {
1714         idx_type i = getFirstCellInRow(row);
1715         if (what) {
1716                 setMultiColumn(i, column_info.size());
1717                 setTopLine(i, false);
1718                 setBottomLine(i, false);
1719                 setLeftLine(i, false);
1720                 setRightLine(i, false);
1721         } else
1722                 unsetMultiColumn(i);
1723         row_info[row].caption = what;
1724         return i;
1725 }
1726
1727
1728 bool Tabular::ltCaption(row_type row) const
1729 {
1730         return row_info[row].caption;
1731 }
1732
1733
1734 // end longtable support functions
1735
1736 void Tabular::setRowAscent(row_type row, int height)
1737 {
1738         if (row >= row_info.size() || row_info[row].ascent == height)
1739                 return;
1740         row_info[row].ascent = height;
1741 }
1742
1743
1744 void Tabular::setRowDescent(row_type row, int height)
1745 {
1746         if (row >= row_info.size() || row_info[row].descent == height)
1747                 return;
1748         row_info[row].descent = height;
1749 }
1750
1751
1752 int Tabular::rowAscent(row_type row) const
1753 {
1754         if (row >= row_info.size())
1755                 return 0;
1756         return row_info[row].ascent;
1757 }
1758
1759
1760 int Tabular::rowDescent(row_type row) const
1761 {
1762         LASSERT(row < row_info.size(), /**/);
1763         return row_info[row].descent;
1764 }
1765
1766
1767 int Tabular::height() const
1768 {
1769         int height = 0;
1770         for (row_type row = 0; row < row_info.size(); ++row)
1771                 height += rowAscent(row) + rowDescent(row) +
1772                         getAdditionalHeight(row);
1773         return height;
1774 }
1775
1776
1777 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
1778 {
1779         LASSERT(row < row_info.size(), /**/);
1780         LASSERT(column < column_info.size(), /**/);
1781         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
1782 }
1783
1784
1785 int Tabular::TeXTopHLine(odocstream & os, row_type row) const
1786 {
1787         // FIXME: assert or return 0 as in TeXBottomHLine()?
1788         LASSERT(row != npos, /**/);
1789         LASSERT(row < row_info.size(), /**/);
1790
1791         idx_type const fcell = getFirstCellInRow(row);
1792         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1793         idx_type tmp = 0;
1794
1795         for (idx_type i = fcell; i < n; ++i) {
1796                 if (topLine(i))
1797                         ++tmp;
1798         }
1799         if (use_booktabs && row == 0) {
1800                 if (topLine(fcell))
1801                         os << "\\toprule ";
1802         } else if (tmp == n - fcell) {
1803                 os << (use_booktabs ? "\\midrule " : "\\hline ");
1804         } else if (tmp) {
1805                 for (idx_type i = fcell; i < n; ++i) {
1806                         if (topLine(i)) {
1807                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1808                                    << cellColumn(i) + 1
1809                                    << '-'
1810                                    << cellRightColumn(i) + 1
1811                                    << "} ";
1812                         }
1813                 }
1814         } else {
1815                 return 0;
1816         }
1817         os << "\n";
1818         return 1;
1819 }
1820
1821
1822 int Tabular::TeXBottomHLine(odocstream & os, row_type row) const
1823 {
1824         // FIXME: return 0 or assert as in TeXTopHLine()?
1825         if (row == npos || row >= row_info.size())
1826                 return 0;
1827
1828         idx_type const fcell = getFirstCellInRow(row);
1829         idx_type const n = numberOfCellsInRow(fcell) + fcell;
1830         idx_type tmp = 0;
1831
1832         for (idx_type i = fcell; i < n; ++i) {
1833                 if (bottomLine(i))
1834                         ++tmp;
1835         }
1836         if (use_booktabs && row == row_info.size() - 1) {
1837                 if (bottomLine(fcell))
1838                         os << "\\bottomrule";
1839         } else if (tmp == n - fcell) {
1840                 os << (use_booktabs ? "\\midrule" : "\\hline");
1841         } else if (tmp) {
1842                 for (idx_type i = fcell; i < n; ++i) {
1843                         if (bottomLine(i)) {
1844                                 os << (use_booktabs ? "\\cmidrule{" : "\\cline{")
1845                                    << cellColumn(i) + 1
1846                                    << '-'
1847                                    << cellRightColumn(i) + 1
1848                                    << "} ";
1849                         }
1850                 }
1851         } else {
1852                 return 0;
1853         }
1854         os << "\n";
1855         return 1;
1856 }
1857
1858
1859 int Tabular::TeXCellPreamble(odocstream & os, idx_type cell, bool & ismulticol) const
1860 {
1861         int ret = 0;
1862         row_type const r = cellRow(cell);
1863         if (is_long_tabular && row_info[r].caption)
1864                 return ret;
1865
1866         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
1867         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
1868         // figure out how to set the lines
1869         // we always set double lines to the right of the cell
1870         col_type const c = cellColumn(cell);
1871         col_type const nextcol = c + columnSpan(cell);
1872         bool colright = columnRightLine(c);
1873         bool colleft = columnLeftLine(c);
1874         bool nextcolleft = nextcol < column_info.size() && columnLeftLine(nextcol);
1875         bool nextcellleft = nextcol < column_info.size() 
1876                 && leftLine(cellIndex(r, nextcol));
1877         bool coldouble = colright && nextcolleft;
1878         bool celldouble = rightLine(cell) && nextcellleft;
1879         ismulticol = isMultiColumn(cell) 
1880                 || (c == 0 && colleft != leftLine(cell))
1881                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
1882                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
1883                 || (coldouble != celldouble);
1884         if (ismulticol) {
1885                 os << "\\multicolumn{" << columnSpan(cell) << "}{";
1886                 if (c ==0 && leftLine(cell))
1887                         os << '|';
1888                 if (!cellInfo(cell).align_special.empty()) {
1889                         os << cellInfo(cell).align_special;
1890                 } else {
1891                         if (!getPWidth(cell).zero()) {
1892                                 switch (valign) {
1893                                 case LYX_VALIGN_TOP:
1894                                         os << 'p';
1895                                         break;
1896                                 case LYX_VALIGN_MIDDLE:
1897                                         os << 'm';
1898                                         break;
1899                                 case LYX_VALIGN_BOTTOM:
1900                                         os << 'b';
1901                                         break;
1902                                 }
1903                                 os << '{'
1904                                    << from_ascii(getPWidth(cell).asLatexString())
1905                                    << '}';
1906                         } else {
1907                                 switch (align) {
1908                                 case LYX_ALIGN_LEFT:
1909                                         os << 'l';
1910                                         break;
1911                                 case LYX_ALIGN_RIGHT:
1912                                         os << 'r';
1913                                         break;
1914                                 default:
1915                                         os << 'c';
1916                                         break;
1917                                 }
1918                         } // end if else !getPWidth
1919                 } // end if else !cellinfo_of_cell
1920                 if (rightLine(cell) || nextcellleft)
1921                         os << '|';
1922                 if (celldouble)
1923                         // add extra vertical line if we want a double one
1924                         os << '|';
1925                 os << "}{";
1926                 }
1927         if (getRotateCell(cell)) {
1928                 os << "\\begin{sideways}\n";
1929                 ++ret;
1930         }
1931         if (getUsebox(cell) == BOX_PARBOX) {
1932                 os << "\\parbox[";
1933                 switch (valign) {
1934                 case LYX_VALIGN_TOP:
1935                         os << 't';
1936                         break;
1937                 case LYX_VALIGN_MIDDLE:
1938                         os << 'c';
1939                         break;
1940                 case LYX_VALIGN_BOTTOM:
1941                         os << 'b';
1942                         break;
1943                 }
1944                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1945                    << "}{";
1946         } else if (getUsebox(cell) == BOX_MINIPAGE) {
1947                 os << "\\begin{minipage}[";
1948                 switch (valign) {
1949                 case LYX_VALIGN_TOP:
1950                         os << 't';
1951                         break;
1952                 case LYX_VALIGN_MIDDLE:
1953                         os << 'm';
1954                         break;
1955                 case LYX_VALIGN_BOTTOM:
1956                         os << 'b';
1957                         break;
1958                 }
1959                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
1960                    << "}\n";
1961                 ++ret;
1962         }
1963         return ret;
1964 }
1965
1966
1967 int Tabular::TeXCellPostamble(odocstream & os, idx_type cell, bool ismulticol) const
1968 {
1969         int ret = 0;
1970         row_type const r = cellRow(cell);
1971         if (is_long_tabular && row_info[r].caption)
1972                 return ret;
1973
1974         // usual cells
1975         if (getUsebox(cell) == BOX_PARBOX)
1976                 os << '}';
1977         else if (getUsebox(cell) == BOX_MINIPAGE) {
1978                 os << "%\n\\end{minipage}";
1979                 ret += 2;
1980         }
1981         if (getRotateCell(cell)) {
1982                 os << "%\n\\end{sideways}";
1983                 ++ret;
1984         }
1985         if (ismulticol) {
1986                 os << '}';
1987         }
1988         return ret;
1989 }
1990
1991
1992 int Tabular::TeXLongtableHeaderFooter(odocstream & os,
1993                                          OutputParams const & runparams) const
1994 {
1995         if (!is_long_tabular)
1996                 return 0;
1997
1998         int ret = 0;
1999         // output header info
2000         if (haveLTHead()) {
2001                 if (endhead.topDL) {
2002                         os << "\\hline\n";
2003                         ++ret;
2004                 }
2005                 for (row_type i = 0; i < row_info.size(); ++i) {
2006                         if (row_info[i].endhead) {
2007                                 ret += TeXRow(os, i, runparams);
2008                         }
2009                 }
2010                 if (endhead.bottomDL) {
2011                         os << "\\hline\n";
2012                         ++ret;
2013                 }
2014                 os << "\\endhead\n";
2015                 ++ret;
2016                 if (endfirsthead.empty) {
2017                         os << "\\endfirsthead\n";
2018                         ++ret;
2019                 }
2020         }
2021         // output firstheader info
2022         if (haveLTFirstHead()) {
2023                 if (endfirsthead.topDL) {
2024                         os << "\\hline\n";
2025                         ++ret;
2026                 }
2027                 for (row_type i = 0; i < row_info.size(); ++i) {
2028                         if (row_info[i].endfirsthead) {
2029                                 ret += TeXRow(os, i, runparams);
2030                         }
2031                 }
2032                 if (endfirsthead.bottomDL) {
2033                         os << "\\hline\n";
2034                         ++ret;
2035                 }
2036                 os << "\\endfirsthead\n";
2037                 ++ret;
2038         }
2039         // output footer info
2040         if (haveLTFoot()) {
2041                 if (endfoot.topDL) {
2042                         os << "\\hline\n";
2043                         ++ret;
2044                 }
2045                 for (row_type i = 0; i < row_info.size(); ++i) {
2046                         if (row_info[i].endfoot) {
2047                                 ret += TeXRow(os, i, runparams);
2048                         }
2049                 }
2050                 if (endfoot.bottomDL) {
2051                         os << "\\hline\n";
2052                         ++ret;
2053                 }
2054                 os << "\\endfoot\n";
2055                 ++ret;
2056                 if (endlastfoot.empty) {
2057                         os << "\\endlastfoot\n";
2058                         ++ret;
2059                 }
2060         }
2061         // output lastfooter info
2062         if (haveLTLastFoot()) {
2063                 if (endlastfoot.topDL) {
2064                         os << "\\hline\n";
2065                         ++ret;
2066                 }
2067                 for (row_type i = 0; i < row_info.size(); ++i) {
2068                         if (row_info[i].endlastfoot) {
2069                                 ret += TeXRow(os, i, runparams);
2070                         }
2071                 }
2072                 if (endlastfoot.bottomDL) {
2073                         os << "\\hline\n";
2074                         ++ret;
2075                 }
2076                 os << "\\endlastfoot\n";
2077                 ++ret;
2078         }
2079         return ret;
2080 }
2081
2082
2083 bool Tabular::isValidRow(row_type row) const
2084 {
2085         if (!is_long_tabular)
2086                 return true;
2087         return !row_info[row].endhead && !row_info[row].endfirsthead &&
2088                         !row_info[row].endfoot && !row_info[row].endlastfoot;
2089 }
2090
2091
2092 int Tabular::TeXRow(odocstream & os, row_type i,
2093                        OutputParams const & runparams) const
2094 {
2095         idx_type cell = cellIndex(i, 0);
2096         int ret = TeXTopHLine(os, i);
2097         if (row_info[i].top_space_default) {
2098                 if (use_booktabs)
2099                         os << "\\addlinespace\n";
2100                 else
2101                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2102                 ++ret;
2103         } else if(!row_info[i].top_space.zero()) {
2104                 if (use_booktabs)
2105                         os << "\\addlinespace["
2106                            << from_ascii(row_info[i].top_space.asLatexString())
2107                            << "]\n";
2108                 else {
2109                         os << "\\noalign{\\vskip"
2110                            << from_ascii(row_info[i].top_space.asLatexString())
2111                            << "}\n";
2112                 }
2113                 ++ret;
2114         }
2115         bool ismulticol = false;
2116         for (col_type j = 0; j < column_info.size(); ++j) {
2117                 if (isPartOfMultiColumn(i, j))
2118                         continue;
2119                 ret += TeXCellPreamble(os, cell, ismulticol);
2120                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2121
2122                 Paragraph const & par = inset->paragraphs().front();
2123                 bool rtl = par.isRTL(buffer().params())
2124                         && !par.empty()
2125                         && getPWidth(cell).zero();
2126
2127                 if (rtl) {
2128                         if (par.getParLanguage(buffer().params())->lang() ==
2129                         "farsi")
2130                                 os << "\\textFR{";
2131                         else if (par.getParLanguage(buffer().params())->lang() == "arabic_arabi")
2132                                 os << "\\textAR{";
2133                         // currently, remaning RTL languages are arabic_arabtex and hebrew
2134                         else
2135                                 os << "\\R{";
2136                 }
2137                 ret += inset->latex(os, runparams);
2138                 if (rtl)
2139                         os << '}';
2140
2141                 ret += TeXCellPostamble(os, cell, ismulticol);
2142                 if (!isLastCellInRow(cell)) { // not last cell in row
2143                         os << " & ";
2144                 }
2145                 ++cell;
2146         }
2147         os << "\\tabularnewline";
2148         if (row_info[i].bottom_space_default) {
2149                 if (use_booktabs)
2150                         os << "\\addlinespace";
2151                 else
2152                         os << "[\\doublerulesep]";
2153         } else if (!row_info[i].bottom_space.zero()) {
2154                 if (use_booktabs)
2155                         os << "\\addlinespace";
2156                 os << '['
2157                    << from_ascii(row_info[i].bottom_space.asLatexString())
2158                    << ']';
2159         }
2160         os << '\n';
2161         ++ret;
2162         ret += TeXBottomHLine(os, i);
2163         if (row_info[i].interline_space_default) {
2164                 if (use_booktabs)
2165                         os << "\\addlinespace\n";
2166                 else
2167                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2168                 ++ret;
2169         } else if (!row_info[i].interline_space.zero()) {
2170                 if (use_booktabs)
2171                         os << "\\addlinespace["
2172                            << from_ascii(row_info[i].interline_space.asLatexString())
2173                            << "]\n";
2174                 else
2175                         os << "\\noalign{\\vskip"
2176                            << from_ascii(row_info[i].interline_space.asLatexString())
2177                            << "}\n";
2178                 ++ret;
2179         }
2180         return ret;
2181 }
2182
2183
2184 int Tabular::latex(odocstream & os, OutputParams const & runparams) const
2185 {
2186         int ret = 0;
2187
2188         //+---------------------------------------------------------------------
2189         //+                      first the opening preamble                    +
2190         //+---------------------------------------------------------------------
2191
2192         if (rotate) {
2193                 os << "\\begin{sideways}\n";
2194                 ++ret;
2195         }
2196         if (is_long_tabular)
2197                 os << "\\begin{longtable}{";
2198         else
2199                 os << "\\begin{tabular}{";
2200
2201         for (col_type i = 0; i < column_info.size(); ++i) {
2202                 if (columnLeftLine(i))
2203                         os << '|';
2204                 if (!column_info[i].align_special.empty()) {
2205                         os << column_info[i].align_special;
2206                 } else {
2207                         if (!column_info[i].p_width.zero()) {
2208                                 switch (column_info[i].alignment) {
2209                                 case LYX_ALIGN_LEFT:
2210                                         os << ">{\\raggedright}";
2211                                         break;
2212                                 case LYX_ALIGN_RIGHT:
2213                                         os << ">{\\raggedleft}";
2214                                         break;
2215                                 case LYX_ALIGN_CENTER:
2216                                         os << ">{\\centering}";
2217                                         break;
2218                                 case LYX_ALIGN_NONE:
2219                                 case LYX_ALIGN_BLOCK:
2220                                 case LYX_ALIGN_LAYOUT:
2221                                 case LYX_ALIGN_SPECIAL:
2222                                         break;
2223                                 }
2224
2225                                 switch (column_info[i].valignment) {
2226                                 case LYX_VALIGN_TOP:
2227                                         os << 'p';
2228                                         break;
2229                                 case LYX_VALIGN_MIDDLE:
2230                                         os << 'm';
2231                                         break;
2232                                 case LYX_VALIGN_BOTTOM:
2233                                         os << 'b';
2234                                         break;
2235                         }
2236                                 os << '{'
2237                                    << from_ascii(column_info[i].p_width.asLatexString())
2238                                    << '}';
2239                         } else {
2240                                 switch (column_info[i].alignment) {
2241                                 case LYX_ALIGN_LEFT:
2242                                         os << 'l';
2243                                         break;
2244                                 case LYX_ALIGN_RIGHT:
2245                                         os << 'r';
2246                                         break;
2247                                 default:
2248                                         os << 'c';
2249                                         break;
2250                                 }
2251                         } // end if else !column_info[i].p_width
2252                 } // end if else !column_info[i].align_special
2253                 if (columnRightLine(i))
2254                         os << '|';
2255         }
2256         os << "}\n";
2257         ++ret;
2258
2259         ret += TeXLongtableHeaderFooter(os, runparams);
2260
2261         //+---------------------------------------------------------------------
2262         //+                      the single row and columns (cells)            +
2263         //+---------------------------------------------------------------------
2264
2265         for (row_type i = 0; i < row_info.size(); ++i) {
2266                 if (isValidRow(i)) {
2267                         ret += TeXRow(os, i, runparams);
2268                         if (is_long_tabular && row_info[i].newpage) {
2269                                 os << "\\newpage\n";
2270                                 ++ret;
2271                         }
2272                 }
2273         }
2274
2275         //+---------------------------------------------------------------------
2276         //+                      the closing of the tabular                    +
2277         //+---------------------------------------------------------------------
2278
2279         if (is_long_tabular)
2280                 os << "\\end{longtable}";
2281         else
2282                 os << "\\end{tabular}";
2283         if (rotate) {
2284                 os << "\n\\end{sideways}";
2285                 ++ret;
2286         }
2287
2288         return ret;
2289 }
2290
2291
2292 int Tabular::docbookRow(odocstream & os, row_type row,
2293                            OutputParams const & runparams) const
2294 {
2295         int ret = 0;
2296         idx_type cell = getFirstCellInRow(row);
2297
2298         os << "<row>\n";
2299         for (col_type j = 0; j < column_info.size(); ++j) {
2300                 if (isPartOfMultiColumn(row, j))
2301                         continue;
2302
2303                 os << "<entry align=\"";
2304                 switch (getAlignment(cell)) {
2305                 case LYX_ALIGN_LEFT:
2306                         os << "left";
2307                         break;
2308                 case LYX_ALIGN_RIGHT:
2309                         os << "right";
2310                         break;
2311                 default:
2312                         os << "center";
2313                         break;
2314                 }
2315
2316                 os << "\" valign=\"";
2317                 switch (getVAlignment(cell)) {
2318                 case LYX_VALIGN_TOP:
2319                         os << "top";
2320                         break;
2321                 case LYX_VALIGN_BOTTOM:
2322                         os << "bottom";
2323                         break;
2324                 case LYX_VALIGN_MIDDLE:
2325                         os << "middle";
2326                 }
2327                 os << '"';
2328
2329                 if (isMultiColumn(cell)) {
2330                         os << " namest=\"col" << j << "\" ";
2331                         os << "nameend=\"col" << j + columnSpan(cell) - 1<< '"';
2332                 }
2333
2334                 os << '>';
2335                 ret += cellInset(cell)->docbook(os, runparams);
2336                 os << "</entry>\n";
2337                 ++cell;
2338         }
2339         os << "</row>\n";
2340         return ret;
2341 }
2342
2343
2344 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2345 {
2346         int ret = 0;
2347
2348         //+---------------------------------------------------------------------
2349         //+                      first the opening preamble                    +
2350         //+---------------------------------------------------------------------
2351
2352         os << "<tgroup cols=\"" << column_info.size()
2353            << "\" colsep=\"1\" rowsep=\"1\">\n";
2354
2355         for (col_type i = 0; i < column_info.size(); ++i) {
2356                 os << "<colspec colname=\"col" << i << "\" align=\"";
2357                 switch (column_info[i].alignment) {
2358                 case LYX_ALIGN_LEFT:
2359                         os << "left";
2360                         break;
2361                 case LYX_ALIGN_RIGHT:
2362                         os << "right";
2363                         break;
2364                 default:
2365                         os << "center";
2366                         break;
2367                 }
2368                 os << '"';
2369                 if (runparams.flavor == OutputParams::XML)
2370                         os << '/';
2371                 os << ">\n";
2372                 ++ret;
2373         }
2374
2375         //+---------------------------------------------------------------------
2376         //+                      Long Tabular case                             +
2377         //+---------------------------------------------------------------------
2378
2379         // output header info
2380         if (haveLTHead() || haveLTFirstHead()) {
2381                 os << "<thead>\n";
2382                 ++ret;
2383                 for (row_type i = 0; i < row_info.size(); ++i) {
2384                         if (row_info[i].endhead || row_info[i].endfirsthead) {
2385                                 ret += docbookRow(os, i, runparams);
2386                         }
2387                 }
2388                 os << "</thead>\n";
2389                 ++ret;
2390         }
2391         // output footer info
2392         if (haveLTFoot() || haveLTLastFoot()) {
2393                 os << "<tfoot>\n";
2394                 ++ret;
2395                 for (row_type i = 0; i < row_info.size(); ++i) {
2396                         if (row_info[i].endfoot || row_info[i].endlastfoot) {
2397                                 ret += docbookRow(os, i, runparams);
2398                         }
2399                 }
2400                 os << "</tfoot>\n";
2401                 ++ret;
2402         }
2403
2404         //+---------------------------------------------------------------------
2405         //+                      the single row and columns (cells)            +
2406         //+---------------------------------------------------------------------
2407
2408         os << "<tbody>\n";
2409         ++ret;
2410         for (row_type i = 0; i < row_info.size(); ++i) {
2411                 if (isValidRow(i)) {
2412                         ret += docbookRow(os, i, runparams);
2413                 }
2414         }
2415         os << "</tbody>\n";
2416         ++ret;
2417         //+---------------------------------------------------------------------
2418         //+                      the closing of the tabular                    +
2419         //+---------------------------------------------------------------------
2420
2421         os << "</tgroup>";
2422         ++ret;
2423
2424         return ret;
2425 }
2426
2427
2428 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
2429                                    vector<unsigned int> const & clen) const
2430 {
2431         idx_type const fcell = getFirstCellInRow(row);
2432         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2433         idx_type tmp = 0;
2434
2435         for (idx_type i = fcell; i < n; ++i) {
2436                 if (topLine(i)) {
2437                         ++tmp;
2438                         break;
2439                 }
2440         }
2441         if (!tmp)
2442                 return false;
2443
2444         char_type ch;
2445         for (idx_type i = fcell; i < n; ++i) {
2446                 if (topLine(i)) {
2447                         if (leftLine(i))
2448                                 os << "+-";
2449                         else
2450                                 os << "--";
2451                         ch = '-';
2452                 } else {
2453                         os << "  ";
2454                         ch = ' ';
2455                 }
2456                 col_type column = cellColumn(i);
2457                 int len = clen[column];
2458                 while (column < column_info.size() - 1
2459                        && isPartOfMultiColumn(row, ++column))
2460                         len += clen[column] + 4;
2461                 os << docstring(len, ch);
2462                 if (topLine(i)) {
2463                         if (rightLine(i))
2464                                 os << "-+";
2465                         else
2466                                 os << "--";
2467                 } else {
2468                         os << "  ";
2469                 }
2470         }
2471         os << endl;
2472         return true;
2473 }
2474
2475
2476 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
2477                                       vector<unsigned int> const & clen) const
2478 {
2479         idx_type const fcell = getFirstCellInRow(row);
2480         idx_type const n = numberOfCellsInRow(fcell) + fcell;
2481         idx_type tmp = 0;
2482
2483         for (idx_type i = fcell; i < n; ++i) {
2484                 if (bottomLine(i)) {
2485                         ++tmp;
2486                         break;
2487                 }
2488         }
2489         if (!tmp)
2490                 return false;
2491
2492         char_type ch;
2493         for (idx_type i = fcell; i < n; ++i) {
2494                 if (bottomLine(i)) {
2495                         if (leftLine(i))
2496                                 os << "+-";
2497                         else
2498                                 os << "--";
2499                         ch = '-';
2500                 } else {
2501                         os << "  ";
2502                         ch = ' ';
2503                 }
2504                 col_type column = cellColumn(i);
2505                 int len = clen[column];
2506                 while (column < column_info.size() -1
2507                        && isPartOfMultiColumn(row, ++column))
2508                         len += clen[column] + 4;
2509                 os << docstring(len, ch);
2510                 if (bottomLine(i)) {
2511                         if (rightLine(i))
2512                                 os << "-+";
2513                         else
2514                                 os << "--";
2515                 } else {
2516                         os << "  ";
2517                 }
2518         }
2519         os << endl;
2520         return true;
2521 }
2522
2523
2524 void Tabular::plaintextPrintCell(odocstream & os,
2525                                OutputParams const & runparams,
2526                                idx_type cell, row_type row, col_type column,
2527                                vector<unsigned int> const & clen,
2528                                bool onlydata) const
2529 {
2530         odocstringstream sstr;
2531         cellInset(cell)->plaintext(sstr, runparams);
2532
2533         if (onlydata) {
2534                 os << sstr.str();
2535                 return;
2536         }
2537
2538         if (leftLine(cell))
2539                 os << "| ";
2540         else
2541                 os << "  ";
2542
2543         unsigned int len1 = sstr.str().length();
2544         unsigned int len2 = clen[column];
2545         while (column < column_info.size() -1
2546                && isPartOfMultiColumn(row, ++column))
2547                 len2 += clen[column] + 4;
2548         len2 -= len1;
2549
2550         switch (getAlignment(cell)) {
2551         default:
2552         case LYX_ALIGN_LEFT:
2553                 len1 = 0;
2554                 break;
2555         case LYX_ALIGN_RIGHT:
2556                 len1 = len2;
2557                 len2 = 0;
2558                 break;
2559         case LYX_ALIGN_CENTER:
2560                 len1 = len2 / 2;
2561                 len2 -= len1;
2562                 break;
2563         }
2564
2565         os << docstring(len1, ' ') << sstr.str()
2566            << docstring(len2, ' ');
2567
2568         if (rightLine(cell))
2569                 os << " |";
2570         else
2571                 os << "  ";
2572 }
2573
2574
2575 void Tabular::plaintext(odocstream & os,
2576                            OutputParams const & runparams, int const depth,
2577                            bool onlydata, char_type delim) const
2578 {
2579         // first calculate the width of the single columns
2580         vector<unsigned int> clen(column_info.size());
2581
2582         if (!onlydata) {
2583                 // first all non (real) multicolumn cells!
2584                 for (col_type j = 0; j < column_info.size(); ++j) {
2585                         clen[j] = 0;
2586                         for (row_type i = 0; i < row_info.size(); ++i) {
2587                                 idx_type cell = cellIndex(i, j);
2588                                 if (isMultiColumnReal(cell))
2589                                         continue;
2590                                 odocstringstream sstr;
2591                                 cellInset(cell)->plaintext(sstr, runparams);
2592                                 if (clen[j] < sstr.str().length())
2593                                         clen[j] = sstr.str().length();
2594                         }
2595                 }
2596                 // then all (real) multicolumn cells!
2597                 for (col_type j = 0; j < column_info.size(); ++j) {
2598                         for (row_type i = 0; i < row_info.size(); ++i) {
2599                                 idx_type cell = cellIndex(i, j);
2600                                 if (!isMultiColumnReal(cell) || isPartOfMultiColumn(i, j))
2601                                         continue;
2602                                 odocstringstream sstr;
2603                                 cellInset(cell)->plaintext(sstr, runparams);
2604                                 int len = int(sstr.str().length());
2605                                 idx_type const n = columnSpan(cell);
2606                                 for (col_type k = j; len > 0 && k < j + n - 1; ++k)
2607                                         len -= clen[k];
2608                                 if (len > int(clen[j + n - 1]))
2609                                         clen[j + n - 1] = len;
2610                         }
2611                 }
2612         }
2613         idx_type cell = 0;
2614         for (row_type i = 0; i < row_info.size(); ++i) {
2615                 if (!onlydata && plaintextTopHLine(os, i, clen))
2616                         os << docstring(depth * 2, ' ');
2617                 for (col_type j = 0; j < column_info.size(); ++j) {
2618                         if (isPartOfMultiColumn(i, j))
2619                                 continue;
2620                         if (onlydata && j > 0)
2621                                 // we don't use operator<< for single UCS4 character.
2622                                 // see explanation in docstream.h
2623                                 os.put(delim);
2624                         plaintextPrintCell(os, runparams, cell, i, j, clen, onlydata);
2625                         ++cell;
2626                 }
2627                 os << endl;
2628                 if (!onlydata) {
2629                         os << docstring(depth * 2, ' ');
2630                         if (plaintextBottomHLine(os, i, clen))
2631                                 os << docstring(depth * 2, ' ');
2632                 }
2633         }
2634 }
2635
2636
2637 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
2638 {
2639         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
2640 }
2641
2642
2643 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
2644                                                col_type column) const
2645 {
2646         return cell_info[row][column].inset;
2647 }
2648
2649
2650 void Tabular::setCellInset(row_type row, col_type column,
2651                               shared_ptr<InsetTableCell> ins) const
2652 {
2653         CellData & cd = cell_info[row][column];
2654         cd.inset = ins;
2655 }
2656
2657
2658 void Tabular::validate(LaTeXFeatures & features) const
2659 {
2660         features.require("NeedTabularnewline");
2661         if (use_booktabs)
2662                 features.require("booktabs");
2663         if (is_long_tabular)
2664                 features.require("longtable");
2665         if (needRotating())
2666                 features.require("rotating");
2667         for (idx_type cell = 0; cell < numberofcells; ++cell) {
2668                 if (getVAlignment(cell) != LYX_VALIGN_TOP ||
2669                      (!getPWidth(cell).zero() && !isMultiColumn(cell)))
2670                         features.require("array");
2671                 cellInset(cell)->validate(features);
2672         }
2673 }
2674
2675
2676 Tabular::BoxType Tabular::useParbox(idx_type cell) const
2677 {
2678         ParagraphList const & parlist = cellInset(cell)->paragraphs();
2679         ParagraphList::const_iterator cit = parlist.begin();
2680         ParagraphList::const_iterator end = parlist.end();
2681
2682         for (; cit != end; ++cit)
2683                 for (int i = 0; i < cit->size(); ++i)
2684                         if (cit->isNewline(i))
2685                                 return BOX_PARBOX;
2686
2687         return BOX_NONE;
2688 }
2689
2690
2691 /////////////////////////////////////////////////////////////////////
2692 //
2693 // InsetTableCell
2694 //
2695 /////////////////////////////////////////////////////////////////////
2696
2697 InsetTableCell::InsetTableCell(Buffer const & buf)
2698         : InsetText(buf), isFixedWidth(false)
2699 {}
2700
2701
2702 bool InsetTableCell::forcePlainLayout(idx_type) const
2703 {
2704         return !isFixedWidth;
2705 }
2706
2707 bool InsetTableCell::allowParagraphCustomization(idx_type) const
2708 {
2709         return isFixedWidth;
2710 }
2711
2712 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
2713         FuncStatus & status) const
2714 {
2715         bool enabled;
2716         switch (cmd.action) {
2717         case LFUN_LAYOUT:
2718                 enabled = !forcePlainLayout();
2719                 break;
2720         case LFUN_LAYOUT_PARAGRAPH:
2721                 enabled = allowParagraphCustomization();
2722                 break;
2723         default:
2724                 return InsetText::getStatus(cur, cmd, status);
2725         }
2726         status.setEnabled(enabled);
2727         return true;
2728 }
2729
2730 /////////////////////////////////////////////////////////////////////
2731 //
2732 // InsetTabular
2733 //
2734 /////////////////////////////////////////////////////////////////////
2735
2736 InsetTabular::InsetTabular(Buffer const & buf, row_type rows,
2737                            col_type columns)
2738         : tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
2739         rowselect_(false), colselect_(false)
2740 {
2741         setBuffer(const_cast<Buffer &>(buf)); // FIXME: remove later
2742 }
2743
2744
2745 InsetTabular::InsetTabular(InsetTabular const & tab)
2746         : Inset(tab), tabular(tab.tabular),  scx_(0)
2747 {
2748         setBuffer(const_cast<Buffer &>(tab.buffer())); // FIXME: remove later
2749 }
2750
2751
2752 InsetTabular::~InsetTabular()
2753 {
2754         hideDialogs("tabular", this);
2755 }
2756
2757
2758 bool InsetTabular::insetAllowed(InsetCode code) const
2759 {
2760         if (code == MATHMACRO_CODE)
2761                 return false;
2762
2763         return true;
2764 }
2765
2766
2767 void InsetTabular::write(ostream & os) const
2768 {
2769         os << "Tabular" << endl;
2770         tabular.write(os);
2771 }
2772
2773
2774 docstring InsetTabular::contextMenu(BufferView const &, int, int) const
2775 {
2776         // FIXME: depending on the selection state, we could offer a different menu.
2777         return from_ascii("context-tabular");
2778 }
2779
2780
2781 void InsetTabular::read(Lexer & lex)
2782 {
2783         //bool const old_format = (lex.getString() == "\\LyXTable");
2784
2785         tabular.read(lex);
2786
2787         //if (old_format)
2788         //      return;
2789
2790         lex.next();
2791         string token = lex.getString();
2792         while (lex && token != "\\end_inset") {
2793                 lex.next();
2794                 token = lex.getString();
2795         }
2796         if (!lex)
2797                 lex.printError("Missing \\end_inset at this point. ");
2798 }
2799
2800
2801 int InsetTabular::rowFromY(Cursor & cur, int y) const
2802 {
2803         // top y coordinate of tabular
2804         int h = yo(cur.bv()) - tabular.rowAscent(0);
2805         size_t nrows = tabular.row_info.size();
2806         row_type r = 0;
2807         for (; r < nrows && y > h; ++r) {
2808                 h += tabular.rowAscent(r);
2809                 h += tabular.rowDescent(r);
2810                 h += tabular.getAdditionalHeight(r);
2811         }
2812         return r - 1;
2813 }
2814
2815
2816 int InsetTabular::columnFromX(Cursor & cur, int x) const
2817 {
2818         // left x coordinate of tabular
2819         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
2820         size_t ncols = tabular.column_info.size();
2821         col_type c = 0;
2822         for (; c < ncols && x > w; ++c)
2823                 w += tabular.columnWidth(c);
2824         return c - 1;
2825 }
2826
2827
2828 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
2829 {
2830         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
2831         //      mi.base.textwidth << "\n";
2832         if (!mi.base.bv) {
2833                 LYXERR0("need bv");
2834                 LASSERT(false, /**/);
2835         }
2836
2837         row_type i = 0;
2838         for (idx_type cell = 0; i < tabular.row_info.size(); ++i) {
2839                 int maxAsc = 0;
2840                 int maxDesc = 0;
2841                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
2842                         if (tabular.isPartOfMultiColumn(i, j))
2843                                 // Multicolumn cell, but not first one
2844                                 continue;
2845                         Dimension dim;
2846                         MetricsInfo m = mi;
2847                         Length p_width;
2848                         if (tabular.cell_info[i][j].multicolumn ==
2849                                 Tabular::CELL_BEGIN_OF_MULTICOLUMN)
2850                                 p_width = tabular.cellInfo(cell).p_width;
2851                         else
2852                                 p_width = tabular.column_info[j].p_width;
2853                         if (!p_width.zero())
2854                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
2855                         tabular.cellInset(cell)->metrics(m, dim);
2856                         if (!p_width.zero())
2857                                 dim.wid = m.base.textwidth;
2858                         tabular.setCellWidth(cell, dim.wid);
2859                         maxAsc  = max(maxAsc, dim.asc);
2860                         maxDesc = max(maxDesc, dim.des);
2861                         ++cell;
2862                 }
2863                 int const top_space = tabular.row_info[i].top_space_default ?
2864                         default_line_space :
2865                         tabular.row_info[i].top_space.inPixels(mi.base.textwidth);
2866                 tabular.setRowAscent(i, maxAsc + ADD_TO_HEIGHT + top_space);
2867                 int const bottom_space = tabular.row_info[i].bottom_space_default ?
2868                         default_line_space :
2869                         tabular.row_info[i].bottom_space.inPixels(mi.base.textwidth);
2870                 tabular.setRowDescent(i, maxDesc + ADD_TO_HEIGHT + bottom_space);
2871         }
2872         tabular.updateColumnWidths();
2873         dim.asc = tabular.rowAscent(0);
2874         dim.des = tabular.height() - dim.asc;
2875         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
2876 }
2877
2878
2879 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
2880 {
2881         //lyxerr << "InsetTabular::draw: " << x << " " << y << endl;
2882         BufferView * bv = pi.base.bv;
2883
2884         // FIXME: As the full backrgound is painted in drawSelection(),
2885         // we have no choice but to do a full repaint for the Text cells.
2886         pi.full_repaint = true;
2887
2888         resetPos(bv->cursor());
2889
2890         x += scx_;
2891         x += ADD_TO_TABULAR_WIDTH;
2892
2893         bool const original_drawing_state = pi.pain.isDrawingEnabled();
2894
2895         idx_type idx = 0;
2896         first_visible_cell = Tabular::npos;
2897         for (row_type i = 0; i < tabular.row_info.size(); ++i) {
2898                 int nx = x;
2899                 int const a = tabular.rowAscent(i);
2900                 int const d = tabular.rowDescent(i);
2901                 idx = tabular.cellIndex(i, 0);
2902                 for (col_type j = 0; j < tabular.column_info.size(); ++j) {
2903                         if (tabular.isPartOfMultiColumn(i, j))
2904                                 continue;
2905                         if (first_visible_cell == Tabular::npos)
2906                                 first_visible_cell = idx;
2907
2908                         int const cx = nx + tabular.getBeginningOfTextInCell(idx);
2909                         // Cache the Inset position.
2910                         bv->coordCache().insets().add(cell(idx).get(), cx, y);
2911                         if (nx + tabular.columnWidth(idx) < 0
2912                             || nx > bv->workWidth()
2913                             || y + d < 0
2914                             || y - a > bv->workHeight()) {
2915                                 pi.pain.setDrawingEnabled(false);
2916                                 cell(idx)->draw(pi, cx, y);
2917                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2918                                 pi.pain.setDrawingEnabled(original_drawing_state);
2919                         } else {
2920                                 cell(idx)->draw(pi, cx, y);
2921                                 drawCellLines(pi.pain, nx, y, i, idx, pi.erased_);
2922                         }
2923                         nx += tabular.columnWidth(idx);
2924                         ++idx;
2925                 }
2926
2927                 if (i + 1 < tabular.row_info.size())
2928                         y += d + tabular.rowAscent(i + 1) +
2929                                 tabular.getAdditionalHeight(i + 1);
2930         }
2931 }
2932
2933
2934 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
2935 {
2936         Cursor & cur = pi.base.bv->cursor();
2937
2938         x += scx_ + ADD_TO_TABULAR_WIDTH;
2939
2940         // FIXME: it is wrong to completely paint the background
2941         // if we want to do single row painting.
2942
2943         // Paint background of current tabular
2944         int const w = tabular.width();
2945         int const h = tabular.height();
2946         int yy = y - tabular.rowAscent(0);
2947         pi.pain.fillRectangle(x, yy, w, h, backgroundColor());
2948
2949         if (!cur.selection())
2950                 return;
2951         if (&cur.inset() != this)
2952                 return;
2953
2954         //resetPos(cur);
2955
2956
2957         if (tablemode(cur)) {
2958                 row_type rs, re;
2959                 col_type cs, ce;
2960                 getSelection(cur, rs, re, cs, ce);
2961                 y -= tabular.rowAscent(0);
2962                 for (row_type j = 0; j < tabular.row_info.size(); ++j) {
2963                         int const a = tabular.rowAscent(j);
2964                         int const h = a + tabular.rowDescent(j);
2965                         int xx = x;
2966                         y += tabular.getAdditionalHeight(j);
2967                         for (col_type i = 0; i < tabular.column_info.size(); ++i) {
2968                                 if (tabular.isPartOfMultiColumn(j, i))
2969                                         continue;
2970                                 idx_type const cell =
2971                                         tabular.cellIndex(j, i);
2972                                 int const w = tabular.columnWidth(cell);
2973                                 if (i >= cs && i <= ce && j >= rs && j <= re)
2974                                         pi.pain.fillRectangle(xx, y, w, h,
2975                                                               Color_selection);
2976                                 xx += w;
2977                         }
2978                         y += h;
2979                 }
2980
2981         } else {
2982                 x += cellXPos(cur.idx());
2983                 x += tabular.getBeginningOfTextInCell(cur.idx());
2984                 cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
2985         }
2986 }
2987
2988
2989 void InsetTabular::drawCellLines(Painter & pain, int x, int y,
2990                                  row_type row, idx_type cell, bool erased) const
2991 {
2992         int x2 = x + tabular.columnWidth(cell);
2993         bool on_off = false;
2994         ColorCode col = Color_tabularline;
2995         ColorCode onoffcol = Color_tabularonoffline;
2996
2997         if (erased) {
2998                 col = Color_deletedtext;
2999                 onoffcol = Color_deletedtext;
3000         }
3001
3002         if (!tabular.topAlreadyDrawn(cell)) {
3003                 on_off = !tabular.topLine(cell);
3004                 pain.line(x, y - tabular.rowAscent(row),
3005                           x2, y -  tabular.rowAscent(row),
3006                           on_off ? onoffcol : col,
3007                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3008         }
3009         on_off = !tabular.bottomLine(cell);
3010         pain.line(x, y + tabular.rowDescent(row),
3011                   x2, y + tabular.rowDescent(row),
3012                   on_off ? onoffcol : col,
3013                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3014         if (!tabular.leftAlreadyDrawn(cell)) {
3015                 on_off = !tabular.leftLine(cell);
3016                 pain.line(x, y -  tabular.rowAscent(row),
3017                           x, y +  tabular.rowDescent(row),
3018                           on_off ? onoffcol : col,
3019                           on_off ? Painter::line_onoffdash : Painter::line_solid);
3020         }
3021         on_off = !tabular.rightLine(cell);
3022         pain.line(x2 - tabular.getAdditionalWidth(cell),
3023                   y -  tabular.rowAscent(row),
3024                   x2 - tabular.getAdditionalWidth(cell),
3025                   y +  tabular.rowDescent(row),
3026                   on_off ? onoffcol : col,
3027                   on_off ? Painter::line_onoffdash : Painter::line_solid);
3028 }
3029
3030
3031 docstring InsetTabular::editMessage() const
3032 {
3033         return _("Opened table");
3034 }
3035
3036
3037 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3038 {
3039         //lyxerr << "InsetTabular::edit: " << this << endl;
3040         cur.finishUndo();
3041         cur.selection() = false;
3042         cur.push(*this);
3043         if (front) {
3044                 if (isRightToLeft(cur))
3045                         cur.idx() = tabular.getLastCellInRow(0);
3046                 else
3047                         cur.idx() = 0;
3048                 cur.pit() = 0;
3049                 cur.pos() = 0;
3050         } else {
3051                 if (isRightToLeft(cur))
3052                         cur.idx() = tabular.getFirstCellInRow(tabular.row_info.size() - 1);
3053                 else
3054                         cur.idx() = tabular.numberofcells - 1;
3055                 cur.pit() = 0;
3056                 cur.pos() = cur.lastpos(); // FIXME crude guess
3057         }
3058         // FIXME: this accesses the position cache before it is initialized
3059         //resetPos(cur);
3060         //cur.bv().fitCursor();
3061 }
3062
3063
3064 void InsetTabular::updateLabels(ParIterator const & it)
3065 {
3066         // In a longtable, tell captions what the current float is
3067         Counters & cnts = buffer().params().documentClass().counters();
3068         string const saveflt = cnts.current_float();
3069         if (tabular.is_long_tabular)
3070                 cnts.current_float("table");
3071
3072         ParIterator it2 = it;
3073         it2.forwardPos();
3074         size_t const end = it2.nargs();
3075         for ( ; it2.idx() < end; it2.top().forwardIdx())
3076                 lyx::updateLabels(buffer(), it2);
3077
3078         //reset afterwards
3079         if (tabular.is_long_tabular)
3080                 cnts.current_float(saveflt);
3081 }
3082
3083
3084 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3085 {
3086         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3087                              << "\n  cur:" << cur);
3088         CursorSlice sl = cur.top();
3089         Cursor & bvcur = cur.bv().cursor();
3090
3091         switch (cmd.action) {
3092
3093         case LFUN_MOUSE_PRESS: {
3094                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3095                 // select row
3096                 if (cmd.x < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3097                         || cmd.x > xo(cur.bv()) + tabular.width()) {
3098                         row_type r = rowFromY(cur, cmd.y);
3099                         cur.idx() = tabular.getFirstCellInRow(r);
3100                         cur.pos() = 0;
3101                         cur.resetAnchor();
3102                         cur.idx() = tabular.getLastCellInRow(r);
3103                         cur.pos() = cur.lastpos();
3104                         cur.selection() = true;
3105                         bvcur = cur; 
3106                         rowselect_ = true;
3107                         break;
3108                 }
3109                 // select column
3110                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0);
3111                 if (cmd.y < y0 + ADD_TO_TABULAR_WIDTH 
3112                         || cmd.y > y0 + tabular.height()) {
3113                         col_type c = columnFromX(cur, cmd.x);
3114                         cur.idx() = tabular.cellIndex(0, c);
3115                         cur.pos() = 0;
3116                         cur.resetAnchor();
3117                         cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3118                         cur.pos() = cur.lastpos();
3119                         cur.selection() = true;
3120                         bvcur = cur; 
3121                         colselect_ = true;
3122                         break;
3123                 }
3124                 // do not reset cursor/selection if we have selected
3125                 // some cells (bug 2715).
3126                 if (cmd.button() == mouse_button::button3
3127                     && &bvcur.selBegin().inset() == this 
3128                     && tablemode(bvcur)) 
3129                         ;
3130                 else
3131                         // Let InsetTableCell do it
3132                         cell(cur.idx())->dispatch(cur, cmd);
3133                 break;
3134         }
3135         case LFUN_MOUSE_MOTION:
3136                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3137                 if (cmd.button() == mouse_button::button1) {
3138                         // only accept motions to places not deeper nested than the real anchor
3139                         if (!bvcur.anchor_.hasPart(cur)) {
3140                                 cur.undispatched();
3141                                 break;
3142                         }
3143                         // select (additional) row
3144                         if (rowselect_) {
3145                                 row_type r = rowFromY(cur, cmd.y);
3146                                 cur.idx() = tabular.getLastCellInRow(r);
3147                                 bvcur.setCursor(cur);
3148                                 bvcur.selection() = true;
3149                                 break;
3150                         }
3151                         // select (additional) column
3152                         if (colselect_) {
3153                                 col_type c = columnFromX(cur, cmd.x);
3154                                 cur.idx() = tabular.cellIndex(tabular.row_info.size() - 1, c);
3155                                 bvcur.setCursor(cur);
3156                                 bvcur.selection() = true;
3157                                 break;
3158                         }
3159                         // only update if selection changes
3160                         if (bvcur.idx() == cur.idx() &&
3161                                 !(bvcur.anchor_.idx() == cur.idx() && bvcur.pos() != cur.pos()))
3162                                 cur.noUpdate();
3163                         setCursorFromCoordinates(cur, cmd.x, cmd.y);
3164                         bvcur.setCursor(cur);
3165                         bvcur.selection() = true;
3166                 }
3167                 break;
3168
3169         case LFUN_MOUSE_RELEASE:
3170                 rowselect_ = false;
3171                 colselect_ = false;
3172                 break;
3173
3174         case LFUN_CELL_BACKWARD:
3175                 movePrevCell(cur);
3176                 cur.selection() = false;
3177                 break;
3178
3179         case LFUN_CELL_FORWARD:
3180                 moveNextCell(cur);
3181                 cur.selection() = false;
3182                 break;
3183         case LFUN_CHAR_FORWARD_SELECT:
3184         case LFUN_CHAR_FORWARD:
3185         case LFUN_CHAR_BACKWARD_SELECT:
3186         case LFUN_CHAR_BACKWARD:
3187         case LFUN_CHAR_RIGHT_SELECT:
3188         case LFUN_CHAR_RIGHT:
3189         case LFUN_CHAR_LEFT_SELECT:
3190         case LFUN_CHAR_LEFT: {
3191
3192                 // determine whether we move to next or previous cell, where to enter 
3193                 // the new cell from, and which command to "finish" (i.e., exit the
3194                 // inset) with:
3195                 bool next_cell;
3196                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3197                 FuncCode finish_lfun;
3198
3199                 if (cmd.action == LFUN_CHAR_FORWARD 
3200                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
3201                         next_cell = true;
3202                         finish_lfun = LFUN_FINISHED_FORWARD;
3203                 }
3204                 else if (cmd.action == LFUN_CHAR_BACKWARD
3205                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
3206                         next_cell = false;
3207                         finish_lfun = LFUN_FINISHED_BACKWARD;
3208                 }
3209                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3210                 // table's direction.
3211                 else {
3212                         bool right = (cmd.action == LFUN_CHAR_RIGHT
3213                                                         || cmd.action == LFUN_CHAR_RIGHT_SELECT);
3214                         next_cell = (isRightToLeft(cur) != right);
3215                         
3216                         if (lyxrc.visual_cursor) {
3217                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3218                         }
3219
3220                         if (right)
3221                                 finish_lfun = LFUN_FINISHED_RIGHT;
3222                         else
3223                                 finish_lfun = LFUN_FINISHED_LEFT;
3224                 }
3225                 
3226
3227                 // finally, now that we know what we want to do, do it!
3228                 cell(cur.idx())->dispatch(cur, cmd);
3229                 if (!cur.result().dispatched()) {
3230                         // move to next/prev cell, as appropriate
3231                         LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
3232                                 << " cell from: " << int(entry_from));
3233                         if (next_cell)
3234                                 moveNextCell(cur, entry_from);
3235                         else
3236                                 movePrevCell(cur, entry_from);
3237                         // if we're exiting the table, call the appropriate FINISHED lfun
3238                         if (sl == cur.top())
3239                                 cmd = FuncRequest(finish_lfun);
3240                         else
3241                                 cur.dispatched();
3242                 }
3243                 break;
3244
3245         }
3246
3247         case LFUN_DOWN_SELECT:
3248         case LFUN_DOWN:
3249                 cell(cur.idx())->dispatch(cur, cmd);
3250                 cur.dispatched(); // override the cell's decision
3251                 if (sl == cur.top())
3252                         // if our Text didn't do anything to the cursor
3253                         // then we try to put the cursor into the cell below
3254                         // setting also the right targetX.
3255                         if (tabular.cellRow(cur.idx()) != tabular.row_info.size() - 1) {
3256                                 cur.idx() = tabular.cellBelow(cur.idx());
3257                                 cur.pit() = 0;
3258                                 TextMetrics const & tm =
3259                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
3260                                 cur.pos() = tm.x2pos(cur.pit(), 0, cur.targetX());
3261                         }
3262                 if (sl == cur.top()) {
3263                         // we trick it to go to forward after leaving the
3264                         // tabular.
3265                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
3266                         cur.undispatched();
3267                 }
3268                 break;
3269
3270         case LFUN_UP_SELECT:
3271         case LFUN_UP:
3272                 cell(cur.idx())->dispatch(cur, cmd);
3273                 cur.dispatched(); // override the cell's decision
3274                 if (sl == cur.top())
3275                         // if our Text didn't do anything to the cursor
3276                         // then we try to put the cursor into the cell above
3277                         // setting also the right targetX.
3278                         if (tabular.cellRow(cur.idx()) != 0) {
3279                                 cur.idx() = tabular.cellAbove(cur.idx());
3280                                 cur.pit() = cur.lastpit();
3281                                 Text const * text = cell(cur.idx())->getText(0);
3282                                 TextMetrics const & tm = cur.bv().textMetrics(text);
3283                                 ParagraphMetrics const & pm =
3284                                         tm.parMetrics(cur.lastpit());
3285                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, cur.targetX());
3286                         }
3287                 if (sl == cur.top()) {
3288                         cmd = FuncRequest(LFUN_UP);
3289                         cur.undispatched();
3290                 }
3291                 break;
3292
3293 //      case LFUN_SCREEN_DOWN: {
3294 //              //if (hasSelection())
3295 //              //      cur.selection() = false;
3296 //              col_type const col = tabular.cellColumn(cur.idx());
3297 //              int const t =   cur.bv().top_y() + cur.bv().height();
3298 //              if (t < yo() + tabular.getHeightOfTabular()) {
3299 //                      cur.bv().scrollDocView(t);
3300 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3301 //              } else {
3302 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
3303 //              }
3304 //              cur.par() = 0;
3305 //              cur.pos() = 0;
3306 //              break;
3307 //      }
3308 //
3309 //      case LFUN_SCREEN_UP: {
3310 //              //if (hasSelection())
3311 //              //      cur.selection() = false;
3312 //              col_type const col = tabular.cellColumn(cur.idx());
3313 //              int const t =   cur.bv().top_y() + cur.bv().height();
3314 //              if (yo() < 0) {
3315 //                      cur.bv().scrollDocView(t);
3316 //                      if (yo() > 0)
3317 //                              cur.idx() = col;
3318 //                      else
3319 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
3320 //              } else {
3321 //                      cur.idx() = col;
3322 //              }
3323 //              cur.par() = cur.lastpar();
3324 //              cur.pos() = cur.lastpos();
3325 //              break;
3326 //      }
3327
3328         case LFUN_LAYOUT_TABULAR:
3329                 cur.bv().showDialog("tabular", params2string(*this), this);
3330                 break;
3331
3332         case LFUN_INSET_DIALOG_UPDATE:
3333                 cur.bv().updateDialog("tabular", params2string(*this));
3334                 break;
3335
3336         case LFUN_TABULAR_FEATURE:
3337                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
3338                         cur.undispatched();
3339                 break;
3340
3341         // insert file functions
3342         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
3343         case LFUN_FILE_INSERT_PLAINTEXT: {
3344                 // FIXME UNICODE
3345                 docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
3346                         FileName(to_utf8(cmd.argument())));
3347                 if (tmpstr.empty())
3348                         break;
3349                 cur.recordUndoInset(INSERT_UNDO);
3350                 if (insertPlaintextString(cur.bv(), tmpstr, false)) {
3351                         // content has been replaced,
3352                         // so cursor might be invalid
3353                         cur.pos() = cur.lastpos();
3354                         cur.pit() = cur.lastpit();
3355                         bvcur.setCursor(cur);
3356                 } else
3357                         cur.undispatched();
3358                 break;
3359         }
3360
3361         case LFUN_CUT:
3362                 if (tablemode(cur)) {
3363                         if (copySelection(cur)) {
3364                                 cur.recordUndoInset(DELETE_UNDO);
3365                                 cutSelection(cur);
3366                         }
3367                 }
3368                 else
3369                         cell(cur.idx())->dispatch(cur, cmd);
3370                 break;
3371
3372         case LFUN_CHAR_DELETE_BACKWARD:
3373         case LFUN_CHAR_DELETE_FORWARD:
3374                 if (tablemode(cur)) {
3375                         cur.recordUndoInset(DELETE_UNDO);
3376                         cutSelection(cur);
3377                 }
3378                 else
3379                         cell(cur.idx())->dispatch(cur, cmd);
3380                 break;
3381
3382         case LFUN_COPY:
3383                 if (!cur.selection())
3384                         break;
3385                 if (tablemode(cur)) {
3386                         cur.finishUndo();
3387                         copySelection(cur);
3388                 } else
3389                         cell(cur.idx())->dispatch(cur, cmd);
3390                 break;
3391
3392         case LFUN_CLIPBOARD_PASTE:
3393         case LFUN_PRIMARY_SELECTION_PASTE: {
3394                 docstring const clip = (cmd.action == LFUN_CLIPBOARD_PASTE) ?
3395                         theClipboard().getAsText() :
3396                         theSelection().get();
3397                 if (clip.empty())
3398                         break;
3399                 // pass to InsertPlaintextString, but
3400                 // only if we have multi-cell content
3401                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
3402                         cur.recordUndoInset(INSERT_UNDO);
3403                         if (insertPlaintextString(cur.bv(), clip, false)) {
3404                                 // content has been replaced,
3405                                 // so cursor might be invalid
3406                                 cur.pos() = cur.lastpos();
3407                                 cur.pit() = cur.lastpit();
3408                                 bvcur.setCursor(cur);
3409                                 break;
3410                         }
3411                 }
3412                 // Let the cell handle normal text
3413                 cell(cur.idx())->dispatch(cur, cmd);
3414                 break;
3415         }
3416
3417         case LFUN_PASTE:
3418                 if (!tabularStackDirty()) {
3419                         cell(cur.idx())->dispatch(cur, cmd);
3420                         break;
3421                 }
3422                 if (theClipboard().isInternal() ||
3423                     !theClipboard().hasInternal() && theClipboard().hasLyXContents()) {
3424                         cur.recordUndoInset(INSERT_UNDO);
3425                         pasteClipboard(cur);
3426                 }
3427                 break;
3428
3429         case LFUN_FONT_EMPH:
3430         case LFUN_FONT_BOLD:
3431         case LFUN_FONT_ROMAN:
3432         case LFUN_FONT_NOUN:
3433         case LFUN_FONT_ITAL:
3434         case LFUN_FONT_FRAK:
3435         case LFUN_FONT_TYPEWRITER:
3436         case LFUN_FONT_SANS:
3437         case LFUN_TEXTSTYLE_APPLY:
3438         case LFUN_TEXTSTYLE_UPDATE:
3439         case LFUN_FONT_SIZE:
3440         case LFUN_FONT_UNDERLINE:
3441         case LFUN_LANGUAGE:
3442         case LFUN_WORD_CAPITALIZE:
3443         case LFUN_WORD_UPCASE:
3444         case LFUN_WORD_LOWCASE:
3445         case LFUN_CHARS_TRANSPOSE:
3446                 if (tablemode(cur)) {
3447                         row_type rs, re;
3448                         col_type cs, ce;
3449                         getSelection(cur, rs, re, cs, ce);
3450                         Cursor tmpcur = cur;
3451                         for (row_type i = rs; i <= re; ++i) {
3452                                 for (col_type j = cs; j <= ce; ++j) {
3453                                         // cursor follows cell:
3454                                         tmpcur.idx() = tabular.cellIndex(i, j);
3455                                         // select this cell only:
3456                                         tmpcur.pit() = 0;
3457                                         tmpcur.pos() = 0;
3458                                         tmpcur.resetAnchor();
3459                                         tmpcur.pit() = tmpcur.lastpit();
3460                                         tmpcur.pos() = tmpcur.top().lastpos();
3461                                         tmpcur.setCursor(tmpcur);
3462                                         tmpcur.setSelection();
3463                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
3464                                 }
3465                         }
3466                         break;
3467                 } else {
3468                         cell(cur.idx())->dispatch(cur, cmd);
3469                         break;
3470                 }
3471         default:
3472                 // we try to handle this event in the insets dispatch function.
3473                 cell(cur.idx())->dispatch(cur, cmd);
3474                 break;
3475         }
3476 }
3477
3478
3479 // function sets an object as defined in func_status.h:
3480 // states OK, Unknown, Disabled, On, Off.
3481 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
3482         FuncStatus & status) const
3483 {
3484         switch (cmd.action) {
3485         case LFUN_TABULAR_FEATURE: {
3486                 int action = Tabular::LAST_ACTION;
3487                 int i = 0;
3488                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
3489                         string const tmp = tabularFeature[i].feature;
3490                         if (tmp == to_utf8(cmd.argument()).substr(0, tmp.length())) {
3491                                 action = tabularFeature[i].action;
3492                                 break;
3493                         }
3494                 }
3495                 if (action == Tabular::LAST_ACTION) {
3496                         status.clear();
3497                         status.unknown(true);
3498                         return true;
3499                 }
3500
3501                 string const argument
3502                         = ltrim(to_utf8(cmd.argument()).substr(tabularFeature[i].feature.length()));
3503
3504                 row_type sel_row_start = 0;
3505                 row_type sel_row_end = 0;
3506                 col_type sel_col_start = 0;
3507                 col_type sel_col_end = 0;
3508                 Tabular::ltType dummyltt;
3509                 bool flag = true;
3510
3511                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
3512
3513                 switch (action) {
3514                 case Tabular::SET_PWIDTH:
3515                 case Tabular::SET_MPWIDTH:
3516                 case Tabular::SET_SPECIAL_COLUMN:
3517                 case Tabular::SET_SPECIAL_MULTI:
3518                 case Tabular::APPEND_ROW:
3519                 case Tabular::APPEND_COLUMN:
3520                 case Tabular::DELETE_ROW:
3521                 case Tabular::DELETE_COLUMN:
3522                 case Tabular::COPY_ROW:
3523                 case Tabular::COPY_COLUMN:
3524                 case Tabular::SET_TOP_SPACE:
3525                 case Tabular::SET_BOTTOM_SPACE:
3526                 case Tabular::SET_INTERLINE_SPACE:
3527                         status.clear();
3528                         return true;
3529
3530                 case Tabular::MULTICOLUMN:
3531                         status.setEnabled(sel_row_start == sel_row_end);
3532                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
3533                         break;
3534
3535                 case Tabular::SET_ALL_LINES:
3536                 case Tabular::UNSET_ALL_LINES:
3537                 case Tabular::SET_BORDER_LINES:
3538                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3539                         break;
3540
3541                 case Tabular::TOGGLE_LINE_TOP:
3542                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3543                         status.setOnOff(tabular.topLine(cur.idx()));
3544                         break;
3545
3546                 case Tabular::TOGGLE_LINE_BOTTOM:
3547                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3548                         status.setOnOff(tabular.bottomLine(cur.idx()));
3549                         break;
3550
3551                 case Tabular::TOGGLE_LINE_LEFT:
3552                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3553                         status.setOnOff(tabular.leftLine(cur.idx()));
3554                         break;
3555
3556                 case Tabular::TOGGLE_LINE_RIGHT:
3557                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
3558                         status.setOnOff(tabular.rightLine(cur.idx()));
3559                         break;
3560
3561                 case Tabular::M_ALIGN_LEFT:
3562                         flag = false;
3563                 case Tabular::ALIGN_LEFT:
3564                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
3565                         break;
3566
3567                 case Tabular::M_ALIGN_RIGHT:
3568                         flag = false;
3569                 case Tabular::ALIGN_RIGHT:
3570                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
3571                         break;
3572
3573                 case Tabular::M_ALIGN_CENTER:
3574                         flag = false;
3575                 case Tabular::ALIGN_CENTER:
3576                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
3577                         break;
3578
3579                 case Tabular::ALIGN_BLOCK:
3580                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero());
3581                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
3582                         break;
3583
3584                 case Tabular::M_VALIGN_TOP:
3585                         flag = false;
3586                 case Tabular::VALIGN_TOP:
3587                         status.setOnOff(
3588                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
3589                         break;
3590
3591                 case Tabular::M_VALIGN_BOTTOM:
3592                         flag = false;
3593                 case Tabular::VALIGN_BOTTOM:
3594                         status.setOnOff(
3595                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
3596                         break;
3597
3598                 case Tabular::M_VALIGN_MIDDLE:
3599                         flag = false;
3600                 case Tabular::VALIGN_MIDDLE:
3601                         status.setOnOff(
3602                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
3603                         break;
3604
3605                 case Tabular::SET_LONGTABULAR:
3606                         status.setOnOff(tabular.is_long_tabular);
3607                         break;
3608
3609                 case Tabular::UNSET_LONGTABULAR:
3610                         status.setOnOff(!tabular.is_long_tabular);
3611                         break;
3612
3613                 case Tabular::TOGGLE_ROTATE_TABULAR:
3614                 case Tabular::SET_ROTATE_TABULAR:
3615                         status.setOnOff(tabular.rotate);
3616                         break;
3617
3618                 case Tabular::UNSET_ROTATE_TABULAR:
3619                         status.setOnOff(!tabular.rotate);
3620                         break;
3621
3622                 case Tabular::TOGGLE_ROTATE_CELL:
3623                 case Tabular::SET_ROTATE_CELL:
3624                         status.setOnOff(!oneCellHasRotationState(false,
3625                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3626                         break;
3627
3628                 case Tabular::UNSET_ROTATE_CELL:
3629                         status.setOnOff(!oneCellHasRotationState(true,
3630                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
3631                         break;
3632
3633                 case Tabular::SET_USEBOX:
3634                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
3635                         break;
3636
3637                 case Tabular::SET_LTFIRSTHEAD:
3638                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3639                         break;
3640
3641                 case Tabular::UNSET_LTFIRSTHEAD:
3642                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3643                         break;
3644
3645                 case Tabular::SET_LTHEAD:
3646                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
3647                         break;
3648
3649                 case Tabular::UNSET_LTHEAD:
3650                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
3651                         break;
3652
3653                 case Tabular::SET_LTFOOT:
3654                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3655                         break;
3656
3657                 case Tabular::UNSET_LTFOOT:
3658                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3659                         break;
3660
3661                 case Tabular::SET_LTLASTFOOT:
3662                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3663                         break;
3664
3665                 case Tabular::UNSET_LTLASTFOOT:
3666                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
3667                         break;
3668
3669                 case Tabular::SET_LTNEWPAGE:
3670                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
3671                         break;
3672
3673                 case Tabular::TOGGLE_LTCAPTION:
3674                         status.setEnabled(sel_row_start == sel_row_end);
3675                         status.setOnOff(tabular.ltCaption(sel_row_start));
3676                         break;
3677
3678                 case Tabular::SET_BOOKTABS:
3679                         status.setOnOff(tabular.use_booktabs);
3680                         break;
3681
3682                 case Tabular::UNSET_BOOKTABS:
3683                         status.setOnOff(!tabular.use_booktabs);
3684                         break;
3685
3686                 default:
3687                         status.clear();
3688                         status.setEnabled(false);
3689                         break;
3690                 }
3691                 return true;
3692         }
3693
3694         // These are only enabled inside tabular
3695         case LFUN_CELL_BACKWARD:
3696         case LFUN_CELL_FORWARD:
3697                 status.setEnabled(true);
3698                 return true;
3699
3700         // disable these with multiple cells selected
3701         case LFUN_INSET_INSERT:
3702         case LFUN_TABULAR_INSERT:
3703         case LFUN_FLEX_INSERT:
3704         case LFUN_FLOAT_INSERT:
3705         case LFUN_FLOAT_WIDE_INSERT:
3706         case LFUN_FOOTNOTE_INSERT:
3707         case LFUN_MARGINALNOTE_INSERT:
3708         case LFUN_MATH_INSERT:
3709         case LFUN_MATH_MODE:
3710         case LFUN_MATH_MUTATE:
3711         case LFUN_MATH_DISPLAY:
3712         case LFUN_NOTE_INSERT:
3713         case LFUN_OPTIONAL_INSERT:
3714         case LFUN_BOX_INSERT:
3715         case LFUN_BRANCH_INSERT:
3716         case LFUN_WRAP_INSERT:
3717         case LFUN_ERT_INSERT: {
3718                 if (tablemode(cur)) {
3719                         status.setEnabled(false);
3720                         return true;
3721                 } else
3722                         return cell(cur.idx())->getStatus(cur, cmd, status);
3723         }
3724
3725         // disable in non-fixed-width cells
3726         case LFUN_NEWLINE_INSERT:
3727         case LFUN_BREAK_PARAGRAPH: {
3728                 if (tabular.getPWidth(cur.idx()).zero()) {
3729                         status.setEnabled(false);
3730                         return true;
3731                 } else
3732                         return cell(cur.idx())->getStatus(cur, cmd, status);
3733         }
3734
3735         case LFUN_PASTE:
3736                 if (tabularStackDirty() && theClipboard().isInternal()) {
3737                         status.setEnabled(true);
3738                         return true;
3739                 } else
3740                         return cell(cur.idx())->getStatus(cur, cmd, status);
3741
3742         case LFUN_INSET_MODIFY:
3743                 if (insetCode(cmd.getArg(0)) == TABULAR_CODE) {
3744                         status.setEnabled(true);
3745                         return true;
3746                 }
3747                 // Fall through
3748
3749         default:
3750                 // we try to handle this event in the insets dispatch function.
3751                 return cell(cur.idx())->getStatus(cur, cmd, status);
3752         }
3753 }
3754
3755
3756 int InsetTabular::latex(odocstream & os, OutputParams const & runparams) const
3757 {
3758         return tabular.latex(os, runparams);
3759 }
3760
3761
3762 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
3763 {
3764         os << '\n'; // output table on a new line
3765         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
3766         tabular.plaintext(os, runparams, dp, false, 0);
3767         return PLAINTEXT_NEWLINE;
3768 }
3769
3770
3771 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
3772 {
3773         int ret = 0;
3774         Inset * master = 0;
3775
3776         // FIXME: Why not pass a proper DocIterator here?
3777 #if 0
3778         // if the table is inside a float it doesn't need the informaltable
3779         // wrapper. Search for it.
3780         for (master = owner(); master; master = master->owner())
3781                 if (master->lyxCode() == FLOAT_CODE)
3782                         break;
3783 #endif
3784
3785         if (!master) {
3786                 os << "<informaltable>";
3787                 ++ret;
3788         }
3789         ret += tabular.docbook(os, runparams);
3790         if (!master) {
3791                 os << "</informaltable>";
3792                 ++ret;
3793         }
3794         return ret;
3795 }
3796
3797
3798 void InsetTabular::validate(LaTeXFeatures & features) const
3799 {
3800         tabular.validate(features);
3801 }
3802
3803
3804 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
3805 {
3806         return tabular.cellInset(idx);
3807 }
3808
3809
3810 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
3811 {
3812         return tabular.cellInset(idx);
3813 }
3814
3815
3816 void InsetTabular::cursorPos(BufferView const & bv,
3817                 CursorSlice const & sl, bool boundary, int & x, int & y) const
3818 {
3819         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
3820
3821         // y offset     correction
3822         int const row = tabular.cellRow(sl.idx());
3823         for (int i = 0; i <= row; ++i) {
3824                 if (i != 0) {
3825                         y += tabular.rowAscent(i);
3826                         y += tabular.getAdditionalHeight(i);
3827                 }
3828                 if (i != row)
3829                         y += tabular.rowDescent(i);
3830         }
3831
3832         // x offset correction
3833         int const col = tabular.cellColumn(sl.idx());
3834         int idx = tabular.cellIndex(row, 0);
3835         for (int j = 0; j < col; ++j) {
3836                 if (tabular.isPartOfMultiColumn(row, j))
3837                         continue;
3838                 x += tabular.columnWidth(idx);
3839                 ++idx;
3840         }
3841         x += tabular.getBeginningOfTextInCell(idx);
3842         x += ADD_TO_TABULAR_WIDTH;
3843         x += scx_;
3844 }
3845
3846
3847 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
3848 {
3849         int xx = 0;
3850         int yy = 0;
3851         Inset const & inset = *tabular.cellInset(cell);
3852         Point o = bv.coordCache().getInsets().xy(&inset);
3853         int const xbeg = o.x_ - tabular.getBeginningOfTextInCell(cell);
3854         int const xend = xbeg + tabular.columnWidth(cell);
3855         row_type const row = tabular.cellRow(cell);
3856         int const ybeg = o.y_ - tabular.rowAscent(row) -
3857                          tabular.getAdditionalHeight(row);
3858         int const yend = o.y_ + tabular.rowDescent(row);
3859
3860         if (x < xbeg)
3861                 xx = xbeg - x;
3862         else if (x > xend)
3863                 xx = x - xend;
3864
3865         if (y < ybeg)
3866                 yy = ybeg - y;
3867         else if (y > yend)
3868                 yy = y - yend;
3869
3870         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
3871         //       << " ybeg=" << ybeg << " yend=" << yend
3872         //       << " xx=" << xx << " yy=" << yy
3873         //       << " dist=" << xx + yy << endl;
3874         return xx + yy;
3875 }
3876
3877
3878 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
3879 {
3880         //lyxerr << "InsetTabular::editXY: " << this << endl;
3881         cur.selection() = false;
3882         cur.push(*this);
3883         cur.idx() = getNearestCell(cur.bv(), x, y);
3884         resetPos(cur);
3885         return cur.bv().textMetrics(&cell(cur.idx())->text_).editXY(cur, x, y);
3886 }
3887
3888
3889 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
3890 {
3891         cur.idx() = getNearestCell(cur.bv(), x, y);
3892         cur.bv().textMetrics(&cell(cur.idx())->text_).setCursorFromCoordinates(cur, x, y);
3893 }
3894
3895
3896 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
3897 {
3898         idx_type idx_min = 0;
3899         int dist_min = numeric_limits<int>::max();
3900         for (idx_type i = 0, n = nargs(); i != n; ++i) {
3901                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
3902                         int const d = dist(bv, i, x, y);
3903                         if (d < dist_min) {
3904                                 dist_min = d;
3905                                 idx_min = i;
3906                         }
3907                 }
3908         }
3909         return idx_min;
3910 }
3911
3912
3913 int InsetTabular::cellXPos(idx_type const cell) const
3914 {
3915         idx_type c = cell;
3916
3917         for (; !tabular.isFirstCellInRow(c); --c)
3918                 ;
3919         int lx = 0;
3920         for (; c < cell; ++c)
3921                 lx += tabular.columnWidth(c);
3922
3923         return lx;
3924 }
3925
3926
3927 void InsetTabular::resetPos(Cursor & cur) const
3928 {
3929         BufferView & bv = cur.bv();
3930         int const maxwidth = bv.workWidth();
3931
3932         if (&cur.inset() != this) {
3933                 scx_ = 0;
3934         } else {
3935                 int const X1 = 0;
3936                 int const X2 = maxwidth;
3937                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
3938                 int const x1 = xo(cur.bv()) + cellXPos(cur.idx()) + offset;
3939                 int const x2 = x1 + tabular.columnWidth(cur.idx());
3940
3941                 if (x1 < X1)
3942                         scx_ = X1 + 20 - x1;
3943                 else if (x2 > X2)
3944                         scx_ = X2 - 20 - x2;
3945                 else
3946                         scx_ = 0;
3947         }
3948
3949         cur.updateFlags(Update::Force | Update::FitCursor);
3950 }
3951
3952
3953 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
3954 {
3955         if (isRightToLeft(cur)) {
3956                 if (tabular.isFirstCellInRow(cur.idx())) {
3957                         row_type const row = tabular.cellRow(cur.idx());
3958                         if (row == tabular.row_info.size() - 1)
3959                                 return;
3960                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
3961                 } else {
3962                         if (cur.idx() == 0)
3963                                 return;
3964                         --cur.idx();
3965                 }
3966         } else {
3967                 if (tabular.isLastCell(cur.idx()))
3968                         return;
3969                 ++cur.idx();
3970         }
3971         cur.pit() = 0;
3972         cur.pos() = 0;
3973         cur.boundary(false);
3974
3975         // in visual mode, place cursor at extreme left or right
3976         
3977         switch(entry_from) {
3978
3979         case ENTRY_DIRECTION_RIGHT:
3980                 cur.posVisToRowExtremity(false /* !left */);
3981                 break;
3982         case ENTRY_DIRECTION_LEFT:
3983                 cur.posVisToRowExtremity(true /* left */);
3984                 break;
3985         case ENTRY_DIRECTION_IGNORE:
3986                 // nothing to do in this case
3987                 break;
3988
3989         }
3990
3991         resetPos(cur);
3992 }
3993
3994
3995 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
3996 {
3997         if (isRightToLeft(cur)) {
3998                 if (tabular.isLastCellInRow(cur.idx())) {
3999                         row_type const row = tabular.cellRow(cur.idx());
4000                         if (row == 0)
4001                                 return;
4002                         cur.idx() = tabular.getFirstCellInRow(row);
4003                         cur.idx() = tabular.cellAbove(cur.idx());
4004                 } else {
4005                         if (tabular.isLastCell(cur.idx()))
4006                                 return;
4007                         ++cur.idx();
4008                 }
4009         } else {
4010                 if (cur.idx() == 0) // first cell
4011                         return;
4012                 --cur.idx();
4013         }
4014         cur.pit() = cur.lastpit();
4015         cur.pos() = cur.lastpos();
4016
4017         // in visual mode, place cursor at extreme left or right
4018         
4019         switch(entry_from) {
4020
4021         case ENTRY_DIRECTION_RIGHT:
4022                 cur.posVisToRowExtremity(false /* !left */);
4023                 break;
4024         case ENTRY_DIRECTION_LEFT:
4025                 cur.posVisToRowExtremity(true /* left */);
4026                 break;
4027         case ENTRY_DIRECTION_IGNORE:
4028                 // nothing to do in this case
4029                 break;
4030
4031         }
4032
4033         // FIXME: this accesses the position cache before it is initialized
4034         //resetPos(cur);
4035 }
4036
4037
4038 bool InsetTabular::tabularFeatures(Cursor & cur, string const & what)
4039 {
4040         Tabular::Feature action = Tabular::LAST_ACTION;
4041
4042         int i = 0;
4043         for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4044                 string const tmp = tabularFeature[i].feature;
4045
4046                 if (tmp == what.substr(0, tmp.length())) {
4047                         //if (!compare(tabularFeatures[i].feature.c_str(), what.c_str(),
4048                         //tabularFeatures[i].feature.length()))
4049                         action = tabularFeature[i].action;
4050                         break;
4051                 }
4052         }
4053         if (action == Tabular::LAST_ACTION)
4054                 return false;
4055
4056         string const val =
4057                 ltrim(what.substr(tabularFeature[i].feature.length()));
4058         tabularFeatures(cur, action, val);
4059         return true;
4060 }
4061
4062
4063 static void checkLongtableSpecial(Tabular::ltType & ltt,
4064                           string const & special, bool & flag)
4065 {
4066         if (special == "dl_above") {
4067                 ltt.topDL = flag;
4068                 ltt.set = false;
4069         } else if (special == "dl_below") {
4070                 ltt.bottomDL = flag;
4071                 ltt.set = false;
4072         } else if (special == "empty") {
4073                 ltt.empty = flag;
4074                 ltt.set = false;
4075         } else if (flag) {
4076                 ltt.empty = false;
4077                 ltt.set = true;
4078         }
4079 }
4080
4081 bool InsetTabular::oneCellHasRotationState(bool rotated,
4082                 row_type row_start, row_type row_end,
4083                 col_type col_start, col_type col_end) const {
4084
4085         for (row_type i = row_start; i <= row_end; ++i) {
4086                 for (col_type j = col_start; j <= col_end; ++j) {
4087                         if (tabular.getRotateCell(tabular.cellIndex(i, j))
4088                                 == rotated) {
4089                                 return true;
4090                         }
4091                 }
4092         }
4093         return false;
4094 }
4095
4096 void InsetTabular::tabularFeatures(Cursor & cur,
4097         Tabular::Feature feature, string const & value)
4098 {
4099         col_type sel_col_start;
4100         col_type sel_col_end;
4101         row_type sel_row_start;
4102         row_type sel_row_end;
4103         bool setLines = false;
4104         LyXAlignment setAlign = LYX_ALIGN_LEFT;
4105         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
4106
4107         switch (feature) {
4108
4109         case Tabular::M_ALIGN_LEFT:
4110         case Tabular::ALIGN_LEFT:
4111                 setAlign = LYX_ALIGN_LEFT;
4112                 break;
4113
4114         case Tabular::M_ALIGN_RIGHT:
4115         case Tabular::ALIGN_RIGHT:
4116                 setAlign = LYX_ALIGN_RIGHT;
4117                 break;
4118
4119         case Tabular::M_ALIGN_CENTER:
4120         case Tabular::ALIGN_CENTER:
4121                 setAlign = LYX_ALIGN_CENTER;
4122                 break;
4123
4124         case Tabular::ALIGN_BLOCK:
4125                 setAlign = LYX_ALIGN_BLOCK;
4126                 break;
4127
4128         case Tabular::M_VALIGN_TOP:
4129         case Tabular::VALIGN_TOP:
4130                 setVAlign = Tabular::LYX_VALIGN_TOP;
4131                 break;
4132
4133         case Tabular::M_VALIGN_BOTTOM:
4134         case Tabular::VALIGN_BOTTOM:
4135                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
4136                 break;
4137
4138         case Tabular::M_VALIGN_MIDDLE:
4139         case Tabular::VALIGN_MIDDLE:
4140                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
4141                 break;
4142
4143         default:
4144                 break;
4145         }
4146
4147         cur.recordUndoInset(ATOMIC_UNDO);
4148
4149         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4150         row_type const row = tabular.cellRow(cur.idx());
4151         col_type const column = tabular.cellColumn(cur.idx());
4152         bool flag = true;
4153         Tabular::ltType ltt;
4154
4155         switch (feature) {
4156
4157         case Tabular::SET_PWIDTH: {
4158                 Length const len(value);
4159                 tabular.setColumnPWidth(cur, cur.idx(), len);
4160                 if (len.zero()
4161                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
4162                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
4163                 break;
4164         }
4165
4166         case Tabular::SET_MPWIDTH:
4167                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
4168                 break;
4169
4170         case Tabular::SET_SPECIAL_COLUMN:
4171         case Tabular::SET_SPECIAL_MULTI:
4172                 tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
4173                 break;
4174
4175         case Tabular::APPEND_ROW:
4176                 // append the row into the tabular
4177                 tabular.appendRow(cur.idx());
4178                 break;
4179
4180         case Tabular::APPEND_COLUMN:
4181                 // append the column into the tabular
4182                 tabular.appendColumn(cur.idx());
4183                 cur.idx() = tabular.cellIndex(row, column);
4184                 break;
4185
4186         case Tabular::DELETE_ROW:
4187                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4188                         tabular.deleteRow(sel_row_start);
4189                 if (sel_row_start >= tabular.row_info.size())
4190                         --sel_row_start;
4191                 cur.idx() = tabular.cellIndex(sel_row_start, column);
4192                 cur.pit() = 0;
4193                 cur.pos() = 0;
4194                 cur.selection() = false;
4195                 break;
4196
4197         case Tabular::DELETE_COLUMN:
4198                 for (col_type i = sel_col_start; i <= sel_col_end; ++i)
4199                         tabular.deleteColumn(sel_col_start);
4200                 if (sel_col_start >= tabular.column_info.size())
4201                         --sel_col_start;
4202                 cur.idx() = tabular.cellIndex(row, sel_col_start);
4203                 cur.pit() = 0;
4204                 cur.pos() = 0;
4205                 cur.selection() = false;
4206                 break;
4207
4208         case Tabular::COPY_ROW:
4209                 tabular.copyRow(row);
4210                 break;
4211
4212         case Tabular::COPY_COLUMN:
4213                 tabular.copyColumn(column);
4214                 cur.idx() = tabular.cellIndex(row, column);
4215                 break;
4216
4217         case Tabular::TOGGLE_LINE_TOP: {
4218                 bool lineSet = !tabular.topLine(cur.idx());
4219                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4220                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4221                                 tabular.setTopLine(tabular.cellIndex(i, j), lineSet);
4222                 break;
4223         }
4224
4225         case Tabular::TOGGLE_LINE_BOTTOM: {
4226                 bool lineSet = !tabular.bottomLine(cur.idx());
4227                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4228                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4229                                 tabular.setBottomLine(tabular.cellIndex(i, j), lineSet);
4230                 break;
4231         }
4232
4233         case Tabular::TOGGLE_LINE_LEFT: {
4234                 bool lineSet = !tabular.leftLine(cur.idx());
4235                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4236                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4237                                 tabular.setLeftLine(tabular.cellIndex(i, j), lineSet);
4238                 break;
4239         }
4240
4241         case Tabular::TOGGLE_LINE_RIGHT: {
4242                 bool lineSet = !tabular.rightLine(cur.idx());
4243                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4244                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4245                                 tabular.setRightLine(tabular.cellIndex(i, j), lineSet);
4246                 break;
4247         }
4248
4249         case Tabular::M_ALIGN_LEFT:
4250         case Tabular::M_ALIGN_RIGHT:
4251         case Tabular::M_ALIGN_CENTER:
4252                 flag = false;
4253         case Tabular::ALIGN_LEFT:
4254         case Tabular::ALIGN_RIGHT:
4255         case Tabular::ALIGN_CENTER:
4256         case Tabular::ALIGN_BLOCK:
4257                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4258                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4259                                 tabular.setAlignment(tabular.cellIndex(i, j), setAlign, flag);
4260                 break;
4261
4262         case Tabular::M_VALIGN_TOP:
4263         case Tabular::M_VALIGN_BOTTOM:
4264         case Tabular::M_VALIGN_MIDDLE:
4265                 flag = false;
4266         case Tabular::VALIGN_TOP:
4267         case Tabular::VALIGN_BOTTOM:
4268         case Tabular::VALIGN_MIDDLE:
4269                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4270                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4271                                 tabular.setVAlignment(tabular.cellIndex(i, j), setVAlign, flag);
4272                 break;
4273
4274         case Tabular::MULTICOLUMN: {
4275                 if (!cur.selection()) {
4276                         // just multicol for one single cell
4277                         // check whether we are completely in a multicol
4278                         if (tabular.isMultiColumn(cur.idx()))
4279                                 tabular.unsetMultiColumn(cur.idx());
4280                         else
4281                                 tabular.setMultiColumn(cur.idx(), 1);
4282                         break;
4283                 }
4284                 // we have a selection so this means we just add all this
4285                 // cells to form a multicolumn cell
4286                 idx_type const s_start = cur.selBegin().idx();
4287                 idx_type const s_end = cur.selEnd().idx();
4288                 tabular.setMultiColumn(s_start, s_end - s_start + 1);
4289                 cur.idx() = s_start;
4290                 cur.pit() = 0;
4291                 cur.pos() = 0;
4292                 cur.selection() = false;
4293                 break;
4294         }
4295
4296         case Tabular::SET_ALL_LINES:
4297                 setLines = true;
4298         case Tabular::UNSET_ALL_LINES:
4299                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4300                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4301                                 tabular.setAllLines(
4302                                         tabular.cellIndex(i,j), setLines);
4303                 break;
4304
4305         case Tabular::SET_BORDER_LINES:
4306                 for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4307                         tabular.setLeftLine(tabular.cellIndex(i, sel_col_start), true);
4308                         tabular.setRightLine(tabular.cellIndex(i, sel_col_end), true);
4309                 }
4310                 for (col_type j = sel_col_start; j <= sel_col_end; ++j) {
4311                         tabular.setTopLine(tabular.cellIndex(sel_row_start, j), true);
4312                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, j), true);
4313                 }
4314                 break;
4315
4316         case Tabular::SET_LONGTABULAR:
4317                 tabular.is_long_tabular = true;
4318                 break;
4319
4320         case Tabular::UNSET_LONGTABULAR:
4321                 tabular.is_long_tabular = false;
4322                 break;
4323
4324         case Tabular::SET_ROTATE_TABULAR:
4325                 tabular.rotate = true;
4326                 break;
4327
4328         case Tabular::UNSET_ROTATE_TABULAR:
4329                 tabular.rotate = false;
4330                 break;
4331
4332         case Tabular::TOGGLE_ROTATE_TABULAR:
4333                 tabular.rotate = !tabular.rotate;
4334                 break;
4335
4336         case Tabular::SET_ROTATE_CELL:
4337                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4338                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4339                                 tabular.setRotateCell(
4340                                         tabular.cellIndex(i, j), true);
4341                 break;
4342
4343         case Tabular::UNSET_ROTATE_CELL:
4344                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4345                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4346                                 tabular.setRotateCell(tabular.cellIndex(i, j), false);
4347                 break;
4348
4349         case Tabular::TOGGLE_ROTATE_CELL:
4350                 {
4351                 bool oneNotRotated = oneCellHasRotationState(false,
4352                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4353
4354                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4355                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4356                                 tabular.setRotateCell(tabular.cellIndex(i, j),
4357                                                                           oneNotRotated);
4358                 }
4359                 break;
4360
4361         case Tabular::SET_USEBOX: {
4362                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
4363                 if (val == tabular.getUsebox(cur.idx()))
4364                         val = Tabular::BOX_NONE;
4365                 for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4366                         for (col_type j = sel_col_start; j <= sel_col_end; ++j)
4367                                 tabular.setUsebox(tabular.cellIndex(i, j), val);
4368                 break;
4369         }
4370
4371         case Tabular::UNSET_LTFIRSTHEAD:
4372                 flag = false;
4373         case Tabular::SET_LTFIRSTHEAD:
4374                 tabular.getRowOfLTFirstHead(row, ltt);
4375                 checkLongtableSpecial(ltt, value, flag);
4376                 tabular.setLTHead(row, flag, ltt, true);
4377                 break;
4378
4379         case Tabular::UNSET_LTHEAD:
4380                 flag = false;
4381         case Tabular::SET_LTHEAD:
4382                 tabular.getRowOfLTHead(row, ltt);
4383                 checkLongtableSpecial(ltt, value, flag);
4384                 tabular.setLTHead(row, flag, ltt, false);
4385                 break;
4386
4387         case Tabular::UNSET_LTFOOT:
4388                 flag = false;
4389         case Tabular::SET_LTFOOT:
4390                 tabular.getRowOfLTFoot(row, ltt);
4391                 checkLongtableSpecial(ltt, value, flag);
4392                 tabular.setLTFoot(row, flag, ltt, false);
4393                 break;
4394
4395         case Tabular::UNSET_LTLASTFOOT:
4396                 flag = false;
4397         case Tabular::SET_LTLASTFOOT:
4398                 tabular.getRowOfLTLastFoot(row, ltt);
4399                 checkLongtableSpecial(ltt, value, flag);
4400                 tabular.setLTFoot(row, flag, ltt, true);
4401                 break;
4402
4403         case Tabular::SET_LTNEWPAGE:
4404                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
4405                 break;
4406
4407         case Tabular::TOGGLE_LTCAPTION:
4408                 cur.idx() = tabular.setLTCaption(row, !tabular.ltCaption(row));
4409                 cur.pit() = 0;
4410                 cur.pos() = 0;
4411                 cur.selection() = false;
4412                 break;
4413
4414         case Tabular::SET_BOOKTABS:
4415                 tabular.use_booktabs = true;
4416                 break;
4417
4418         case Tabular::UNSET_BOOKTABS:
4419                 tabular.use_booktabs = false;
4420                 break;
4421
4422         case Tabular::SET_TOP_SPACE: {
4423                 Length len;
4424                 if (value == "default")
4425                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4426                                 tabular.row_info[i].top_space_default = true;
4427                 else if (isValidLength(value, &len))
4428                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4429                                 tabular.row_info[i].top_space_default = false;
4430                                 tabular.row_info[i].top_space = len;
4431                         }
4432                 else
4433                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4434                                 tabular.row_info[i].top_space_default = false;
4435                                 tabular.row_info[i].top_space = len;
4436                         }
4437                 break;
4438         }
4439
4440         case Tabular::SET_BOTTOM_SPACE: {
4441                 Length len;
4442                 if (value == "default")
4443                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4444                                 tabular.row_info[i].bottom_space_default = true;
4445                 else if (isValidLength(value, &len))
4446                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4447                                 tabular.row_info[i].bottom_space_default = false;
4448                                 tabular.row_info[i].bottom_space = len;
4449                         }
4450                 else
4451                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4452                                 tabular.row_info[i].bottom_space_default = false;
4453                                 tabular.row_info[i].bottom_space = len;
4454                         }
4455                 break;
4456         }
4457
4458         case Tabular::SET_INTERLINE_SPACE: {
4459                 Length len;
4460                 if (value == "default")
4461                         for (row_type i = sel_row_start; i <= sel_row_end; ++i)
4462                                 tabular.row_info[i].interline_space_default = true;
4463                 else if (isValidLength(value, &len))
4464                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4465                                 tabular.row_info[i].interline_space_default = false;
4466                                 tabular.row_info[i].interline_space = len;
4467                         }
4468                 else
4469                         for (row_type i = sel_row_start; i <= sel_row_end; ++i) {
4470                                 tabular.row_info[i].interline_space_default = false;
4471                                 tabular.row_info[i].interline_space = len;
4472                         }
4473                 break;
4474         }
4475
4476         // dummy stuff just to avoid warnings
4477         case Tabular::LAST_ACTION:
4478                 break;
4479         }
4480 }
4481
4482
4483 bool InsetTabular::showInsetDialog(BufferView * bv) const
4484 {
4485         bv->showDialog("tabular", params2string(*this),
4486                 const_cast<InsetTabular *>(this));
4487         return true;
4488 }
4489
4490
4491 void InsetTabular::openLayoutDialog(BufferView * bv) const
4492 {
4493         bv->showDialog("tabular", params2string(*this),
4494                 const_cast<InsetTabular *>(this));
4495 }
4496
4497
4498 bool InsetTabular::copySelection(Cursor & cur)
4499 {
4500         if (!cur.selection())
4501                 return false;
4502
4503         row_type rs, re;
4504         col_type cs, ce;
4505         getSelection(cur, rs, re, cs, ce);
4506
4507         paste_tabular.reset(new Tabular(tabular));
4508
4509         for (row_type i = 0; i < rs; ++i)
4510                 paste_tabular->deleteRow(0);
4511
4512         row_type const rows = re - rs + 1;
4513         while (paste_tabular->row_info.size() > rows)
4514                 paste_tabular->deleteRow(rows);
4515
4516         for (col_type i = 0; i < cs; ++i)
4517                 paste_tabular->deleteColumn(0);
4518
4519         col_type const columns = ce - cs + 1;
4520         while (paste_tabular->column_info.size() > columns)
4521                 paste_tabular->deleteColumn(columns);
4522
4523         odocstringstream os;
4524         OutputParams const runparams(0);
4525         paste_tabular->plaintext(os, runparams, 0, true, '\t');
4526         // Needed for the "Edit->Paste recent" menu and the system clipboard.
4527         cap::copySelection(cur, os.str());
4528
4529         // mark tabular stack dirty
4530         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
4531         // when we (hopefully) have a one-for-all paste mechanism.
4532         // This must be called after cap::copySelection.
4533         dirtyTabularStack(true);
4534
4535         return true;
4536 }
4537
4538
4539 bool InsetTabular::pasteClipboard(Cursor & cur)
4540 {
4541         if (!paste_tabular)
4542                 return false;
4543         col_type const actcol = tabular.cellColumn(cur.idx());
4544         row_type const actrow = tabular.cellRow(cur.idx());
4545         for (row_type r1 = 0, r2 = actrow;
4546              r1 < paste_tabular->row_info.size() && r2 < tabular.row_info.size();
4547              ++r1, ++r2) {
4548                 for (col_type c1 = 0, c2 = actcol;
4549                     c1 < paste_tabular->column_info.size() && c2 < tabular.column_info.size();
4550                     ++c1, ++c2) {
4551                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
4552                             tabular.isPartOfMultiColumn(r2, c2))
4553                                 continue;
4554                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
4555                                 --c2;
4556                                 continue;
4557                         }
4558                         if (tabular.isPartOfMultiColumn(r2, c2)) {
4559                                 --c1;
4560                                 continue;
4561                         }
4562                         shared_ptr<InsetTableCell> inset(
4563                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
4564                         tabular.setCellInset(r2, c2, inset);
4565                         // FIXME: change tracking (MG)
4566                         inset->setChange(Change(cur.buffer().params().trackChanges ?
4567                                                 Change::INSERTED : Change::UNCHANGED));
4568                         cur.pos() = 0;
4569                 }
4570         }
4571         return true;
4572 }
4573
4574
4575 void InsetTabular::cutSelection(Cursor & cur)
4576 {
4577         if (!cur.selection())
4578                 return;
4579
4580         row_type rs, re;
4581         col_type cs, ce;
4582         getSelection(cur, rs, re, cs, ce);
4583         for (row_type i = rs; i <= re; ++i) {
4584                 for (col_type j = cs; j <= ce; ++j) {
4585                         shared_ptr<InsetTableCell> t
4586                                 = cell(tabular.cellIndex(i, j));
4587                         if (cur.buffer().params().trackChanges)
4588                                 // FIXME: Change tracking (MG)
4589                                 t->setChange(Change(Change::DELETED));
4590                         else
4591                                 t->clear();
4592                 }
4593         }
4594
4595         // cursor position might be invalid now
4596         if (cur.pit() > cur.lastpit())
4597                 cur.pit() = cur.lastpit();
4598         if (cur.pos() > cur.lastpos())
4599                 cur.pos() = cur.lastpos();
4600         cur.clearSelection();
4601 }
4602
4603
4604 bool InsetTabular::isRightToLeft(Cursor & cur) const
4605 {
4606         LASSERT(cur.depth() > 1, /**/);
4607         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
4608         pos_type const parentpos = cur[cur.depth() - 2].pos();
4609         return parentpar.getFontSettings(cur.bv().buffer().params(),
4610                                          parentpos).language()->rightToLeft();
4611 }
4612
4613
4614 void InsetTabular::getSelection(Cursor & cur,
4615         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
4616 {
4617         CursorSlice const & beg = cur.selBegin();
4618         CursorSlice const & end = cur.selEnd();
4619         cs = tabular.cellColumn(beg.idx());
4620         ce = tabular.cellColumn(end.idx());
4621         if (cs > ce) {
4622                 ce = cs;
4623                 cs = tabular.cellColumn(end.idx());
4624         } else {
4625                 ce = tabular.cellRightColumn(end.idx());
4626         }
4627
4628         rs = tabular.cellRow(beg.idx());
4629         re = tabular.cellRow(end.idx());
4630         if (rs > re)
4631                 swap(rs, re);
4632 }
4633
4634
4635 Text * InsetTabular::getText(int idx) const
4636 {
4637         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
4638 }
4639
4640
4641 void InsetTabular::setChange(Change const & change)
4642 {
4643         for (idx_type idx = 0; idx < nargs(); ++idx)
4644                 cell(idx)->setChange(change);
4645 }
4646
4647
4648 void InsetTabular::acceptChanges(BufferParams const & bparams)
4649 {
4650         for (idx_type idx = 0; idx < nargs(); ++idx)
4651                 cell(idx)->acceptChanges(bparams);
4652 }
4653
4654
4655 void InsetTabular::rejectChanges(BufferParams const & bparams)
4656 {
4657         for (idx_type idx = 0; idx < nargs(); ++idx)
4658                 cell(idx)->rejectChanges(bparams);
4659 }
4660
4661
4662 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
4663 {
4664         return tabular.getPWidth(cell).zero();
4665 }
4666
4667
4668 bool InsetTabular::forcePlainLayout(idx_type cell) const
4669 {
4670         return !tabular.getPWidth(cell).zero();
4671 }
4672
4673
4674 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
4675                                      bool usePaste)
4676 {
4677         if (buf.length() <= 0)
4678                 return true;
4679
4680         col_type cols = 1;
4681         row_type rows = 1;
4682         col_type maxCols = 1;
4683         size_t const len = buf.length();
4684         size_t p = 0;
4685
4686         while (p < len &&
4687                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
4688                 switch (buf[p]) {
4689                 case '\t':
4690                         ++cols;
4691                         break;
4692                 case '\n':
4693                         if (p + 1 < len)
4694                                 ++rows;
4695                         maxCols = max(cols, maxCols);
4696                         cols = 1;
4697                         break;
4698                 }
4699                 ++p;
4700         }
4701         maxCols = max(cols, maxCols);
4702         Tabular * loctab;
4703         idx_type cell = 0;
4704         col_type ocol = 0;
4705         row_type row = 0;
4706         if (usePaste) {
4707                 paste_tabular.reset(new Tabular(buffer(), rows, maxCols));
4708                 loctab = paste_tabular.get();
4709                 cols = 0;
4710                 dirtyTabularStack(true);
4711         } else {
4712                 loctab = &tabular;
4713                 cell = bv.cursor().idx();
4714                 ocol = tabular.cellColumn(cell);
4715                 row = tabular.cellRow(cell);
4716         }
4717
4718         size_t op = 0;
4719         idx_type const cells = loctab->numberofcells;
4720         p = 0;
4721         cols = ocol;
4722         rows = loctab->row_info.size();
4723         col_type const columns = loctab->column_info.size();
4724
4725         while (cell < cells && p < len && row < rows &&
4726                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
4727         {
4728                 if (p >= len)
4729                         break;
4730                 switch (buf[p]) {
4731                 case '\t':
4732                         // we can only set this if we are not too far right
4733                         if (cols < columns) {
4734                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4735                                 Font const font = bv.textMetrics(&inset->text_).
4736                                         displayFont(0, 0);
4737                                 inset->setText(buf.substr(op, p - op), font,
4738                                                buffer().params().trackChanges);
4739                                 ++cols;
4740                                 ++cell;
4741                         }
4742                         break;
4743                 case '\n':
4744                         // we can only set this if we are not too far right
4745                         if (cols < columns) {
4746                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
4747                                 Font const font = bv.textMetrics(&inset->text_).
4748                                         displayFont(0, 0);
4749                                 inset->setText(buf.substr(op, p - op), font,
4750                                                buffer().params().trackChanges);
4751                         }
4752                         cols = ocol;
4753                         ++row;
4754                         if (row < rows)
4755                                 cell = loctab->cellIndex(row, cols);
4756                         break;
4757                 }
4758                 ++p;
4759                 op = p;
4760         }
4761         // check for the last cell if there is no trailing '\n'
4762         if (cell < cells && op < len) {
4763                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
4764                 Font const font = bv.textMetrics(&inset->text_).displayFont(0, 0);
4765                 inset->setText(buf.substr(op, len - op), font,
4766                         buffer().params().trackChanges);
4767         }
4768         return true;
4769 }
4770
4771
4772 void InsetTabular::addPreview(PreviewLoader & loader) const
4773 {
4774         row_type const rows = tabular.row_info.size();
4775         col_type const columns = tabular.column_info.size();
4776         for (row_type i = 0; i < rows; ++i) {
4777                 for (col_type j = 0; j < columns; ++j)
4778                         tabular.cellInset(i, j)->addPreview(loader);
4779         }
4780 }
4781
4782
4783 bool InsetTabular::tablemode(Cursor & cur) const
4784 {
4785         return cur.selection() && cur.selBegin().idx() != cur.selEnd().idx();
4786 }
4787
4788
4789 bool InsetTabular::completionSupported(Cursor const & cur) const
4790 {
4791         Cursor const & bvCur = cur.bv().cursor();
4792         if (&bvCur.inset() != this)
4793                 return false;
4794         return cur.text()->completionSupported(cur);
4795 }
4796
4797
4798 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
4799 {
4800         return completionSupported(cur);
4801 }
4802
4803
4804 bool InsetTabular::automaticInlineCompletion() const
4805 {
4806         return lyxrc.completion_inline_text;
4807 }
4808
4809
4810 bool InsetTabular::automaticPopupCompletion() const
4811 {
4812         return lyxrc.completion_popup_text;
4813 }
4814
4815
4816 bool InsetTabular::showCompletionCursor() const
4817 {
4818         return lyxrc.completion_cursor_text;
4819 }
4820
4821
4822 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
4823 {
4824         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
4825 }
4826
4827
4828 docstring InsetTabular::completionPrefix(Cursor const & cur) const
4829 {
4830         if (!completionSupported(cur))
4831                 return docstring();
4832         return cur.text()->completionPrefix(cur);
4833 }
4834
4835
4836 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
4837 {
4838         if (!completionSupported(cur))
4839                 return false;
4840
4841         return cur.text()->insertCompletion(cur, s, finished);
4842 }
4843
4844
4845 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
4846                                     Dimension & dim) const
4847 {
4848         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
4849         tm.completionPosAndDim(cur, x, y, dim);
4850 }
4851
4852
4853 void InsetTabular::string2params(string const & in, InsetTabular & inset)
4854 {
4855         istringstream data(in);
4856         Lexer lex;
4857         lex.setStream(data);
4858
4859         if (in.empty())
4860                 return;
4861
4862         string token;
4863         lex >> token;
4864         if (!lex || token != "tabular") {
4865                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
4866                 return;
4867         }
4868
4869         // This is part of the inset proper that is usually swallowed
4870         // by Buffer::readInset
4871         lex >> token;
4872         if (!lex || token != "Tabular") {
4873                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
4874                 return;
4875         }
4876
4877         inset.read(lex);
4878 }
4879
4880
4881 string InsetTabular::params2string(InsetTabular const & inset)
4882 {
4883         ostringstream data;
4884         data << "tabular" << ' ';
4885         inset.write(data);
4886         data << "\\end_inset\n";
4887         return data.str();
4888 }
4889
4890
4891 } // namespace lyx