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