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