]> git.lyx.org Git - features.git/blob - src/CutAndPaste.cpp
InsetIndex: hide printTree behind a LYX_INSET_INDEX_DEBUG flag
[features.git] / src / CutAndPaste.cpp
1 /**
2  * \file CutAndPaste.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "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 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1041 {
1042         ParagraphList pars;
1043         Paragraph par;
1044         BufferParams const & bp = cur.buffer()->params();
1045         par.setLayout(bp.documentClass().plainLayout());
1046         Font font(inherit_font, bp.language);
1047         par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1048         pars.push_back(par);
1049         theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1050
1051         // stuff the selection onto the X clipboard, from an explicit copy request
1052         putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1053 }
1054
1055
1056 namespace {
1057
1058 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1059 {
1060         // this doesn't make sense, if there is no selection
1061         if (!cur.selection())
1062                 return;
1063
1064         // copySelection can not yet handle the case of cross idx selection
1065         if (cur.selBegin().idx() != cur.selEnd().idx())
1066                 return;
1067
1068         if (cur.inTexted()) {
1069                 Text * text = cur.text();
1070                 LBUFERR(text);
1071                 // ok we have a selection. This is always between cur.selBegin()
1072                 // and sel_end cursor
1073                 copySelectionHelper(*cur.buffer(), *text,
1074                                     cur.selBegin().pit(), cur.selEnd().pit(),
1075                                     cur.selBegin().pos(), cur.selEnd().pos(),
1076                                     cur.buffer()->params().documentClassPtr(),
1077                                     cutstack);
1078                 // Reset the dirty_tabular_stack_ flag only when something
1079                 // is copied to the clipboard (not to the selectionBuffer).
1080                 if (&cutstack == &theCuts)
1081                         dirtyTabularStack(false);
1082         }
1083
1084         if (cur.inMathed()) {
1085                 //lyxerr << "copySelection in mathed" << endl;
1086                 ParagraphList pars;
1087                 Paragraph par;
1088                 BufferParams const & bp = cur.buffer()->params();
1089                 // FIXME This should be the plain layout...right?
1090                 par.setLayout(bp.documentClass().plainLayout());
1091                 // For pasting into text, we set the language to the paragraph language
1092                 // (rather than the default_language which is always English; see #2596)
1093                 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1094                            Change(Change::UNCHANGED));
1095                 pars.push_back(par);
1096                 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1097         }
1098 }
1099
1100 } // namespace
1101
1102
1103 void copySelectionToStack()
1104 {
1105         if (!selectionBuffer.empty())
1106                 theCuts.push(selectionBuffer[0]);
1107 }
1108
1109
1110 void copySelectionToTemp(Cursor const & cur)
1111 {
1112         copySelectionToStack(cur, tempCut);
1113 }
1114
1115
1116 void copySelection(Cursor const & cur, docstring const & plaintext)
1117 {
1118         // In tablemode, because copy and paste actually use a special table stack,
1119         // we need to go through the cells and collect the paragraphs.
1120         // In math matrices, we generate a plain text version.
1121         if (cur.selBegin().idx() != cur.selEnd().idx()) {
1122                 ParagraphList pars;
1123                 BufferParams const & bp = cur.buffer()->params();
1124                 if (cur.inMathed()) {
1125                         Paragraph par;
1126                         par.setLayout(bp.documentClass().plainLayout());
1127                         // Replace (column-separating) tabs by space (#4449)
1128                         docstring const clean_text = subst(plaintext, '\t', ' ');
1129                         // For pasting into text, we set the language to the paragraph language
1130                         // (rather than the default_language which is always English; see #11898)
1131                         par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1132                                    Change(Change::UNCHANGED));
1133                         pars.push_back(par);
1134                 } else {
1135                         // Get paragraphs from all cells
1136                         InsetTabular * table = cur.inset().asInsetTabular();
1137                         LASSERT(table, return);
1138                         ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1139                         for (auto & cpar : tplist) {
1140                                 cpar.setLayout(bp.documentClass().plainLayout());
1141                                 pars.push_back(cpar);
1142                                 // since the pars are merged later, we separate them by blank
1143                                 Paragraph epar;
1144                                 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1145                                             Change(Change::UNCHANGED));
1146                                 pars.push_back(epar);
1147                         }
1148                         // remove last empty par
1149                         pars.pop_back();
1150                         // merge all paragraphs to one
1151                         while (pars.size() > 1)
1152                                 mergeParagraph(bp, pars, 0);
1153                 }
1154                 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1155         } else {
1156                 copySelectionToStack(cur, theCuts);
1157         }
1158
1159         // stuff the selection onto the X clipboard, from an explicit copy request
1160         putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1161                         cur.buffer()->params());
1162 }
1163
1164
1165 void saveSelection(Cursor const & cur)
1166 {
1167         // This function is called, not when a selection is formed, but when
1168         // a selection is cleared. Therefore, multiple keyboard selection
1169         // will not repeatively trigger this function (bug 3877).
1170         if (cur.selection()
1171             && cur.selBegin() == cur.bv().cursor().selBegin()
1172             && cur.selEnd() == cur.bv().cursor().selEnd()) {
1173                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1174                 copySelectionToStack(cur, selectionBuffer);
1175         }
1176 }
1177
1178
1179 bool selection()
1180 {
1181         return !selectionBuffer.empty();
1182 }
1183
1184
1185 void clearSelection()
1186 {
1187         selectionBuffer.clear();
1188 }
1189
1190
1191 void clearCutStack()
1192 {
1193         theCuts.clear();
1194         tempCut.clear();
1195 }
1196
1197
1198 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1199 {
1200         if (sel_index >= theCuts.size())
1201                 return docstring();
1202
1203         unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1204                                                    docinfo.first));
1205         if (!buffer)
1206                 return docstring();
1207
1208         int options = AS_STR_INSETS | AS_STR_NEWLINES;
1209         if (for_math)
1210                 options |= AS_STR_MATHED;
1211
1212         return buffer->paragraphs().back().asString(options);
1213 }
1214
1215
1216 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1217                         DocumentClassConstPtr docclass, AuthorList const & authors,
1218                         ErrorList & errorList,
1219                         cap::BranchAction branchAction)
1220 {
1221         // Copy authors to the params. We need those pointers.
1222         for (Author const & a : authors)
1223                 cur.buffer()->params().authors().record(a);
1224         
1225         if (cur.inTexted()) {
1226                 Text * text = cur.text();
1227                 LBUFERR(text);
1228
1229                 PasteReturnValue prv =
1230                         pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1231                 cur.forceBufferUpdate();
1232                 cur.clearSelection();
1233                 text->setCursor(cur, prv.pit, prv.pos);
1234         }
1235
1236         // mathed is handled in InsetMathNest/InsetMathGrid
1237         LATTEST(!cur.inMathed());
1238 }
1239
1240
1241 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1242 {
1243         // this does not make sense, if there is nothing to paste
1244         if (!checkPastePossible(sel_index))
1245                 return false;
1246
1247         cur.recordUndo();
1248         pasteParagraphList(cur, theCuts[sel_index].first,
1249                            theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1250                            errorList, BRANCH_ASK);
1251         return true;
1252 }
1253
1254
1255 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1256 {
1257         // this does not make sense, if there is nothing to paste
1258         if (tempCut.empty() || tempCut[0].first.empty())
1259                 return false;
1260
1261         cur.recordUndo();
1262         pasteParagraphList(cur, tempCut[0].first,
1263                         tempCut[0].second.first, tempCut[0].second.second,
1264                         errorList, BRANCH_IGNORE);
1265         return true;
1266 }
1267
1268
1269 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1270                         Clipboard::TextType type)
1271 {
1272         // Use internal clipboard if it is the most recent one
1273         // This overrides asParagraphs and type on purpose!
1274         if (theClipboard().isInternal())
1275                 return pasteFromStack(cur, errorList, 0);
1276
1277         // First try LyX format
1278         if ((type == Clipboard::LyXTextType ||
1279              type == Clipboard::LyXOrPlainTextType ||
1280              type == Clipboard::AnyTextType) &&
1281             theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1282                 string lyx = theClipboard().getAsLyX();
1283                 if (!lyx.empty()) {
1284                         Buffer buffer(string(), false);
1285                         buffer.setInternal(true);
1286                         buffer.setUnnamed(true);
1287                         if (buffer.readString(lyx)) {
1288                                 cur.recordUndo();
1289                                 pasteParagraphList(cur, buffer.paragraphs(),
1290                                                    buffer.params().documentClassPtr(),
1291                                                    buffer.params().authors(),
1292                                                    errorList);
1293                                 return true;
1294                         }
1295                 }
1296         }
1297
1298         // Then try TeX and HTML
1299         Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1300         string names[2] = {"html", "latexclipboard"};
1301         for (int i = 0; i < 2; ++i) {
1302                 if (type != types[i] && type != Clipboard::AnyTextType)
1303                         continue;
1304                 bool available = theClipboard().hasTextContents(types[i]);
1305
1306                 // If a specific type was explicitly requested, try to
1307                 // interpret plain text: The user told us that the clipboard
1308                 // contents is in the desired format
1309                 if (!available && type == types[i]) {
1310                         types[i] = Clipboard::PlainTextType;
1311                         available = theClipboard().hasTextContents(types[i]);
1312                 }
1313
1314                 if (available) {
1315                         docstring text = theClipboard().getAsText(types[i]);
1316                         available = !text.empty();
1317                         if (available) {
1318                                 Buffer buffer(string(), false);
1319                                 buffer.setInternal(true);
1320                                 buffer.setUnnamed(true);
1321                                 buffer.params() = cur.buffer()->params();
1322                                 available = buffer.importString(names[i], text, errorList);
1323                                 if (available)
1324                                         available = !buffer.paragraphs().empty();
1325                                 if (available && !buffer.paragraphs()[0].empty()) {
1326                                         // TeX2lyx (also used in the HTML chain) assumes English as document language
1327                                         // if no language is explicitly set (as is the case here).
1328                                         // We thus reset the temp buffer's language to the context language
1329                                         buffer.changeLanguage(buffer.language(), cur.getFont().language());
1330                                         cur.recordUndo();
1331                                         pasteParagraphList(cur, buffer.paragraphs(),
1332                                                            buffer.params().documentClassPtr(),
1333                                                            buffer.params().authors(),
1334                                                            errorList);
1335                                         return true;
1336                                 }
1337                         }
1338                 }
1339         }
1340
1341         // Then try plain text
1342         docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1343         if (text.empty())
1344                 return false;
1345         cur.recordUndo();
1346         if (asParagraphs)
1347                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1348         else
1349                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1350         cur.forceBufferUpdate();
1351         return true;
1352 }
1353
1354
1355 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1356 {
1357         docstring text;
1358         // Use internal clipboard if it is the most recent one
1359         if (theClipboard().isInternal()) {
1360                 if (!checkPastePossible(0))
1361                         return;
1362
1363                 ParagraphList const & pars = theCuts[0].first;
1364                 ParagraphList::const_iterator it = pars.begin();
1365                 for (; it != pars.end(); ++it) {
1366                         if (it != pars.begin())
1367                                 text += "\n";
1368                         text += (*it).asString();
1369                 }
1370                 asParagraphs = false;
1371         } else {
1372                 // Then try plain text
1373                 text = theClipboard().getAsText(Clipboard::PlainTextType);
1374         }
1375
1376         if (text.empty())
1377                 return;
1378
1379         cur.recordUndo();
1380         cutSelection(cur, false);
1381         if (asParagraphs)
1382                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1383         else
1384                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1385 }
1386
1387
1388 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1389                             Clipboard::GraphicsType preferedType)
1390 {
1391         LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1392
1393         // get picture from clipboard
1394         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1395         if (filename.empty())
1396                 return;
1397
1398         // create inset for graphic
1399         InsetGraphics * inset = new InsetGraphics(cur.buffer());
1400         InsetGraphicsParams params;
1401         params.filename = support::DocFileName(filename.absFileName(), false);
1402         inset->setParams(params);
1403         cur.recordUndo();
1404         cur.insert(inset);
1405 }
1406
1407
1408 void pasteSelection(Cursor & cur, ErrorList & errorList)
1409 {
1410         if (selectionBuffer.empty())
1411                 return;
1412         cur.recordUndo();
1413         pasteParagraphList(cur, selectionBuffer[0].first,
1414                         selectionBuffer[0].second.first,
1415                         selectionBuffer[0].second.second,
1416                         errorList);
1417 }
1418
1419
1420 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1421 {
1422         cur.recordUndo();
1423         DocIterator selbeg = cur.selectionBegin();
1424
1425         // Get font setting before we cut, we need a copy here, not a bare reference.
1426         Font const font =
1427                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1428
1429         // Insert the new string
1430         pos_type pos = cur.selEnd().pos();
1431         Paragraph & par = cur.selEnd().paragraph();
1432         for (auto const & c : str) {
1433                 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1434                 ++pos;
1435         }
1436
1437         // Cut the selection
1438         cutSelection(cur, false);
1439 }
1440
1441
1442 void replaceSelection(Cursor & cur)
1443 {
1444         if (cur.selection())
1445                 cutSelection(cur, false);
1446 }
1447
1448
1449 void eraseSelection(Cursor & cur)
1450 {
1451         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1452         CursorSlice const & i1 = cur.selBegin();
1453         CursorSlice const & i2 = cur.selEnd();
1454         if (!i1.asInsetMath()) {
1455                 LYXERR0("Can't erase this selection");
1456                 return;
1457         }
1458
1459         saveSelection(cur);
1460         cur.top() = i1;
1461         InsetMath * p = i1.asInsetMath();
1462         if (i1.idx() == i2.idx()) {
1463                 i1.cell().erase(i1.pos(), i2.pos());
1464                 // We may have deleted i1.cell(cur.pos()).
1465                 // Make sure that pos is valid.
1466                 if (cur.pos() > cur.lastpos())
1467                         cur.pos() = cur.lastpos();
1468         } else if (p->nrows() > 0 && p->ncols() > 0) {
1469                 // This is a grid, delete a nice square region
1470                 row_type r1, r2;
1471                 col_type c1, c2;
1472                 region(i1, i2, r1, r2, c1, c2);
1473                 for (row_type row = r1; row <= r2; ++row)
1474                         for (col_type col = c1; col <= c2; ++col)
1475                                 p->cell(p->index(row, col)).clear();
1476                 // We've deleted the whole cell. Only pos 0 is valid.
1477                 cur.pos() = 0;
1478         } else {
1479                 idx_type idx1 = i1.idx();
1480                 idx_type idx2 = i2.idx();
1481                 if (idx1 > idx2)
1482                         swap(idx1, idx2);
1483                 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1484                         p->cell(idx).clear();
1485                 // We've deleted the whole cell. Only pos 0 is valid.
1486                 cur.pos() = 0;
1487         }
1488
1489         // need a valid cursor. (Lgb)
1490         cur.clearSelection();
1491         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1492 }
1493
1494
1495 void selDel(Cursor & cur)
1496 {
1497         //lyxerr << "cap::selDel" << endl;
1498         if (cur.selection())
1499                 eraseSelection(cur);
1500 }
1501
1502
1503 void selClearOrDel(Cursor & cur)
1504 {
1505         //lyxerr << "cap::selClearOrDel" << endl;
1506         if (lyxrc.auto_region_delete)
1507                 selDel(cur);
1508         else
1509                 cur.selection(false);
1510 }
1511
1512
1513 docstring grabSelection(CursorData const & cur)
1514 {
1515         if (!cur.selection())
1516                 return docstring();
1517
1518 #if 0
1519         // grab selection by glueing multiple cells together. This is not what
1520         // we want because selections spanning multiple cells will get "&" and "\\"
1521         // seperators.
1522         ostringstream os;
1523         for (DocIterator dit = cur.selectionBegin();
1524              dit != cur.selectionEnd(); dit.forwardPos())
1525                 os << asString(dit.cell());
1526         return os.str();
1527 #endif
1528
1529         CursorSlice i1 = cur.selBegin();
1530         CursorSlice i2 = cur.selEnd();
1531
1532         if (i1.idx() == i2.idx()) {
1533                 if (i1.inset().asInsetMath()) {
1534                         MathData::const_iterator it = i1.cell().begin();
1535                         Buffer * buf = cur.buffer();
1536                         return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1537                 } else {
1538                         return from_ascii("unknown selection 1");
1539                 }
1540         }
1541
1542         row_type r1, r2;
1543         col_type c1, c2;
1544         region(i1, i2, r1, r2, c1, c2);
1545
1546         docstring data;
1547         if (i1.inset().asInsetMath()) {
1548                 for (row_type row = r1; row <= r2; ++row) {
1549                         if (row > r1)
1550                                 data += "\\\\";
1551                         for (col_type col = c1; col <= c2; ++col) {
1552                                 if (col > c1)
1553                                         data += '&';
1554                                 data += asString(i1.asInsetMath()->
1555                                         cell(i1.asInsetMath()->index(row, col)));
1556                         }
1557                 }
1558         } else {
1559                 data = from_ascii("unknown selection 2");
1560         }
1561         return data;
1562 }
1563
1564
1565 void dirtyTabularStack(bool b)
1566 {
1567         dirty_tabular_stack_ = b;
1568 }
1569
1570
1571 bool tabularStackDirty()
1572 {
1573         return dirty_tabular_stack_;
1574 }
1575
1576
1577 } // namespace cap
1578 } // namespace lyx