]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Update shortcuts in fr.po
[lyx.git] / src / CutAndPaste.cpp
1 /**
2  * \file CutAndPaste.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "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].setBuffer(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->setBuffer(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(Cursor & 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(Cursor 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.setBuffer(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 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                 // need a valid cursor. (Lgb)
958                 cur.clearSelection();
959
960                 // After a cut operation, we must make sure that the Buffer is updated
961                 // because some further operation might need updated label information for
962                 // example. So we cannot just use "cur.forceBufferUpdate()" here.
963                 // This fixes #7071.
964                 cur.buffer()->updateBuffer();
965
966                 // tell tabular that a recent copy happened
967                 dirtyTabularStack(false);
968         }
969
970         if (cur.inMathed()) {
971                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
972                         // The current selection spans more than one cell.
973                         // Record all cells
974                         cur.recordUndoInset();
975                 } else {
976                         // Record only the current cell to avoid a jumping
977                         // cursor after undo
978                         cur.recordUndo();
979                 }
980                 if (realcut)
981                         copySelection(cur);
982                 eraseSelection(cur);
983         }
984 }
985
986 } // namespace
987
988 void cutSelection(Cursor & cur, bool realcut)
989 {
990         cutSelectionHelper(cur, theCuts, realcut, true);
991 }
992
993
994 void cutSelectionToTemp(Cursor & cur, bool realcut)
995 {
996         cutSelectionHelper(cur, tempCut, realcut, false);
997 }
998
999
1000 void copySelection(Cursor const & cur)
1001 {
1002         copySelection(cur, cur.selectionAsString(true));
1003 }
1004
1005
1006 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1007 {
1008         ParagraphList pars;
1009         Paragraph par;
1010         BufferParams const & bp = cur.buffer()->params();
1011         par.setLayout(bp.documentClass().plainLayout());
1012         Font font(inherit_font, bp.language);
1013         par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1014         pars.push_back(par);
1015         theCuts.push(make_pair(pars, bp.documentClassPtr()));
1016
1017         // stuff the selection onto the X clipboard, from an explicit copy request
1018         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1019 }
1020
1021
1022 namespace {
1023
1024 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
1025 {
1026         // this doesn't make sense, if there is no selection
1027         if (!cur.selection())
1028                 return;
1029
1030         // copySelection can not yet handle the case of cross idx selection
1031         if (cur.selBegin().idx() != cur.selEnd().idx())
1032                 return;
1033
1034         if (cur.inTexted()) {
1035                 Text * text = cur.text();
1036                 LBUFERR(text);
1037                 // ok we have a selection. This is always between cur.selBegin()
1038                 // and sel_end cursor
1039                 copySelectionHelper(*cur.buffer(), *text,
1040                                     cur.selBegin().pit(), cur.selEnd().pit(),
1041                                     cur.selBegin().pos(), cur.selEnd().pos(),
1042                                     cur.buffer()->params().documentClassPtr(),
1043                                     cutstack);
1044                 // Reset the dirty_tabular_stack_ flag only when something
1045                 // is copied to the clipboard (not to the selectionBuffer).
1046                 if (&cutstack == &theCuts)
1047                         dirtyTabularStack(false);
1048         }
1049
1050         if (cur.inMathed()) {
1051                 //lyxerr << "copySelection in mathed" << endl;
1052                 ParagraphList pars;
1053                 Paragraph par;
1054                 BufferParams const & bp = cur.buffer()->params();
1055                 // FIXME This should be the plain layout...right?
1056                 par.setLayout(bp.documentClass().plainLayout());
1057                 // For pasting into text, we set the language to the paragraph language
1058                 // (rather than the default_language which is always English; see #2596)
1059                 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1060                            Change(Change::UNCHANGED));
1061                 pars.push_back(par);
1062                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1063         }
1064 }
1065
1066 } // namespace
1067
1068
1069 void copySelectionToStack()
1070 {
1071         if (!selectionBuffer.empty())
1072                 theCuts.push(selectionBuffer[0]);
1073 }
1074
1075
1076 void copySelectionToTemp(Cursor & cur)
1077 {
1078         copySelectionToStack(cur, tempCut);
1079 }
1080
1081
1082 void copySelection(Cursor const & cur, docstring const & plaintext)
1083 {
1084         // In tablemode, because copy and paste actually use special table stack
1085         // we do not attempt to get selected paragraphs under cursor. Instead, a
1086         // paragraph with the plain text version is generated so that table cells
1087         // can be pasted as pure text somewhere else.
1088         if (cur.selBegin().idx() != cur.selEnd().idx()) {
1089                 ParagraphList pars;
1090                 Paragraph par;
1091                 BufferParams const & bp = cur.buffer()->params();
1092                 par.setLayout(bp.documentClass().plainLayout());
1093                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1094                 pars.push_back(par);
1095                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1096         } else {
1097                 copySelectionToStack(cur, theCuts);
1098         }
1099
1100         // stuff the selection onto the X clipboard, from an explicit copy request
1101         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1102 }
1103
1104
1105 void saveSelection(Cursor const & cur)
1106 {
1107         // This function is called, not when a selection is formed, but when
1108         // a selection is cleared. Therefore, multiple keyboard selection
1109         // will not repeatively trigger this function (bug 3877).
1110         if (cur.selection()
1111             && cur.selBegin() == cur.bv().cursor().selBegin()
1112             && cur.selEnd() == cur.bv().cursor().selEnd()) {
1113                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1114                 copySelectionToStack(cur, selectionBuffer);
1115         }
1116 }
1117
1118
1119 bool selection()
1120 {
1121         return !selectionBuffer.empty();
1122 }
1123
1124
1125 void clearSelection()
1126 {
1127         selectionBuffer.clear();
1128 }
1129
1130
1131 void clearCutStack()
1132 {
1133         theCuts.clear();
1134         tempCut.clear();
1135 }
1136
1137
1138 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1139 {
1140         if (sel_index >= theCuts.size())
1141                 return docstring();
1142
1143         unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1144                                                    docclass));
1145         if (!buffer)
1146                 return docstring();
1147
1148         return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1149 }
1150
1151
1152 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1153                                                 DocumentClassConstPtr docclass, ErrorList & errorList,
1154                                                 cap::BranchAction branchAction)
1155 {
1156         if (cur.inTexted()) {
1157                 Text * text = cur.text();
1158                 LBUFERR(text);
1159
1160                 PasteReturnValue prv =
1161                         pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1162                 cur.forceBufferUpdate();
1163                 cur.clearSelection();
1164                 text->setCursor(cur, prv.pit, prv.pos);
1165         }
1166
1167         // mathed is handled in InsetMathNest/InsetMathGrid
1168         LATTEST(!cur.inMathed());
1169 }
1170
1171
1172 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1173 {
1174         // this does not make sense, if there is nothing to paste
1175         if (!checkPastePossible(sel_index))
1176                 return false;
1177
1178         cur.recordUndo();
1179         pasteParagraphList(cur, theCuts[sel_index].first,
1180                            theCuts[sel_index].second, errorList, BRANCH_ASK);
1181         return true;
1182 }
1183
1184
1185 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1186 {
1187         // this does not make sense, if there is nothing to paste
1188         if (tempCut.empty() || tempCut[0].first.empty())
1189                 return false;
1190
1191         cur.recordUndo();
1192         pasteParagraphList(cur, tempCut[0].first,
1193                            tempCut[0].second, errorList, BRANCH_IGNORE);
1194         return true;
1195 }
1196
1197
1198 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1199                         Clipboard::TextType type)
1200 {
1201         // Use internal clipboard if it is the most recent one
1202         // This overrides asParagraphs and type on purpose!
1203         if (theClipboard().isInternal())
1204                 return pasteFromStack(cur, errorList, 0);
1205
1206         // First try LyX format
1207         if ((type == Clipboard::LyXTextType ||
1208              type == Clipboard::LyXOrPlainTextType ||
1209              type == Clipboard::AnyTextType) &&
1210             theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1211                 string lyx = theClipboard().getAsLyX();
1212                 if (!lyx.empty()) {
1213                         // For some strange reason gcc 3.2 and 3.3 do not accept
1214                         // Buffer buffer(string(), false);
1215                         Buffer buffer("", false);
1216                         buffer.setUnnamed(true);
1217                         if (buffer.readString(lyx)) {
1218                                 cur.recordUndo();
1219                                 pasteParagraphList(cur, buffer.paragraphs(),
1220                                         buffer.params().documentClassPtr(), errorList);
1221                                 return true;
1222                         }
1223                 }
1224         }
1225
1226         // Then try TeX and HTML
1227         Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1228         string names[2] = {"html", "latexclipboard"};
1229         for (int i = 0; i < 2; ++i) {
1230                 if (type != types[i] && type != Clipboard::AnyTextType)
1231                         continue;
1232                 bool available = theClipboard().hasTextContents(types[i]);
1233
1234                 // If a specific type was explicitly requested, try to
1235                 // interpret plain text: The user told us that the clipboard
1236                 // contents is in the desired format
1237                 if (!available && type == types[i]) {
1238                         types[i] = Clipboard::PlainTextType;
1239                         available = theClipboard().hasTextContents(types[i]);
1240                 }
1241
1242                 if (available) {
1243                         docstring text = theClipboard().getAsText(types[i]);
1244                         available = !text.empty();
1245                         if (available) {
1246                                 // For some strange reason gcc 3.2 and 3.3 do not accept
1247                                 // Buffer buffer(string(), false);
1248                                 Buffer buffer("", false);
1249                                 buffer.setUnnamed(true);
1250                                 available = buffer.importString(names[i], text, errorList);
1251                                 if (available)
1252                                         available = !buffer.paragraphs().empty();
1253                                 if (available && !buffer.paragraphs()[0].empty()) {
1254                                         // TeX2lyx (also used in the HTML chain) assumes English as document language
1255                                         // if no language is explicitly set (as is the case here).
1256                                         // We thus reset the temp buffer's language to the context language
1257                                         buffer.changeLanguage(buffer.language(), cur.getFont().language());
1258                                         cur.recordUndo();
1259                                         pasteParagraphList(cur, buffer.paragraphs(),
1260                                                 buffer.params().documentClassPtr(), errorList);
1261                                         return true;
1262                                 }
1263                         }
1264                 }
1265         }
1266
1267         // Then try plain text
1268         docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1269         if (text.empty())
1270                 return false;
1271         cur.recordUndo();
1272         if (asParagraphs)
1273                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1274         else
1275                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1276         cur.forceBufferUpdate();
1277         return true;
1278 }
1279
1280
1281 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1282 {
1283         docstring text;
1284         // Use internal clipboard if it is the most recent one
1285         if (theClipboard().isInternal()) {
1286                 if (!checkPastePossible(0))
1287                         return;
1288
1289                 ParagraphList const & pars = theCuts[0].first;
1290                 ParagraphList::const_iterator it = pars.begin();
1291                 for (; it != pars.end(); ++it) {
1292                         if (it != pars.begin())
1293                                 text += "\n";
1294                         text += (*it).asString();
1295                 }
1296                 asParagraphs = false;
1297         } else {
1298                 // Then try plain text
1299                 text = theClipboard().getAsText(Clipboard::PlainTextType);
1300         }
1301
1302         if (text.empty())
1303                 return;
1304
1305         cur.recordUndo();
1306         cutSelection(cur, false);
1307         if (asParagraphs)
1308                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1309         else
1310                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1311 }
1312
1313
1314 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1315                             Clipboard::GraphicsType preferedType)
1316 {
1317         LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1318
1319         // get picture from clipboard
1320         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1321         if (filename.empty())
1322                 return;
1323
1324         // create inset for graphic
1325         InsetGraphics * inset = new InsetGraphics(cur.buffer());
1326         InsetGraphicsParams params;
1327         params.filename = support::DocFileName(filename.absFileName(), false);
1328         inset->setParams(params);
1329         cur.recordUndo();
1330         cur.insert(inset);
1331 }
1332
1333
1334 void pasteSelection(Cursor & cur, ErrorList & errorList)
1335 {
1336         if (selectionBuffer.empty())
1337                 return;
1338         cur.recordUndo();
1339         pasteParagraphList(cur, selectionBuffer[0].first,
1340                            selectionBuffer[0].second, errorList);
1341 }
1342
1343
1344 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1345 {
1346         cur.recordUndo();
1347         DocIterator selbeg = cur.selectionBegin();
1348
1349         // Get font setting before we cut, we need a copy here, not a bare reference.
1350         Font const font =
1351                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1352
1353         // Insert the new string
1354         pos_type pos = cur.selEnd().pos();
1355         Paragraph & par = cur.selEnd().paragraph();
1356         docstring::const_iterator cit = str.begin();
1357         docstring::const_iterator end = str.end();
1358         for (; cit != end; ++cit, ++pos)
1359                 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1360
1361         // Cut the selection
1362         cutSelection(cur, false);
1363 }
1364
1365
1366 void replaceSelection(Cursor & cur)
1367 {
1368         if (cur.selection())
1369                 cutSelection(cur, false);
1370 }
1371
1372
1373 void eraseSelection(Cursor & cur)
1374 {
1375         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1376         CursorSlice const & i1 = cur.selBegin();
1377         CursorSlice const & i2 = cur.selEnd();
1378         if (!i1.asInsetMath()) {
1379                 LYXERR0("Can't erase this selection");
1380                 return;
1381         }
1382
1383         saveSelection(cur);
1384         cur.top() = i1;
1385         InsetMath * p = i1.asInsetMath();
1386         if (i1.idx() == i2.idx()) {
1387                 i1.cell().erase(i1.pos(), i2.pos());
1388                 // We may have deleted i1.cell(cur.pos()).
1389                 // Make sure that pos is valid.
1390                 if (cur.pos() > cur.lastpos())
1391                         cur.pos() = cur.lastpos();
1392         } else if (p->nrows() > 0 && p->ncols() > 0) {
1393                 // This is a grid, delete a nice square region
1394                 Inset::row_type r1, r2;
1395                 Inset::col_type c1, c2;
1396                 region(i1, i2, r1, r2, c1, c2);
1397                 for (Inset::row_type row = r1; row <= r2; ++row)
1398                         for (Inset::col_type col = c1; col <= c2; ++col)
1399                                 p->cell(p->index(row, col)).clear();
1400                 // We've deleted the whole cell. Only pos 0 is valid.
1401                 cur.pos() = 0;
1402         } else {
1403                 Inset::idx_type idx1 = i1.idx();
1404                 Inset::idx_type idx2 = i2.idx();
1405                 if (idx1 > idx2)
1406                         swap(idx1, idx2);
1407                 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1408                         p->cell(idx).clear();
1409                 // We've deleted the whole cell. Only pos 0 is valid.
1410                 cur.pos() = 0;
1411         }
1412
1413         // need a valid cursor. (Lgb)
1414         cur.clearSelection();
1415         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1416 }
1417
1418
1419 void selDel(Cursor & cur)
1420 {
1421         //lyxerr << "cap::selDel" << endl;
1422         if (cur.selection())
1423                 eraseSelection(cur);
1424 }
1425
1426
1427 void selClearOrDel(Cursor & cur)
1428 {
1429         //lyxerr << "cap::selClearOrDel" << endl;
1430         if (lyxrc.auto_region_delete)
1431                 selDel(cur);
1432         else
1433                 cur.selection(false);
1434 }
1435
1436
1437 docstring grabSelection(Cursor const & cur)
1438 {
1439         if (!cur.selection())
1440                 return docstring();
1441
1442 #if 0
1443         // grab selection by glueing multiple cells together. This is not what
1444         // we want because selections spanning multiple cells will get "&" and "\\"
1445         // seperators.
1446         ostringstream os;
1447         for (DocIterator dit = cur.selectionBegin();
1448              dit != cur.selectionEnd(); dit.forwardPos())
1449                 os << asString(dit.cell());
1450         return os.str();
1451 #endif
1452
1453         CursorSlice i1 = cur.selBegin();
1454         CursorSlice i2 = cur.selEnd();
1455
1456         if (i1.idx() == i2.idx()) {
1457                 if (i1.inset().asInsetMath()) {
1458                         MathData::const_iterator it = i1.cell().begin();
1459                         Buffer * buf = cur.buffer();
1460                         return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1461                 } else {
1462                         return from_ascii("unknown selection 1");
1463                 }
1464         }
1465
1466         Inset::row_type r1, r2;
1467         Inset::col_type c1, c2;
1468         region(i1, i2, r1, r2, c1, c2);
1469
1470         docstring data;
1471         if (i1.inset().asInsetMath()) {
1472                 for (Inset::row_type row = r1; row <= r2; ++row) {
1473                         if (row > r1)
1474                                 data += "\\\\";
1475                         for (Inset::col_type col = c1; col <= c2; ++col) {
1476                                 if (col > c1)
1477                                         data += '&';
1478                                 data += asString(i1.asInsetMath()->
1479                                         cell(i1.asInsetMath()->index(row, col)));
1480                         }
1481                 }
1482         } else {
1483                 data = from_ascii("unknown selection 2");
1484         }
1485         return data;
1486 }
1487
1488
1489 void dirtyTabularStack(bool b)
1490 {
1491         dirty_tabular_stack_ = b;
1492 }
1493
1494
1495 bool tabularStackDirty()
1496 {
1497         return dirty_tabular_stack_;
1498 }
1499
1500
1501 } // namespace cap
1502 } // namespace lyx