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