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