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