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