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