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