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