]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
grammar
[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                         if (!is_undefined)
857                                 continue;
858
859                         // The flex inset is undefined in newtc
860                         docstring const oldname = from_utf8(oldtc.name());
861                         docstring const newname = from_utf8(newtc.name());
862                         docstring s;
863                         if (oldname == newname)
864                                 s = bformat(_("Flex inset %1$s is undefined after "
865                                         "reloading `%2$s' layout."), layoutName, oldname);
866                         else
867                                 s = bformat(_("Flex inset %1$s is undefined because of "
868                                         "conversion from `%2$s' layout to `%3$s'."),
869                                         layoutName, oldname, newname);
870                         // To warn the user that something had to be done.
871                         errorlist.push_back(ErrorItem(
872                                                       _("Undefined flex inset"), s,
873                                                       {iit.paragraph().id(), iit.pos()},
874                                                       {iit.paragraph().id(), iit.pos() + 1}));
875                 } else if (code == TABULAR_CODE) {
876                         // The recursion above does not catch paragraphs in "hidden" cells,
877                         // i.e., ones that are part of a multirow or multicolum. So we need
878                         // to handle those separately.
879                         // This is the cause of bug #9049.
880                         InsetTabular * table = iit->asInsetTabular();
881                         table->setLayoutForHiddenCells(newtc);
882                 }
883         }
884 }
885
886
887 vector<docstring> availableSelections(Buffer const * buf)
888 {
889         vector<docstring> selList;
890         if (!buf)
891                 return selList;
892
893         for (auto const & cut : theCuts) {
894                 ParagraphList const & pars = cut.first;
895                 docstring textSel;
896                 for (auto const & para : pars) {
897                         Paragraph par(para, 0, 46);
898                         // adapt paragraph to current buffer.
899                         par.setInsetBuffers(const_cast<Buffer &>(*buf));
900                         textSel += par.asString(AS_STR_INSETS);
901                         if (textSel.size() > 45) {
902                                 support::truncateWithEllipsis(textSel,45);
903                                 break;
904                         }
905                 }
906                 selList.push_back(textSel);
907         }
908
909         return selList;
910 }
911
912
913 size_type numberOfSelections()
914 {
915         return theCuts.size();
916 }
917
918 namespace {
919
920 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
921 {
922         // This doesn't make sense, if there is no selection
923         if (!cur.selection())
924                 return;
925
926         // OK, we have a selection. This is always between cur.selBegin()
927         // and cur.selEnd()
928
929         if (cur.inTexted()) {
930                 Text * text = cur.text();
931                 LBUFERR(text);
932
933                 saveSelection(cur);
934
935                 // make sure that the depth behind the selection are restored, too
936                 cur.recordUndoSelection();
937                 pit_type begpit = cur.selBegin().pit();
938                 pit_type endpit = cur.selEnd().pit();
939
940                 int endpos = cur.selEnd().pos();
941
942                 BufferParams const & bp = cur.buffer()->params();
943                 if (realcut) {
944                         copySelectionHelper(*cur.buffer(),
945                                 *text,
946                                 begpit, endpit,
947                                 cur.selBegin().pos(), endpos,
948                                 bp.documentClassPtr(), cuts);
949                         // Stuff what we got on the clipboard.
950                         // Even if there is no selection.
951                         if (putclip)
952                                 putClipboard(cuts[0].first, cuts[0].second,
953                                              cur.selectionAsString(true, true), bp);
954                 }
955
956                 if (begpit != endpit)
957                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
958
959                 tie(endpit, endpos) =
960                         eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
961                                              cur.selBegin().pos(), endpos);
962
963                 // cutSelection can invalidate the cursor so we need to set
964                 // it anew. (Lgb)
965                 // we prefer the end for when tracking changes
966                 cur.pos() = endpos;
967                 cur.pit() = endpit;
968
969                 // need a valid cursor. (Lgb)
970                 cur.clearSelection();
971
972                 // After a cut operation, we must make sure that the Buffer is updated
973                 // because some further operation might need updated label information for
974                 // example. So we cannot just use "cur.forceBufferUpdate()" here.
975                 // This fixes #7071.
976                 cur.buffer()->updateBuffer();
977
978                 // tell tabular that a recent copy happened
979                 dirtyTabularStack(false);
980         }
981
982         if (cur.inMathed()) {
983                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
984                         // The current selection spans more than one cell.
985                         // Record all cells
986                         cur.recordUndoInset();
987                 } else {
988                         // Record only the current cell to avoid a jumping
989                         // cursor after undo
990                         cur.recordUndo();
991                 }
992                 if (realcut)
993                         copySelection(cur);
994                 eraseSelection(cur);
995         }
996 }
997
998 } // namespace
999
1000 void cutSelection(Cursor & cur, bool realcut)
1001 {
1002         cutSelectionHelper(cur, theCuts, realcut, true);
1003 }
1004
1005
1006 void cutSelectionToTemp(Cursor & cur, bool realcut)
1007 {
1008         cutSelectionHelper(cur, tempCut, realcut, false);
1009 }
1010
1011
1012 void copySelection(Cursor const & cur)
1013 {
1014         copySelection(cur, cur.selectionAsString(true, true));
1015 }
1016
1017
1018 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1019 {
1020         ParagraphList pars;
1021         Paragraph par;
1022         BufferParams const & bp = cur.buffer()->params();
1023         par.setLayout(bp.documentClass().plainLayout());
1024         Font font(inherit_font, bp.language);
1025         par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1026         pars.push_back(par);
1027         theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1028
1029         // stuff the selection onto the X clipboard, from an explicit copy request
1030         putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1031 }
1032
1033
1034 namespace {
1035
1036 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1037 {
1038         // this doesn't make sense, if there is no selection
1039         if (!cur.selection())
1040                 return;
1041
1042         // copySelection can not yet handle the case of cross idx selection
1043         if (cur.selBegin().idx() != cur.selEnd().idx())
1044                 return;
1045
1046         if (cur.inTexted()) {
1047                 Text * text = cur.text();
1048                 LBUFERR(text);
1049                 // ok we have a selection. This is always between cur.selBegin()
1050                 // and sel_end cursor
1051                 copySelectionHelper(*cur.buffer(), *text,
1052                                     cur.selBegin().pit(), cur.selEnd().pit(),
1053                                     cur.selBegin().pos(), cur.selEnd().pos(),
1054                                     cur.buffer()->params().documentClassPtr(),
1055                                     cutstack);
1056                 // Reset the dirty_tabular_stack_ flag only when something
1057                 // is copied to the clipboard (not to the selectionBuffer).
1058                 if (&cutstack == &theCuts)
1059                         dirtyTabularStack(false);
1060         }
1061
1062         if (cur.inMathed()) {
1063                 //lyxerr << "copySelection in mathed" << endl;
1064                 ParagraphList pars;
1065                 Paragraph par;
1066                 BufferParams const & bp = cur.buffer()->params();
1067                 // FIXME This should be the plain layout...right?
1068                 par.setLayout(bp.documentClass().plainLayout());
1069                 // For pasting into text, we set the language to the paragraph language
1070                 // (rather than the default_language which is always English; see #2596)
1071                 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1072                            Change(Change::UNCHANGED));
1073                 pars.push_back(par);
1074                 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1075         }
1076 }
1077
1078 } // namespace
1079
1080
1081 void copySelectionToStack()
1082 {
1083         if (!selectionBuffer.empty())
1084                 theCuts.push(selectionBuffer[0]);
1085 }
1086
1087
1088 void copySelectionToTemp(Cursor const & cur)
1089 {
1090         copySelectionToStack(cur, tempCut);
1091 }
1092
1093
1094 void copySelection(Cursor const & cur, docstring const & plaintext)
1095 {
1096         // In tablemode, because copy and paste actually use a special table stack,
1097         // we need to go through the cells and collect the paragraphs.
1098         // In math matrices, we generate a plain text version.
1099         if (cur.selBegin().idx() != cur.selEnd().idx()) {
1100                 ParagraphList pars;
1101                 BufferParams const & bp = cur.buffer()->params();
1102                 if (cur.inMathed()) {
1103                         Paragraph par;
1104                         par.setLayout(bp.documentClass().plainLayout());
1105                         // Replace (column-separating) tabs by space (#4449)
1106                         docstring const clean_text = subst(plaintext, '\t', ' ');
1107                         // For pasting into text, we set the language to the paragraph language
1108                         // (rather than the default_language which is always English; see #11898)
1109                         par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1110                                    Change(Change::UNCHANGED));
1111                         pars.push_back(par);
1112                 } else {
1113                         // Get paragraphs from all cells
1114                         InsetTabular * table = cur.inset().asInsetTabular();
1115                         LASSERT(table, return);
1116                         ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1117                         for (auto & cpar : tplist) {
1118                                 cpar.setLayout(bp.documentClass().plainLayout());
1119                                 pars.push_back(cpar);
1120                                 // since the pars are merged later, we separate them by blank
1121                                 Paragraph epar;
1122                                 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1123                                             Change(Change::UNCHANGED));
1124                                 pars.push_back(epar);
1125                         }
1126                         // remove last empty par
1127                         pars.pop_back();
1128                         // merge all paragraphs to one
1129                         while (pars.size() > 1)
1130                                 mergeParagraph(bp, pars, 0);
1131                 }
1132                 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1133         } else {
1134                 copySelectionToStack(cur, theCuts);
1135         }
1136
1137         // stuff the selection onto the X clipboard, from an explicit copy request
1138         putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1139                         cur.buffer()->params());
1140 }
1141
1142
1143 void saveSelection(Cursor const & cur)
1144 {
1145         // This function is called, not when a selection is formed, but when
1146         // a selection is cleared. Therefore, multiple keyboard selection
1147         // will not repeatively trigger this function (bug 3877).
1148         if (cur.selection()
1149             && cur.selBegin() == cur.bv().cursor().selBegin()
1150             && cur.selEnd() == cur.bv().cursor().selEnd()) {
1151                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1152                 copySelectionToStack(cur, selectionBuffer);
1153         }
1154 }
1155
1156
1157 bool selection()
1158 {
1159         return !selectionBuffer.empty();
1160 }
1161
1162
1163 void clearSelection()
1164 {
1165         selectionBuffer.clear();
1166 }
1167
1168
1169 void clearCutStack()
1170 {
1171         theCuts.clear();
1172         tempCut.clear();
1173 }
1174
1175
1176 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1177 {
1178         if (sel_index >= theCuts.size())
1179                 return docstring();
1180
1181         unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1182                                                    docinfo.first));
1183         if (!buffer)
1184                 return docstring();
1185
1186         int options = AS_STR_INSETS | AS_STR_NEWLINES;
1187         if (for_math)
1188                 options |= AS_STR_MATHED;
1189
1190         return buffer->paragraphs().back().asString(options);
1191 }
1192
1193
1194 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1195                         DocumentClassConstPtr docclass, AuthorList const & authors,
1196                         ErrorList & errorList,
1197                         cap::BranchAction branchAction)
1198 {
1199         // Copy authors to the params. We need those pointers.
1200         for (Author const & a : authors)
1201                 cur.buffer()->params().authors().record(a);
1202         
1203         if (cur.inTexted()) {
1204                 Text * text = cur.text();
1205                 LBUFERR(text);
1206
1207                 PasteReturnValue prv =
1208                         pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1209                 cur.forceBufferUpdate();
1210                 cur.clearSelection();
1211                 text->setCursor(cur, prv.pit, prv.pos);
1212         }
1213
1214         // mathed is handled in InsetMathNest/InsetMathGrid
1215         LATTEST(!cur.inMathed());
1216 }
1217
1218
1219 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1220 {
1221         // this does not make sense, if there is nothing to paste
1222         if (!checkPastePossible(sel_index))
1223                 return false;
1224
1225         cur.recordUndo();
1226         pasteParagraphList(cur, theCuts[sel_index].first,
1227                            theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1228                            errorList, BRANCH_ASK);
1229         return true;
1230 }
1231
1232
1233 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1234 {
1235         // this does not make sense, if there is nothing to paste
1236         if (tempCut.empty() || tempCut[0].first.empty())
1237                 return false;
1238
1239         cur.recordUndo();
1240         pasteParagraphList(cur, tempCut[0].first,
1241                         tempCut[0].second.first, tempCut[0].second.second,
1242                         errorList, BRANCH_IGNORE);
1243         return true;
1244 }
1245
1246
1247 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1248                         Clipboard::TextType type)
1249 {
1250         // Use internal clipboard if it is the most recent one
1251         // This overrides asParagraphs and type on purpose!
1252         if (theClipboard().isInternal())
1253                 return pasteFromStack(cur, errorList, 0);
1254
1255         // First try LyX format
1256         if ((type == Clipboard::LyXTextType ||
1257              type == Clipboard::LyXOrPlainTextType ||
1258              type == Clipboard::AnyTextType) &&
1259             theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1260                 string lyx = theClipboard().getAsLyX();
1261                 if (!lyx.empty()) {
1262                         Buffer buffer(string(), false);
1263                         buffer.setUnnamed(true);
1264                         if (buffer.readString(lyx)) {
1265                                 cur.recordUndo();
1266                                 pasteParagraphList(cur, buffer.paragraphs(),
1267                                                    buffer.params().documentClassPtr(),
1268                                                    buffer.params().authors(),
1269                                                    errorList);
1270                                 return true;
1271                         }
1272                 }
1273         }
1274
1275         // Then try TeX and HTML
1276         Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1277         string names[2] = {"html", "latexclipboard"};
1278         for (int i = 0; i < 2; ++i) {
1279                 if (type != types[i] && type != Clipboard::AnyTextType)
1280                         continue;
1281                 bool available = theClipboard().hasTextContents(types[i]);
1282
1283                 // If a specific type was explicitly requested, try to
1284                 // interpret plain text: The user told us that the clipboard
1285                 // contents is in the desired format
1286                 if (!available && type == types[i]) {
1287                         types[i] = Clipboard::PlainTextType;
1288                         available = theClipboard().hasTextContents(types[i]);
1289                 }
1290
1291                 if (available) {
1292                         docstring text = theClipboard().getAsText(types[i]);
1293                         available = !text.empty();
1294                         if (available) {
1295                                 Buffer buffer(string(), false);
1296                                 buffer.setUnnamed(true);
1297                                 available = buffer.importString(names[i], text, errorList);
1298                                 if (available)
1299                                         available = !buffer.paragraphs().empty();
1300                                 if (available && !buffer.paragraphs()[0].empty()) {
1301                                         // TeX2lyx (also used in the HTML chain) assumes English as document language
1302                                         // if no language is explicitly set (as is the case here).
1303                                         // We thus reset the temp buffer's language to the context language
1304                                         buffer.changeLanguage(buffer.language(), cur.getFont().language());
1305                                         cur.recordUndo();
1306                                         pasteParagraphList(cur, buffer.paragraphs(),
1307                                                            buffer.params().documentClassPtr(),
1308                                                            buffer.params().authors(),
1309                                                            errorList);
1310                                         return true;
1311                                 }
1312                         }
1313                 }
1314         }
1315
1316         // Then try plain text
1317         docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1318         if (text.empty())
1319                 return false;
1320         cur.recordUndo();
1321         if (asParagraphs)
1322                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1323         else
1324                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1325         cur.forceBufferUpdate();
1326         return true;
1327 }
1328
1329
1330 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1331 {
1332         docstring text;
1333         // Use internal clipboard if it is the most recent one
1334         if (theClipboard().isInternal()) {
1335                 if (!checkPastePossible(0))
1336                         return;
1337
1338                 ParagraphList const & pars = theCuts[0].first;
1339                 ParagraphList::const_iterator it = pars.begin();
1340                 for (; it != pars.end(); ++it) {
1341                         if (it != pars.begin())
1342                                 text += "\n";
1343                         text += (*it).asString();
1344                 }
1345                 asParagraphs = false;
1346         } else {
1347                 // Then try plain text
1348                 text = theClipboard().getAsText(Clipboard::PlainTextType);
1349         }
1350
1351         if (text.empty())
1352                 return;
1353
1354         cur.recordUndo();
1355         cutSelection(cur, false);
1356         if (asParagraphs)
1357                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1358         else
1359                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1360 }
1361
1362
1363 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1364                             Clipboard::GraphicsType preferedType)
1365 {
1366         LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1367
1368         // get picture from clipboard
1369         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1370         if (filename.empty())
1371                 return;
1372
1373         // create inset for graphic
1374         InsetGraphics * inset = new InsetGraphics(cur.buffer());
1375         InsetGraphicsParams params;
1376         params.filename = support::DocFileName(filename.absFileName(), false);
1377         inset->setParams(params);
1378         cur.recordUndo();
1379         cur.insert(inset);
1380 }
1381
1382
1383 void pasteSelection(Cursor & cur, ErrorList & errorList)
1384 {
1385         if (selectionBuffer.empty())
1386                 return;
1387         cur.recordUndo();
1388         pasteParagraphList(cur, selectionBuffer[0].first,
1389                         selectionBuffer[0].second.first,
1390                         selectionBuffer[0].second.second,
1391                         errorList);
1392 }
1393
1394
1395 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1396 {
1397         cur.recordUndo();
1398         DocIterator selbeg = cur.selectionBegin();
1399
1400         // Get font setting before we cut, we need a copy here, not a bare reference.
1401         Font const font =
1402                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1403
1404         // Insert the new string
1405         pos_type pos = cur.selEnd().pos();
1406         Paragraph & par = cur.selEnd().paragraph();
1407         for (auto const & c : str) {
1408                 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1409                 ++pos;
1410         }
1411
1412         // Cut the selection
1413         cutSelection(cur, false);
1414 }
1415
1416
1417 void replaceSelection(Cursor & cur)
1418 {
1419         if (cur.selection())
1420                 cutSelection(cur, false);
1421 }
1422
1423
1424 void eraseSelection(Cursor & cur)
1425 {
1426         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1427         CursorSlice const & i1 = cur.selBegin();
1428         CursorSlice const & i2 = cur.selEnd();
1429         if (!i1.asInsetMath()) {
1430                 LYXERR0("Can't erase this selection");
1431                 return;
1432         }
1433
1434         saveSelection(cur);
1435         cur.top() = i1;
1436         InsetMath * p = i1.asInsetMath();
1437         if (i1.idx() == i2.idx()) {
1438                 i1.cell().erase(i1.pos(), i2.pos());
1439                 // We may have deleted i1.cell(cur.pos()).
1440                 // Make sure that pos is valid.
1441                 if (cur.pos() > cur.lastpos())
1442                         cur.pos() = cur.lastpos();
1443         } else if (p->nrows() > 0 && p->ncols() > 0) {
1444                 // This is a grid, delete a nice square region
1445                 row_type r1, r2;
1446                 col_type c1, c2;
1447                 region(i1, i2, r1, r2, c1, c2);
1448                 for (row_type row = r1; row <= r2; ++row)
1449                         for (col_type col = c1; col <= c2; ++col)
1450                                 p->cell(p->index(row, col)).clear();
1451                 // We've deleted the whole cell. Only pos 0 is valid.
1452                 cur.pos() = 0;
1453         } else {
1454                 idx_type idx1 = i1.idx();
1455                 idx_type idx2 = i2.idx();
1456                 if (idx1 > idx2)
1457                         swap(idx1, idx2);
1458                 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1459                         p->cell(idx).clear();
1460                 // We've deleted the whole cell. Only pos 0 is valid.
1461                 cur.pos() = 0;
1462         }
1463
1464         // need a valid cursor. (Lgb)
1465         cur.clearSelection();
1466         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1467 }
1468
1469
1470 void selDel(Cursor & cur)
1471 {
1472         //lyxerr << "cap::selDel" << endl;
1473         if (cur.selection())
1474                 eraseSelection(cur);
1475 }
1476
1477
1478 void selClearOrDel(Cursor & cur)
1479 {
1480         //lyxerr << "cap::selClearOrDel" << endl;
1481         if (lyxrc.auto_region_delete)
1482                 selDel(cur);
1483         else
1484                 cur.selection(false);
1485 }
1486
1487
1488 docstring grabSelection(CursorData const & cur)
1489 {
1490         if (!cur.selection())
1491                 return docstring();
1492
1493 #if 0
1494         // grab selection by glueing multiple cells together. This is not what
1495         // we want because selections spanning multiple cells will get "&" and "\\"
1496         // seperators.
1497         ostringstream os;
1498         for (DocIterator dit = cur.selectionBegin();
1499              dit != cur.selectionEnd(); dit.forwardPos())
1500                 os << asString(dit.cell());
1501         return os.str();
1502 #endif
1503
1504         CursorSlice i1 = cur.selBegin();
1505         CursorSlice i2 = cur.selEnd();
1506
1507         if (i1.idx() == i2.idx()) {
1508                 if (i1.inset().asInsetMath()) {
1509                         MathData::const_iterator it = i1.cell().begin();
1510                         Buffer * buf = cur.buffer();
1511                         return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1512                 } else {
1513                         return from_ascii("unknown selection 1");
1514                 }
1515         }
1516
1517         row_type r1, r2;
1518         col_type c1, c2;
1519         region(i1, i2, r1, r2, c1, c2);
1520
1521         docstring data;
1522         if (i1.inset().asInsetMath()) {
1523                 for (row_type row = r1; row <= r2; ++row) {
1524                         if (row > r1)
1525                                 data += "\\\\";
1526                         for (col_type col = c1; col <= c2; ++col) {
1527                                 if (col > c1)
1528                                         data += '&';
1529                                 data += asString(i1.asInsetMath()->
1530                                         cell(i1.asInsetMath()->index(row, col)));
1531                         }
1532                 }
1533         } else {
1534                 data = from_ascii("unknown selection 2");
1535         }
1536         return data;
1537 }
1538
1539
1540 void dirtyTabularStack(bool b)
1541 {
1542         dirty_tabular_stack_ = b;
1543 }
1544
1545
1546 bool tabularStackDirty()
1547 {
1548         return dirty_tabular_stack_;
1549 }
1550
1551
1552 } // namespace cap
1553 } // namespace lyx