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