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