]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Prevent accidental usage of wrong copy constructor
[lyx.git] / src / CutAndPaste.cpp
1 /**
2  * \file CutAndPaste.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "BranchList.h"
19 #include "Buffer.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
24 #include "Changes.h"
25 #include "Cursor.h"
26 #include "Encoding.h"
27 #include "ErrorList.h"
28 #include "FuncCode.h"
29 #include "FuncRequest.h"
30 #include "InsetIterator.h"
31 #include "InsetList.h"
32 #include "Language.h"
33 #include "LyX.h"
34 #include "LyXRC.h"
35 #include "Text.h"
36 #include "Paragraph.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "TextClass.h"
40
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetBranch.h"
43 #include "insets/InsetCommand.h"
44 #include "insets/InsetFlex.h"
45 #include "insets/InsetGraphics.h"
46 #include "insets/InsetGraphicsParams.h"
47 #include "insets/InsetInclude.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetTabular.h"
50
51 #include "mathed/MathData.h"
52 #include "mathed/InsetMath.h"
53 #include "mathed/InsetMathHull.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathSupport.h"
56
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/limited_stack.h"
62 #include "support/lstrings.h"
63 #include "support/TempFile.h"
64
65 #include "frontends/alert.h"
66 #include "frontends/Clipboard.h"
67 #include "frontends/Selection.h"
68
69 #include <boost/tuple/tuple.hpp>
70 #include <boost/next_prior.hpp>
71
72 #include <string>
73
74 using namespace std;
75 using namespace lyx::support;
76 using lyx::frontend::Clipboard;
77
78 namespace lyx {
79
80 namespace {
81
82 typedef pair<pit_type, int> PitPosPair;
83
84 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
85
86 CutStack theCuts(10);
87 // persistent selection, cleared until the next selection
88 CutStack selectionBuffer(1);
89
90 // store whether the tabular stack is newer than the normal copy stack
91 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
92 // when we (hopefully) have a one-for-all paste mechanism.
93 bool dirty_tabular_stack_ = false;
94
95
96 bool checkPastePossible(int index)
97 {
98         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
99 }
100
101
102 struct PasteReturnValue {
103         PasteReturnValue(pit_type r_par, pos_type r_pos, bool r_nu) :
104           par(r_par), pos(r_pos), needupdate(r_nu)
105         {}
106
107         pit_type par;
108         pos_type pos;
109         bool needupdate;
110 };
111
112 PasteReturnValue
113 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
114                      DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
115                      ErrorList & errorlist)
116 {
117         Buffer const & buffer = *cur.buffer();
118         pit_type pit = cur.pit();
119         pos_type pos = cur.pos();
120         bool need_update = false;
121
122         if (parlist.empty())
123                 return PasteReturnValue(pit, pos, need_update);
124
125         InsetText * target_inset = cur.inset().asInsetText();
126         if (!target_inset) {
127                 InsetTabular * it = cur.inset().asInsetTabular();
128                 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
129         }
130         LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
131
132         ParagraphList & pars = target_inset->paragraphs();
133         LASSERT(pos <= pars[pit].size(),
134                         return PasteReturnValue(pit, pos, need_update));
135
136         // Make a copy of the CaP paragraphs.
137         ParagraphList insertion = parlist;
138
139         // Now remove all out of the pars which is NOT allowed in the
140         // new environment and set also another font if that is required.
141
142         // Convert newline to paragraph break in ParbreakIsNewline
143         if (target_inset->getLayout().parbreakIsNewline()
144             || pars[pit].layout().parbreak_is_newline) {
145                 for (size_t i = 0; i != insertion.size(); ++i) {
146                         for (pos_type j = 0; j != insertion[i].size(); ++j) {
147                                 if (insertion[i].isNewline(j)) {
148                                         // do not track deletion of newline
149                                         insertion[i].eraseChar(j, false);
150                                         insertion[i].setInsetOwner(target_inset);
151                                         breakParagraphConservative(
152                                                         buffer.params(),
153                                                         insertion, i, j);
154                                         break;
155                                 }
156                         }
157                 }
158         }
159
160         // set the paragraphs to plain layout if necessary
161         DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
162         if (cur.inset().usePlainLayout()) {
163                 bool forcePlainLayout = cur.inset().forcePlainLayout();
164                 Layout const & plainLayout = newDocClass->plainLayout();
165                 Layout const & defaultLayout = newDocClass->defaultLayout();
166                 ParagraphList::iterator const end = insertion.end();
167                 ParagraphList::iterator par = insertion.begin();
168                 for (; par != end; ++par) {
169                         Layout const & parLayout = par->layout();
170                         if (forcePlainLayout || parLayout == defaultLayout)
171                                 par->setLayout(plainLayout);
172                 }
173         }       else { // check if we need to reset from plain layout
174                 Layout const & defaultLayout = newDocClass->defaultLayout();
175                 Layout const & plainLayout = newDocClass->plainLayout();
176                 ParagraphList::iterator const end = insertion.end();
177                 ParagraphList::iterator par = insertion.begin();
178                 for (; par != end; ++par) {
179                         Layout const & parLayout = par->layout();
180                         if (parLayout == plainLayout)
181                                 par->setLayout(defaultLayout);
182                 }
183         }
184
185         InsetText in(cur.buffer());
186         // Make sure there is no class difference.
187         in.paragraphs().clear();
188         // This works without copying any paragraph data because we have
189         // a specialized swap method for ParagraphList. This is important
190         // since we store pointers to insets at some places and we don't
191         // want to invalidate them.
192         insertion.swap(in.paragraphs());
193         cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
194         insertion.swap(in.paragraphs());
195
196         ParagraphList::iterator tmpbuf = insertion.begin();
197         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
198
199         depth_type max_depth = pars[pit].getMaxDepthAfter();
200
201         for (; tmpbuf != insertion.end(); ++tmpbuf) {
202                 // If we have a negative jump so that the depth would
203                 // go below 0 depth then we have to redo the delta to
204                 // this new max depth level so that subsequent
205                 // paragraphs are aligned correctly to this paragraph
206                 // at level 0.
207                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
208                         depth_delta = 0;
209
210                 // Set the right depth so that we are not too deep or shallow.
211                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
212                 if (tmpbuf->params().depth() > max_depth)
213                         tmpbuf->params().depth(max_depth);
214
215                 // Set max_depth for the next paragraph
216                 max_depth = tmpbuf->getMaxDepthAfter();
217
218                 // Set the inset owner of this paragraph.
219                 tmpbuf->setInsetOwner(target_inset);
220                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
221                         // do not track deletion of invalid insets
222                         if (Inset * inset = tmpbuf->getInset(i))
223                                 if (!target_inset->insetAllowed(inset->lyxCode()))
224                                         tmpbuf->eraseChar(i--, false);
225                 }
226
227                 tmpbuf->setChange(Change(buffer.params().track_changes ?
228                                          Change::INSERTED : Change::UNCHANGED));
229         }
230
231         bool const empty = pars[pit].empty();
232         if (!empty) {
233                 // Make the buf exactly the same layout as the cursor
234                 // paragraph.
235                 insertion.begin()->makeSameLayout(pars[pit]);
236         }
237
238         // Prepare the paragraphs and insets for insertion.
239         insertion.swap(in.paragraphs());
240
241         InsetIterator const i_end = inset_iterator_end(in);
242         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
243                 // Even though this will also be done later, it has to be done here 
244                 // since some inset might going to try to access
245                 // the buffer() member.
246                 it->setBuffer(const_cast<Buffer &>(buffer));
247                 switch (it->lyxCode()) {
248
249                 case MATH_HULL_CODE: {
250                         // check for equation labels and resolve duplicates
251                         InsetMathHull * ins = it->asInsetMath()->asHullInset();
252                         std::vector<InsetLabel *> labels = ins->getLabels();
253                         for (size_t i = 0; i != labels.size(); ++i) {
254                                 if (!labels[i])
255                                         continue;
256                                 InsetLabel * lab = labels[i];
257                                 docstring const oldname = lab->getParam("name");
258                                 lab->updateLabel(oldname);
259                                 // We need to update the buffer reference cache.
260                                 need_update = true;
261                                 docstring const newname = lab->getParam("name");
262                                 if (oldname == newname)
263                                         continue;
264                                 // adapt the references
265                                 for (InsetIterator itt = inset_iterator_begin(in);
266                                       itt != i_end; ++itt) {
267                                         if (itt->lyxCode() == REF_CODE) {
268                                                 InsetCommand * ref = itt->asInsetCommand();
269                                                 if (ref->getParam("reference") == oldname)
270                                                         ref->setParam("reference", newname);
271                                         } else if (itt->lyxCode() == MATH_REF_CODE) {
272                                                 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
273                                                 // this is necessary to prevent an uninitialized
274                                                 // buffer when the RefInset is in a MathBox.
275                                                 // FIXME audit setBuffer calls
276                                                 mi->setBuffer(const_cast<Buffer &>(buffer));
277                                                 if (mi->getTarget() == oldname)
278                                                         mi->changeTarget(newname);
279                                         }
280                                 }
281                         }
282                         break;
283                 }
284
285                 case LABEL_CODE: {
286                         // check for duplicates
287                         InsetLabel & lab = static_cast<InsetLabel &>(*it);
288                         docstring const oldname = lab.getParam("name");
289                         lab.updateLabel(oldname);
290                         // We need to update the buffer reference cache.
291                         need_update = true;
292                         docstring const newname = lab.getParam("name");
293                         if (oldname == newname)
294                                 break;
295                         // adapt the references
296                         for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
297                                 if (itt->lyxCode() == REF_CODE) {
298                                         InsetCommand & ref = static_cast<InsetCommand &>(*itt);
299                                         if (ref.getParam("reference") == oldname)
300                                                 ref.setParam("reference", newname);
301                                 } else if (itt->lyxCode() == MATH_REF_CODE) {
302                                         InsetMathRef * mi = itt->asInsetMath()->asRefInset();
303                                         // this is necessary to prevent an uninitialized
304                                         // buffer when the RefInset is in a MathBox.
305                                         // FIXME audit setBuffer calls
306                                         mi->setBuffer(const_cast<Buffer &>(buffer));
307                                         if (mi->getTarget() == oldname)
308                                                 mi->changeTarget(newname);
309                                 }
310                         }
311                         break;
312                 }
313
314                 case INCLUDE_CODE: {
315                         InsetInclude & inc = static_cast<InsetInclude &>(*it);
316                         inc.updateCommand();
317                         // We need to update the list of included files.
318                         need_update = true;
319                         break;
320                 }
321
322                 case BIBITEM_CODE: {
323                         // check for duplicates
324                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
325                         docstring const oldkey = bib.getParam("key");
326                         bib.updateCommand(oldkey, false);
327                         // We need to update the buffer reference cache.
328                         need_update = true;
329                         docstring const newkey = bib.getParam("key");
330                         if (oldkey == newkey)
331                                 break;
332                         // adapt the references
333                         for (InsetIterator itt = inset_iterator_begin(in);
334                              itt != i_end; ++itt) {
335                                 if (itt->lyxCode() == CITE_CODE) {
336                                         InsetCommand * ref = itt->asInsetCommand();
337                                         if (ref->getParam("key") == oldkey)
338                                                 ref->setParam("key", newkey);
339                                 }
340                         }
341                         break;
342                 }
343
344                 case BRANCH_CODE: {
345                         // check if branch is known to target buffer
346                         // or its master
347                         InsetBranch & br = static_cast<InsetBranch &>(*it);
348                         docstring const name = br.branch();
349                         if (name.empty())
350                                 break;
351                         bool const is_child = (&buffer != buffer.masterBuffer());
352                         BranchList branchlist = buffer.params().branchlist();
353                         if ((!is_child && branchlist.find(name))
354                             || (is_child && (branchlist.find(name)
355                                 || buffer.masterBuffer()->params().branchlist().find(name))))
356                                 break;
357                         if (tmpbuffer) {
358                                 // This is for a temporary buffer, so simply create the branch.
359                                 // Must not use lyx::dispatch(), since tmpbuffer has no view.
360                                 DispatchResult dr;
361                                 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
362                         } else {
363                                 docstring text = bformat(
364                                         _("The pasted branch \"%1$s\" is undefined.\n"
365                                           "Do you want to add it to the document's branch list?"),
366                                         name);
367                                 if (frontend::Alert::prompt(_("Unknown branch"),
368                                           text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
369                                         break;
370                                 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
371                         }
372                         // We need to update the list of branches.
373                         need_update = true;
374                         break;
375                 }
376
377                 default:
378                         break; // nothing
379                 }
380         }
381         insertion.swap(in.paragraphs());
382
383         // Split the paragraph for inserting the buf if necessary.
384         if (!empty)
385                 breakParagraphConservative(buffer.params(), pars, pit, pos);
386
387         // Paste it!
388         if (empty) {
389                 pars.insert(boost::next(pars.begin(), pit),
390                             insertion.begin(),
391                             insertion.end());
392
393                 // merge the empty par with the last par of the insertion
394                 mergeParagraph(buffer.params(), pars,
395                                pit + insertion.size() - 1);
396         } else {
397                 pars.insert(boost::next(pars.begin(), pit + 1),
398                             insertion.begin(),
399                             insertion.end());
400
401                 // merge the first par of the insertion with the current par
402                 mergeParagraph(buffer.params(), pars, pit);
403         }
404
405         // Store the new cursor position.
406         pit_type last_paste = pit + insertion.size() - 1;
407         pit_type startpit = pit;
408         pit = last_paste;
409         pos = pars[last_paste].size();
410
411         // FIXME Should we do it here, or should we let updateBuffer() do it?
412         // Set paragraph buffers. It's important to do this right away
413         // before something calls Inset::buffer() and causes a crash.
414         for (pit_type p = startpit; p <= pit; ++p)
415                 pars[p].setBuffer(const_cast<Buffer &>(buffer));
416
417         // Join (conditionally) last pasted paragraph with next one, i.e.,
418         // the tail of the spliced document paragraph
419         if (!empty && last_paste + 1 != pit_type(pars.size())) {
420                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
421                         mergeParagraph(buffer.params(), pars, last_paste);
422                 } else if (pars[last_paste + 1].empty()) {
423                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
424                         mergeParagraph(buffer.params(), pars, last_paste);
425                 } else if (pars[last_paste].empty()) {
426                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
427                         mergeParagraph(buffer.params(), pars, last_paste);
428                 } else {
429                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
430                         ++last_paste;
431                 }
432         }
433
434         return PasteReturnValue(pit, pos, need_update);
435 }
436
437
438 PitPosPair eraseSelectionHelper(BufferParams const & params,
439         ParagraphList & pars,
440         pit_type startpit, pit_type endpit,
441         int startpos, int endpos)
442 {
443         // Start of selection is really invalid.
444         if (startpit == pit_type(pars.size()) ||
445             (startpos > pars[startpit].size()))
446                 return PitPosPair(endpit, endpos);
447
448         // Start and end is inside same paragraph
449         if (endpit == pit_type(pars.size()) || startpit == endpit) {
450                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
451                 return PitPosPair(endpit, endpos);
452         }
453
454         for (pit_type pit = startpit; pit != endpit + 1;) {
455                 pos_type const left  = (pit == startpit ? startpos : 0);
456                 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
457                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
458
459                 // Logically erase only, including the end-of-paragraph character
460                 pars[pit].eraseChars(left, right, params.track_changes);
461
462                 // Separate handling of paragraph break:
463                 if (merge && pit != endpit &&
464                     (pit + 1 != endpit 
465                      || pars[pit].hasSameLayout(pars[endpit])
466                      || pars[endpit].size() == endpos)) {
467                         if (pit + 1 == endpit)
468                                 endpos += pars[pit].size();
469                         mergeParagraph(params, pars, pit);
470                         --endpit;
471                 } else
472                         ++pit;
473         }
474
475         // Ensure legal cursor pos:
476         endpit = startpit;
477         endpos = startpos;
478         return PitPosPair(endpit, endpos);
479 }
480
481
482 void putClipboard(ParagraphList const & paragraphs, 
483         DocumentClassConstPtr docclass, docstring const & plaintext)
484 {
485         // This used to need to be static to avoid a memory leak. It no longer needs
486         // to be so, but the alternative is to construct a new one of these (with a
487         // new temporary directory, etc) every time, and then to destroy it. So maybe
488         // it's worth just keeping this one around.
489         // FIXME THREAD
490         static TempFile tempfile("clipboard.internal");
491         tempfile.setAutoRemove(false);
492         static Buffer * staticbuffer = theBufferList().newInternalBuffer(
493                         tempfile.name().absFileName());
494
495         // These two things only really need doing the first time.
496         staticbuffer->setUnnamed(true);
497         staticbuffer->inset().setBuffer(*staticbuffer);
498
499         // Use a clone for the complicated stuff so that we do not need to clean
500         // up in order to avoid a crash.
501         Buffer * buffer = staticbuffer->cloneBufferOnly();
502         LASSERT(buffer, return);
503
504         // This needs doing every time.
505         buffer->params().setDocumentClass(docclass);
506
507         // we will use pasteSelectionHelper to copy the paragraphs into the
508         // temporary Buffer, since it does a lot of things to fix them up.
509         DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
510         ErrorList el;
511         pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
512
513         // We don't want to produce images that are not used. Therefore,
514         // output formulas as MathML. Even if this is not understood by all
515         // applications, the number that can parse it should go up in the future.
516         buffer->params().html_math_output = BufferParams::MathML;
517
518         // Make sure MarkAsExporting is deleted before buffer is
519         {
520                 // The Buffer is being used to export. This is necessary so that the
521                 // updateMacros call will record the needed information.
522                 MarkAsExporting mex(buffer);
523
524                 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
525                 buffer->updateMacros();
526                 buffer->updateMacroInstances(OutputUpdate);
527
528                 // LyX's own format
529                 string lyx;
530                 ostringstream oslyx;
531                 if (buffer->write(oslyx))
532                         lyx = oslyx.str();
533
534                 // XHTML format
535                 odocstringstream oshtml;
536                 OutputParams runparams(encodings.fromLyXName("utf8"));
537                 // We do not need to produce images, etc.
538                 runparams.dryrun = true;
539                 // We are not interested in errors (bug 8866)
540                 runparams.silent = true;
541                 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
542
543                 theClipboard().put(lyx, oshtml.str(), plaintext);
544         }
545
546         // Save that memory
547         delete buffer;
548 }
549
550
551 /// return true if the whole ParagraphList is deleted
552 static bool isFullyDeleted(ParagraphList const & pars)
553 {
554         pit_type const pars_size = static_cast<pit_type>(pars.size());
555
556         // check all paragraphs
557         for (pit_type pit = 0; pit < pars_size; ++pit) {
558                 if (!pars[pit].empty())   // prevent assertion failure
559                         if (!pars[pit].isDeleted(0, pars[pit].size()))
560                                 return false;
561         }
562         return true;
563 }
564
565
566 void copySelectionHelper(Buffer const & buf, Text const & text,
567         pit_type startpit, pit_type endpit,
568         int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
569 {
570         ParagraphList const & pars = text.paragraphs();
571
572         // In most of these cases, we can try to recover.
573         LASSERT(0 <= start, start = 0);
574         LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
575         LASSERT(0 <= end, end = 0);
576         LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
577         LASSERT(startpit != endpit || start <= end, return);
578
579         // Clone the paragraphs within the selection.
580         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
581                                 boost::next(pars.begin(), endpit + 1));
582
583         // Remove the end of the last paragraph; afterwards, remove the
584         // beginning of the first paragraph. Keep this order - there may only
585         // be one paragraph!  Do not track deletions here; this is an internal
586         // action not visible to the user
587
588         Paragraph & back = copy_pars.back();
589         back.eraseChars(end, back.size(), false);
590         Paragraph & front = copy_pars.front();
591         front.eraseChars(0, start, false);
592
593         ParagraphList::iterator it = copy_pars.begin();
594         ParagraphList::iterator it_end = copy_pars.end();
595
596         for (; it != it_end; ++it) {
597                 // Since we have a copy of the paragraphs, the insets
598                 // do not have a proper buffer reference. It makes
599                 // sense to add them temporarily, because the
600                 // operations below depend on that (acceptChanges included).
601                 it->setBuffer(const_cast<Buffer &>(buf));
602                 // PassThru paragraphs have the Language
603                 // latex_language. This is invalid for others, so we
604                 // need to change it to the buffer language.
605                 if (it->isPassThru())
606                         it->changeLanguage(buf.params(), 
607                                            latex_language, buf.language());
608         }
609
610         // do not copy text (also nested in insets) which is marked as
611         // deleted, unless the whole selection was deleted
612         if (!isFullyDeleted(copy_pars))
613                 acceptChanges(copy_pars, buf.params());
614         else
615                 rejectChanges(copy_pars, buf.params());
616
617
618         // do some final cleanup now, to make sure that the paragraphs
619         // are not linked to something else.
620         it = copy_pars.begin();
621         for (; it != it_end; ++it) {
622                 it->setBuffer(*static_cast<Buffer *>(0));
623                 it->setInsetOwner(0);
624         }
625
626         cutstack.push(make_pair(copy_pars, dc));
627 }
628
629 } // namespace anon
630
631
632
633
634 namespace cap {
635
636 void region(CursorSlice const & i1, CursorSlice const & i2,
637             Inset::row_type & r1, Inset::row_type & r2,
638             Inset::col_type & c1, Inset::col_type & c2)
639 {
640         Inset & p = i1.inset();
641         c1 = p.col(i1.idx());
642         c2 = p.col(i2.idx());
643         if (c1 > c2)
644                 swap(c1, c2);
645         r1 = p.row(i1.idx());
646         r2 = p.row(i2.idx());
647         if (r1 > r2)
648                 swap(r1, r2);
649 }
650
651
652 docstring grabAndEraseSelection(Cursor & cur)
653 {
654         if (!cur.selection())
655                 return docstring();
656         docstring res = grabSelection(cur);
657         eraseSelection(cur);
658         return res;
659 }
660
661
662 bool reduceSelectionToOneCell(Cursor & cur)
663 {
664         if (!cur.selection() || !cur.inMathed())
665                 return false;
666
667         CursorSlice i1 = cur.selBegin();
668         CursorSlice i2 = cur.selEnd();
669         if (!i1.inset().asInsetMath())
670                 return false;
671
672         // the easy case: do nothing if only one cell is selected
673         if (i1.idx() == i2.idx())
674                 return true;
675         
676         cur.top().pos() = 0;
677         cur.resetAnchor();
678         cur.top().pos() = cur.top().lastpos();
679         
680         return true;
681 }
682
683
684 bool multipleCellsSelected(Cursor const & cur)
685 {
686         if (!cur.selection() || !cur.inMathed())
687                 return false;
688         
689         CursorSlice i1 = cur.selBegin();
690         CursorSlice i2 = cur.selEnd();
691         if (!i1.inset().asInsetMath())
692                 return false;
693         
694         if (i1.idx() == i2.idx())
695                 return false;
696         
697         return true;
698 }
699
700
701 void switchBetweenClasses(DocumentClassConstPtr oldone,
702                 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
703 {
704         errorlist.clear();
705
706         LBUFERR(!in.paragraphs().empty());
707         if (oldone == newone)
708                 return;
709         
710         DocumentClass const & oldtc = *oldone;
711         DocumentClass const & newtc = *newone;
712
713         // layouts
714         ParIterator it = par_iterator_begin(in);
715         ParIterator end = par_iterator_end(in);
716         // for remembering which layouts we've had to add
717         set<docstring> newlayouts;
718         for (; it != end; ++it) {
719                 docstring const name = it->layout().name();
720
721                 // the pasted text will keep their own layout name. If this layout does
722                 // not exist in the new document, it will behave like a standard layout.
723                 bool const added_one = newtc.addLayoutIfNeeded(name);
724                 if (added_one)
725                         newlayouts.insert(name);
726
727                 if (added_one || newlayouts.find(name) != newlayouts.end()) {
728                         // Warn the user.
729                         docstring const s = bformat(_("Layout `%1$s' was not found."), name);
730                         errorlist.push_back(
731                                 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
732                 }
733
734                 if (in.usePlainLayout())
735                         it->setLayout(newtc.plainLayout());
736                 else
737                         it->setLayout(newtc[name]);
738         }
739
740         // character styles and hidden table cells
741         InsetIterator const i_end = inset_iterator_end(in);
742         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
743                 InsetCode const code = it->lyxCode();
744                 if (code == FLEX_CODE) {
745                         // FIXME: Should we verify all InsetCollapsable?
746                         docstring const layoutName = it->layoutName();
747                         docstring const & n = newone->insetLayout(layoutName).name();
748                         bool const is_undefined = n.empty() ||
749                                 n == DocumentClass::plainInsetLayout().name();
750                         if (!is_undefined)
751                                 continue;
752         
753                         // The flex inset is undefined in newtc
754                         docstring const oldname = from_utf8(oldtc.name());
755                         docstring const newname = from_utf8(newtc.name());
756                         docstring s;
757                         if (oldname == newname)
758                                 s = bformat(_("Flex inset %1$s is undefined after "
759                                         "reloading `%2$s' layout."), layoutName, oldname);
760                         else
761                                 s = bformat(_("Flex inset %1$s is undefined because of "
762                                         "conversion from `%2$s' layout to `%3$s'."),
763                                         layoutName, oldname, newname);
764                         // To warn the user that something had to be done.
765                         errorlist.push_back(ErrorItem(
766                                         _("Undefined flex inset"),
767                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
768                 } else if (code == TABULAR_CODE) {
769                         // The recursion above does not catch paragraphs in "hidden" cells,
770                         // i.e., ones that are part of a multirow or multicolum. So we need
771                         // to handle those separately.
772                         // This is the cause of bug #9049.
773                         InsetTabular * table = it->asInsetTabular();
774                         table->setLayoutForHiddenCells(newtc);
775                 }
776         }
777 }
778
779
780 vector<docstring> availableSelections(Buffer const * buf)
781 {
782         vector<docstring> selList;
783         if (!buf)
784                 return selList;
785
786         CutStack::const_iterator cit = theCuts.begin();
787         CutStack::const_iterator end = theCuts.end();
788         for (; cit != end; ++cit) {
789                 // we do not use cit-> here because gcc 2.9x does not
790                 // like it (JMarc)
791                 ParagraphList const & pars = (*cit).first;
792                 docstring asciiSel;
793                 ParagraphList::const_iterator pit = pars.begin();
794                 ParagraphList::const_iterator pend = pars.end();
795                 for (; pit != pend; ++pit) {
796                         Paragraph par(*pit, 0, 26);
797                         // adapt paragraph to current buffer.
798                         par.setBuffer(const_cast<Buffer &>(*buf));
799                         asciiSel += par.asString(AS_STR_INSETS);
800                         if (asciiSel.size() > 25) {
801                                 asciiSel.replace(22, docstring::npos,
802                                                  from_ascii("..."));
803                                 break;
804                         }
805                 }
806
807                 selList.push_back(asciiSel);
808         }
809
810         return selList;
811 }
812
813
814 size_type numberOfSelections()
815 {
816         return theCuts.size();
817 }
818
819
820 void cutSelection(Cursor & cur, bool doclear, bool realcut)
821 {
822         // This doesn't make sense, if there is no selection
823         if (!cur.selection())
824                 return;
825
826         // OK, we have a selection. This is always between cur.selBegin()
827         // and cur.selEnd()
828
829         if (cur.inTexted()) {
830                 Text * text = cur.text();
831                 LBUFERR(text);
832
833                 saveSelection(cur);
834
835                 // make sure that the depth behind the selection are restored, too
836                 cur.recordUndoSelection();
837                 pit_type begpit = cur.selBegin().pit();
838                 pit_type endpit = cur.selEnd().pit();
839
840                 int endpos = cur.selEnd().pos();
841
842                 BufferParams const & bp = cur.buffer()->params();
843                 if (realcut) {
844                         copySelectionHelper(*cur.buffer(),
845                                 *text,
846                                 begpit, endpit,
847                                 cur.selBegin().pos(), endpos,
848                                 bp.documentClassPtr(), theCuts);
849                         // Stuff what we got on the clipboard.
850                         // Even if there is no selection.
851                         putClipboard(theCuts[0].first, theCuts[0].second,
852                                 cur.selectionAsString(true));
853                 }
854
855                 if (begpit != endpit)
856                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
857
858                 boost::tie(endpit, endpos) =
859                         eraseSelectionHelper(bp,
860                                 text->paragraphs(),
861                                 begpit, endpit,
862                                 cur.selBegin().pos(), endpos);
863
864                 // cutSelection can invalidate the cursor so we need to set
865                 // it anew. (Lgb)
866                 // we prefer the end for when tracking changes
867                 cur.pos() = endpos;
868                 cur.pit() = endpit;
869
870                 // sometimes necessary
871                 if (doclear
872                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
873                         cur.fixIfBroken();
874
875                 // need a valid cursor. (Lgb)
876                 cur.clearSelection();
877
878                 // After a cut operation, we must make sure that the Buffer is updated
879                 // because some further operation might need updated label information for
880                 // example. So we cannot just use "cur.forceBufferUpdate()" here.
881                 // This fixes #7071.
882                 cur.buffer()->updateBuffer();
883
884                 // tell tabular that a recent copy happened
885                 dirtyTabularStack(false);
886         }
887
888         if (cur.inMathed()) {
889                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
890                         // The current selection spans more than one cell.
891                         // Record all cells
892                         cur.recordUndoInset();
893                 } else {
894                         // Record only the current cell to avoid a jumping
895                         // cursor after undo
896                         cur.recordUndo();
897                 }
898                 if (realcut)
899                         copySelection(cur);
900                 eraseSelection(cur);
901         }
902 }
903
904
905 void copySelection(Cursor const & cur)
906 {
907         copySelection(cur, cur.selectionAsString(true));
908 }
909
910
911 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
912 {
913         ParagraphList pars;
914         Paragraph par;
915         BufferParams const & bp = cur.buffer()->params();
916         par.setLayout(bp.documentClass().plainLayout());
917         Font font(inherit_font, bp.language);
918         par.insertInset(0, inset, font, Change(Change::UNCHANGED));
919         pars.push_back(par);
920         theCuts.push(make_pair(pars, bp.documentClassPtr()));
921
922         // stuff the selection onto the X clipboard, from an explicit copy request
923         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
924 }
925
926
927 namespace {
928
929 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
930 {
931         // this doesn't make sense, if there is no selection
932         if (!cur.selection())
933                 return;
934
935         // copySelection can not yet handle the case of cross idx selection
936         if (cur.selBegin().idx() != cur.selEnd().idx())
937                 return;
938
939         if (cur.inTexted()) {
940                 Text * text = cur.text();
941                 LBUFERR(text);
942                 // ok we have a selection. This is always between cur.selBegin()
943                 // and sel_end cursor
944
945                 // copy behind a space if there is one
946                 ParagraphList & pars = text->paragraphs();
947                 pos_type pos = cur.selBegin().pos();
948                 pit_type par = cur.selBegin().pit();
949                 while (pos < pars[par].size() &&
950                        pars[par].isLineSeparator(pos) &&
951                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
952                         ++pos;
953
954                 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
955                         pos, cur.selEnd().pos(), 
956                         cur.buffer()->params().documentClassPtr(), cutstack);
957
958                 // Reset the dirty_tabular_stack_ flag only when something
959                 // is copied to the clipboard (not to the selectionBuffer).
960                 if (&cutstack == &theCuts)
961                         dirtyTabularStack(false);
962         }
963
964         if (cur.inMathed()) {
965                 //lyxerr << "copySelection in mathed" << endl;
966                 ParagraphList pars;
967                 Paragraph par;
968                 BufferParams const & bp = cur.buffer()->params();
969                 // FIXME This should be the plain layout...right?
970                 par.setLayout(bp.documentClass().plainLayout());
971                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
972                 pars.push_back(par);
973                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
974         }
975 }
976
977 }
978
979
980 void copySelectionToStack()
981 {
982         if (!selectionBuffer.empty())
983                 theCuts.push(selectionBuffer[0]);
984 }
985
986
987 void copySelection(Cursor const & cur, docstring const & plaintext)
988 {
989         // In tablemode, because copy and paste actually use special table stack
990         // we do not attempt to get selected paragraphs under cursor. Instead, a
991         // paragraph with the plain text version is generated so that table cells
992         // can be pasted as pure text somewhere else.
993         if (cur.selBegin().idx() != cur.selEnd().idx()) {
994                 ParagraphList pars;
995                 Paragraph par;
996                 BufferParams const & bp = cur.buffer()->params();
997                 par.setLayout(bp.documentClass().plainLayout());
998                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
999                 pars.push_back(par);
1000                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1001         } else {
1002                 copySelectionToStack(cur, theCuts);
1003         }
1004
1005         // stuff the selection onto the X clipboard, from an explicit copy request
1006         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1007 }
1008
1009
1010 void saveSelection(Cursor const & cur)
1011 {
1012         // This function is called, not when a selection is formed, but when
1013         // a selection is cleared. Therefore, multiple keyboard selection
1014         // will not repeatively trigger this function (bug 3877).
1015         if (cur.selection() 
1016             && cur.selBegin() == cur.bv().cursor().selBegin()
1017             && cur.selEnd() == cur.bv().cursor().selEnd()) {
1018                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1019                 copySelectionToStack(cur, selectionBuffer);
1020         }
1021 }
1022
1023
1024 bool selection()
1025 {
1026         return !selectionBuffer.empty();
1027 }
1028
1029
1030 void clearSelection()
1031 {
1032         selectionBuffer.clear();
1033 }
1034
1035
1036 void clearCutStack()
1037 {
1038         theCuts.clear();
1039 }
1040
1041
1042 docstring selection(size_t sel_index)
1043 {
1044         return sel_index < theCuts.size()
1045                 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1046                 : docstring();
1047 }
1048
1049
1050 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1051                         DocumentClassConstPtr docclass, ErrorList & errorList)
1052 {
1053         if (cur.inTexted()) {
1054                 Text * text = cur.text();
1055                 LBUFERR(text);
1056
1057                 PasteReturnValue prv =
1058                         pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1059                 cur.forceBufferUpdate();
1060                 cur.clearSelection();
1061                 text->setCursor(cur, prv.par, prv.pos);
1062         }
1063
1064         // mathed is handled in InsetMathNest/InsetMathGrid
1065         LATTEST(!cur.inMathed());
1066 }
1067
1068
1069 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1070 {
1071         // this does not make sense, if there is nothing to paste
1072         if (!checkPastePossible(sel_index))
1073                 return false;
1074
1075         cur.recordUndo();
1076         pasteParagraphList(cur, theCuts[sel_index].first,
1077                            theCuts[sel_index].second, errorList);
1078         return true;
1079 }
1080
1081
1082 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1083                         Clipboard::TextType type)
1084 {
1085         // Use internal clipboard if it is the most recent one
1086         // This overrides asParagraphs and type on purpose!
1087         if (theClipboard().isInternal())
1088                 return pasteFromStack(cur, errorList, 0);
1089
1090         // First try LyX format
1091         if ((type == Clipboard::LyXTextType ||
1092              type == Clipboard::LyXOrPlainTextType ||
1093              type == Clipboard::AnyTextType) &&
1094             theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1095                 string lyx = theClipboard().getAsLyX();
1096                 if (!lyx.empty()) {
1097                         // For some strange reason gcc 3.2 and 3.3 do not accept
1098                         // Buffer buffer(string(), false);
1099                         Buffer buffer("", false);
1100                         buffer.setUnnamed(true);
1101                         if (buffer.readString(lyx)) {
1102                                 cur.recordUndo();
1103                                 pasteParagraphList(cur, buffer.paragraphs(),
1104                                         buffer.params().documentClassPtr(), errorList);
1105                                 return true;
1106                         }
1107                 }
1108         }
1109
1110         // Then try TeX and HTML
1111         Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1112         string names[2] = {"html", "latexclipboard"};
1113         for (int i = 0; i < 2; ++i) {
1114                 if (type != types[i] && type != Clipboard::AnyTextType)
1115                         continue;
1116                 bool available = theClipboard().hasTextContents(types[i]);
1117
1118                 // If a specific type was explicitly requested, try to
1119                 // interpret plain text: The user told us that the clipboard
1120                 // contents is in the desired format
1121                 if (!available && type == types[i]) {
1122                         types[i] = Clipboard::PlainTextType;
1123                         available = theClipboard().hasTextContents(types[i]);
1124                 }
1125
1126                 if (available) {
1127                         docstring text = theClipboard().getAsText(types[i]);
1128                         available = !text.empty();
1129                         if (available) {
1130                                 // For some strange reason gcc 3.2 and 3.3 do not accept
1131                                 // Buffer buffer(string(), false);
1132                                 Buffer buffer("", false);
1133                                 buffer.setUnnamed(true);
1134                                 available = buffer.importString(names[i], text, errorList);
1135                                 if (available)
1136                                         available = !buffer.paragraphs().empty();
1137                                 if (available && !buffer.paragraphs()[0].empty()) {
1138                                         cur.recordUndo();
1139                                         pasteParagraphList(cur, buffer.paragraphs(),
1140                                                 buffer.params().documentClassPtr(), errorList);
1141                                         return true;
1142                                 }
1143                         }
1144                 }
1145         }
1146
1147         // Then try plain text
1148         docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1149         if (text.empty())
1150                 return false;
1151         cur.recordUndo();
1152         if (asParagraphs)
1153                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1154         else
1155                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1156         return true;
1157 }
1158
1159
1160 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1161 {
1162         docstring text;
1163         // Use internal clipboard if it is the most recent one
1164         if (theClipboard().isInternal()) {
1165                 if (!checkPastePossible(0))
1166                         return;
1167
1168                 ParagraphList const & pars = theCuts[0].first;
1169                 ParagraphList::const_iterator it = pars.begin();
1170                 for (; it != pars.end(); ++it) {
1171                         if (it != pars.begin())
1172                                 text += "\n";
1173                         text += (*it).asString();
1174                 }
1175                 asParagraphs = false;
1176         } else {
1177                 // Then try plain text
1178                 text = theClipboard().getAsText(Clipboard::PlainTextType);
1179         }
1180
1181         if (text.empty())
1182                 return;
1183
1184         cur.recordUndo();
1185         cutSelection(cur, true, false);
1186         if (asParagraphs)
1187                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1188         else
1189                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1190 }
1191
1192
1193 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1194                             Clipboard::GraphicsType preferedType)
1195 {
1196         LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1197
1198         // get picture from clipboard
1199         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1200         if (filename.empty())
1201                 return;
1202
1203         // create inset for graphic
1204         InsetGraphics * inset = new InsetGraphics(cur.buffer());
1205         InsetGraphicsParams params;
1206         params.filename = support::DocFileName(filename.absFileName(), false);
1207         inset->setParams(params);
1208         cur.recordUndo();
1209         cur.insert(inset);
1210 }
1211
1212
1213 void pasteSelection(Cursor & cur, ErrorList & errorList)
1214 {
1215         if (selectionBuffer.empty())
1216                 return;
1217         cur.recordUndo();
1218         pasteParagraphList(cur, selectionBuffer[0].first,
1219                            selectionBuffer[0].second, errorList);
1220 }
1221
1222
1223 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1224 {
1225         cur.recordUndo();
1226         DocIterator selbeg = cur.selectionBegin();
1227
1228         // Get font setting before we cut, we need a copy here, not a bare reference.
1229         Font const font =
1230                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1231
1232         // Insert the new string
1233         pos_type pos = cur.selEnd().pos();
1234         Paragraph & par = cur.selEnd().paragraph();
1235         docstring::const_iterator cit = str.begin();
1236         docstring::const_iterator end = str.end();
1237         for (; cit != end; ++cit, ++pos)
1238                 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1239
1240         // Cut the selection
1241         cutSelection(cur, true, false);
1242 }
1243
1244
1245 void replaceSelection(Cursor & cur)
1246 {
1247         if (cur.selection())
1248                 cutSelection(cur, true, false);
1249 }
1250
1251
1252 void eraseSelection(Cursor & cur)
1253 {
1254         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1255         CursorSlice const & i1 = cur.selBegin();
1256         CursorSlice const & i2 = cur.selEnd();
1257         if (!i1.asInsetMath()) {
1258                 LYXERR0("Can't erase this selection");
1259                 return;
1260         }
1261
1262         saveSelection(cur);
1263         cur.top() = i1;
1264         InsetMath * p = i1.asInsetMath();
1265         if (i1.idx() == i2.idx()) {
1266                 i1.cell().erase(i1.pos(), i2.pos());
1267                 // We may have deleted i1.cell(cur.pos()).
1268                 // Make sure that pos is valid.
1269                 if (cur.pos() > cur.lastpos())
1270                         cur.pos() = cur.lastpos();
1271         } else if (p->nrows() > 0 && p->ncols() > 0) {
1272                 // This is a grid, delete a nice square region
1273                 Inset::row_type r1, r2;
1274                 Inset::col_type c1, c2;
1275                 region(i1, i2, r1, r2, c1, c2);
1276                 for (Inset::row_type row = r1; row <= r2; ++row)
1277                         for (Inset::col_type col = c1; col <= c2; ++col)
1278                                 p->cell(p->index(row, col)).clear();
1279                 // We've deleted the whole cell. Only pos 0 is valid.
1280                 cur.pos() = 0;
1281         } else {
1282                 Inset::idx_type idx1 = i1.idx();
1283                 Inset::idx_type idx2 = i2.idx();
1284                 if (idx1 > idx2)
1285                         swap(idx1, idx2);
1286                 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1287                         p->cell(idx).clear();
1288                 // We've deleted the whole cell. Only pos 0 is valid.
1289                 cur.pos() = 0;
1290         }
1291
1292         // need a valid cursor. (Lgb)
1293         cur.clearSelection();
1294         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1295 }
1296
1297
1298 void selDel(Cursor & cur)
1299 {
1300         //lyxerr << "cap::selDel" << endl;
1301         if (cur.selection())
1302                 eraseSelection(cur);
1303 }
1304
1305
1306 void selClearOrDel(Cursor & cur)
1307 {
1308         //lyxerr << "cap::selClearOrDel" << endl;
1309         if (lyxrc.auto_region_delete)
1310                 selDel(cur);
1311         else
1312                 cur.setSelection(false);
1313 }
1314
1315
1316 docstring grabSelection(Cursor const & cur)
1317 {
1318         if (!cur.selection())
1319                 return docstring();
1320
1321 #if 0
1322         // grab selection by glueing multiple cells together. This is not what
1323         // we want because selections spanning multiple cells will get "&" and "\\"
1324         // seperators.
1325         ostringstream os;
1326         for (DocIterator dit = cur.selectionBegin();
1327              dit != cur.selectionEnd(); dit.forwardPos())
1328                 os << asString(dit.cell());
1329         return os.str();
1330 #endif
1331
1332         CursorSlice i1 = cur.selBegin();
1333         CursorSlice i2 = cur.selEnd();
1334
1335         if (i1.idx() == i2.idx()) {
1336                 if (i1.inset().asInsetMath()) {
1337                         MathData::const_iterator it = i1.cell().begin();
1338                         Buffer * buf = cur.buffer();
1339                         return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1340                 } else {
1341                         return from_ascii("unknown selection 1");
1342                 }
1343         }
1344
1345         Inset::row_type r1, r2;
1346         Inset::col_type c1, c2;
1347         region(i1, i2, r1, r2, c1, c2);
1348
1349         docstring data;
1350         if (i1.inset().asInsetMath()) {
1351                 for (Inset::row_type row = r1; row <= r2; ++row) {
1352                         if (row > r1)
1353                                 data += "\\\\";
1354                         for (Inset::col_type col = c1; col <= c2; ++col) {
1355                                 if (col > c1)
1356                                         data += '&';
1357                                 data += asString(i1.asInsetMath()->
1358                                         cell(i1.asInsetMath()->index(row, col)));
1359                         }
1360                 }
1361         } else {
1362                 data = from_ascii("unknown selection 2");
1363         }
1364         return data;
1365 }
1366
1367
1368 void dirtyTabularStack(bool b)
1369 {
1370         dirty_tabular_stack_ = b;
1371 }
1372
1373
1374 bool tabularStackDirty()
1375 {
1376         return dirty_tabular_stack_;
1377 }
1378
1379
1380 } // namespace cap
1381 } // namespace lyx