2 * \file CutAndPaste.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
8 * \author Alfredo Braunstein
11 * Full author contact details are available in file CREDITS.
16 #include "CutAndPaste.h"
18 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
27 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "InsetIterator.h"
31 #include "InsetList.h"
36 #include "Paragraph.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "TextClass.h"
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetBranch.h"
43 #include "insets/InsetCommand.h"
44 #include "insets/InsetFlex.h"
45 #include "insets/InsetGraphics.h"
46 #include "insets/InsetGraphicsParams.h"
47 #include "insets/InsetInclude.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetTabular.h"
51 #include "mathed/MathData.h"
52 #include "mathed/InsetMath.h"
53 #include "mathed/InsetMathHull.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathSupport.h"
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/limited_stack.h"
62 #include "support/lstrings.h"
63 #include "support/TempFile.h"
65 #include "frontends/alert.h"
66 #include "frontends/Clipboard.h"
67 #include "frontends/Selection.h"
69 #include <boost/tuple/tuple.hpp>
70 #include <boost/next_prior.hpp>
75 using namespace lyx::support;
76 using lyx::frontend::Clipboard;
82 typedef pair<pit_type, int> PitPosPair;
84 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
87 // persistent selection, cleared until the next selection
88 CutStack selectionBuffer(1);
90 // store whether the tabular stack is newer than the normal copy stack
91 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
92 // when we (hopefully) have a one-for-all paste mechanism.
93 bool dirty_tabular_stack_ = false;
96 bool checkPastePossible(int index)
98 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
102 struct PasteReturnValue {
103 PasteReturnValue(pit_type r_par, pos_type r_pos, bool r_nu) :
104 par(r_par), pos(r_pos), needupdate(r_nu)
113 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
114 DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
115 ErrorList & errorlist)
117 Buffer const & buffer = *cur.buffer();
118 pit_type pit = cur.pit();
119 pos_type pos = cur.pos();
120 bool need_update = false;
123 return PasteReturnValue(pit, pos, need_update);
125 InsetText * target_inset = cur.inset().asInsetText();
127 InsetTabular * it = cur.inset().asInsetTabular();
128 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
130 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
132 ParagraphList & pars = target_inset->paragraphs();
133 LASSERT(pos <= pars[pit].size(),
134 return PasteReturnValue(pit, pos, need_update));
136 // Make a copy of the CaP paragraphs.
137 ParagraphList insertion = parlist;
139 // Now remove all out of the pars which is NOT allowed in the
140 // new environment and set also another font if that is required.
142 // Convert newline to paragraph break in ParbreakIsNewline
143 if (target_inset->getLayout().parbreakIsNewline()
144 || pars[pit].layout().parbreak_is_newline) {
145 for (size_t i = 0; i != insertion.size(); ++i) {
146 for (pos_type j = 0; j != insertion[i].size(); ++j) {
147 if (insertion[i].isNewline(j)) {
148 // do not track deletion of newline
149 insertion[i].eraseChar(j, false);
150 insertion[i].setInsetOwner(target_inset);
151 breakParagraphConservative(
160 // set the paragraphs to plain layout if necessary
161 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
162 if (cur.inset().usePlainLayout()) {
163 bool forcePlainLayout = cur.inset().forcePlainLayout();
164 Layout const & plainLayout = newDocClass->plainLayout();
165 Layout const & defaultLayout = newDocClass->defaultLayout();
166 ParagraphList::iterator const end = insertion.end();
167 ParagraphList::iterator par = insertion.begin();
168 for (; par != end; ++par) {
169 Layout const & parLayout = par->layout();
170 if (forcePlainLayout || parLayout == defaultLayout)
171 par->setLayout(plainLayout);
173 } else { // check if we need to reset from plain layout
174 Layout const & defaultLayout = newDocClass->defaultLayout();
175 Layout const & plainLayout = newDocClass->plainLayout();
176 ParagraphList::iterator const end = insertion.end();
177 ParagraphList::iterator par = insertion.begin();
178 for (; par != end; ++par) {
179 Layout const & parLayout = par->layout();
180 if (parLayout == plainLayout)
181 par->setLayout(defaultLayout);
185 InsetText in(cur.buffer());
186 // Make sure there is no class difference.
187 in.paragraphs().clear();
188 // This works without copying any paragraph data because we have
189 // a specialized swap method for ParagraphList. This is important
190 // since we store pointers to insets at some places and we don't
191 // want to invalidate them.
192 insertion.swap(in.paragraphs());
193 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
194 insertion.swap(in.paragraphs());
196 ParagraphList::iterator tmpbuf = insertion.begin();
197 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
199 depth_type max_depth = pars[pit].getMaxDepthAfter();
201 for (; tmpbuf != insertion.end(); ++tmpbuf) {
202 // If we have a negative jump so that the depth would
203 // go below 0 depth then we have to redo the delta to
204 // this new max depth level so that subsequent
205 // paragraphs are aligned correctly to this paragraph
207 if (int(tmpbuf->params().depth()) + depth_delta < 0)
210 // Set the right depth so that we are not too deep or shallow.
211 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
212 if (tmpbuf->params().depth() > max_depth)
213 tmpbuf->params().depth(max_depth);
215 // Set max_depth for the next paragraph
216 max_depth = tmpbuf->getMaxDepthAfter();
218 // Set the inset owner of this paragraph.
219 tmpbuf->setInsetOwner(target_inset);
220 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
221 // do not track deletion of invalid insets
222 if (Inset * inset = tmpbuf->getInset(i))
223 if (!target_inset->insetAllowed(inset->lyxCode()))
224 tmpbuf->eraseChar(i--, false);
227 tmpbuf->setChange(Change(buffer.params().track_changes ?
228 Change::INSERTED : Change::UNCHANGED));
231 bool const empty = pars[pit].empty();
233 // Make the buf exactly the same layout as the cursor
235 insertion.begin()->makeSameLayout(pars[pit]);
238 // Prepare the paragraphs and insets for insertion.
239 insertion.swap(in.paragraphs());
241 InsetIterator const i_end = inset_iterator_end(in);
242 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
243 // Even though this will also be done later, it has to be done here
244 // since some inset might going to try to access
245 // the buffer() member.
246 it->setBuffer(const_cast<Buffer &>(buffer));
247 switch (it->lyxCode()) {
249 case MATH_HULL_CODE: {
250 // check for equation labels and resolve duplicates
251 InsetMathHull * ins = it->asInsetMath()->asHullInset();
252 std::vector<InsetLabel *> labels = ins->getLabels();
253 for (size_t i = 0; i != labels.size(); ++i) {
256 InsetLabel * lab = labels[i];
257 docstring const oldname = lab->getParam("name");
258 lab->updateLabel(oldname);
259 // We need to update the buffer reference cache.
261 docstring const newname = lab->getParam("name");
262 if (oldname == newname)
264 // adapt the references
265 for (InsetIterator itt = inset_iterator_begin(in);
266 itt != i_end; ++itt) {
267 if (itt->lyxCode() == REF_CODE) {
268 InsetCommand * ref = itt->asInsetCommand();
269 if (ref->getParam("reference") == oldname)
270 ref->setParam("reference", newname);
271 } else if (itt->lyxCode() == MATH_REF_CODE) {
272 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
273 // this is necessary to prevent an uninitialized
274 // buffer when the RefInset is in a MathBox.
275 // FIXME audit setBuffer calls
276 mi->setBuffer(const_cast<Buffer &>(buffer));
277 if (mi->getTarget() == oldname)
278 mi->changeTarget(newname);
286 // check for duplicates
287 InsetLabel & lab = static_cast<InsetLabel &>(*it);
288 docstring const oldname = lab.getParam("name");
289 lab.updateLabel(oldname);
290 // We need to update the buffer reference cache.
292 docstring const newname = lab.getParam("name");
293 if (oldname == newname)
295 // adapt the references
296 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
297 if (itt->lyxCode() == REF_CODE) {
298 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
299 if (ref.getParam("reference") == oldname)
300 ref.setParam("reference", newname);
301 } else if (itt->lyxCode() == MATH_REF_CODE) {
302 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
303 // this is necessary to prevent an uninitialized
304 // buffer when the RefInset is in a MathBox.
305 // FIXME audit setBuffer calls
306 mi->setBuffer(const_cast<Buffer &>(buffer));
307 if (mi->getTarget() == oldname)
308 mi->changeTarget(newname);
315 InsetInclude & inc = static_cast<InsetInclude &>(*it);
317 // We need to update the list of included files.
323 // check for duplicates
324 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
325 docstring const oldkey = bib.getParam("key");
326 bib.updateCommand(oldkey, false);
327 // We need to update the buffer reference cache.
329 docstring const newkey = bib.getParam("key");
330 if (oldkey == newkey)
332 // adapt the references
333 for (InsetIterator itt = inset_iterator_begin(in);
334 itt != i_end; ++itt) {
335 if (itt->lyxCode() == CITE_CODE) {
336 InsetCommand * ref = itt->asInsetCommand();
337 if (ref->getParam("key") == oldkey)
338 ref->setParam("key", newkey);
345 // check if branch is known to target buffer
347 InsetBranch & br = static_cast<InsetBranch &>(*it);
348 docstring const name = br.branch();
351 bool const is_child = (&buffer != buffer.masterBuffer());
352 BranchList branchlist = buffer.params().branchlist();
353 if ((!is_child && branchlist.find(name))
354 || (is_child && (branchlist.find(name)
355 || buffer.masterBuffer()->params().branchlist().find(name))))
358 // This is for a temporary buffer, so simply create the branch.
359 // Must not use lyx::dispatch(), since tmpbuffer has no view.
361 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
363 docstring text = bformat(
364 _("The pasted branch \"%1$s\" is undefined.\n"
365 "Do you want to add it to the document's branch list?"),
367 if (frontend::Alert::prompt(_("Unknown branch"),
368 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
370 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
372 // We need to update the list of branches.
381 insertion.swap(in.paragraphs());
383 // Split the paragraph for inserting the buf if necessary.
385 breakParagraphConservative(buffer.params(), pars, pit, pos);
389 pars.insert(boost::next(pars.begin(), pit),
393 // merge the empty par with the last par of the insertion
394 mergeParagraph(buffer.params(), pars,
395 pit + insertion.size() - 1);
397 pars.insert(boost::next(pars.begin(), pit + 1),
401 // merge the first par of the insertion with the current par
402 mergeParagraph(buffer.params(), pars, pit);
405 // Store the new cursor position.
406 pit_type last_paste = pit + insertion.size() - 1;
407 pit_type startpit = pit;
409 pos = pars[last_paste].size();
411 // FIXME Should we do it here, or should we let updateBuffer() do it?
412 // Set paragraph buffers. It's important to do this right away
413 // before something calls Inset::buffer() and causes a crash.
414 for (pit_type p = startpit; p <= pit; ++p)
415 pars[p].setBuffer(const_cast<Buffer &>(buffer));
417 // Join (conditionally) last pasted paragraph with next one, i.e.,
418 // the tail of the spliced document paragraph
419 if (!empty && last_paste + 1 != pit_type(pars.size())) {
420 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
421 mergeParagraph(buffer.params(), pars, last_paste);
422 } else if (pars[last_paste + 1].empty()) {
423 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
424 mergeParagraph(buffer.params(), pars, last_paste);
425 } else if (pars[last_paste].empty()) {
426 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
427 mergeParagraph(buffer.params(), pars, last_paste);
429 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
434 return PasteReturnValue(pit, pos, need_update);
438 PitPosPair eraseSelectionHelper(BufferParams const & params,
439 ParagraphList & pars,
440 pit_type startpit, pit_type endpit,
441 int startpos, int endpos)
443 // Start of selection is really invalid.
444 if (startpit == pit_type(pars.size()) ||
445 (startpos > pars[startpit].size()))
446 return PitPosPair(endpit, endpos);
448 // Start and end is inside same paragraph
449 if (endpit == pit_type(pars.size()) || startpit == endpit) {
450 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
451 return PitPosPair(endpit, endpos);
454 for (pit_type pit = startpit; pit != endpit + 1;) {
455 pos_type const left = (pit == startpit ? startpos : 0);
456 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
457 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
459 // Logically erase only, including the end-of-paragraph character
460 pars[pit].eraseChars(left, right, params.track_changes);
462 // Separate handling of paragraph break:
463 if (merge && pit != endpit &&
465 || pars[pit].hasSameLayout(pars[endpit])
466 || pars[endpit].size() == endpos)) {
467 if (pit + 1 == endpit)
468 endpos += pars[pit].size();
469 mergeParagraph(params, pars, pit);
475 // Ensure legal cursor pos:
478 return PitPosPair(endpit, endpos);
482 void putClipboard(ParagraphList const & paragraphs,
483 DocumentClassConstPtr docclass, docstring const & plaintext)
485 // This used to need to be static to avoid a memory leak. It no longer needs
486 // to be so, but the alternative is to construct a new one of these (with a
487 // new temporary directory, etc) every time, and then to destroy it. So maybe
488 // it's worth just keeping this one around.
490 static TempFile tempfile("clipboard.internal");
491 tempfile.setAutoRemove(false);
492 static Buffer * staticbuffer = theBufferList().newInternalBuffer(
493 tempfile.name().absFileName());
495 // These two things only really need doing the first time.
496 staticbuffer->setUnnamed(true);
497 staticbuffer->inset().setBuffer(*staticbuffer);
499 // Use a clone for the complicated stuff so that we do not need to clean
500 // up in order to avoid a crash.
501 Buffer * buffer = staticbuffer->cloneBufferOnly();
502 LASSERT(buffer, return);
504 // This needs doing every time.
505 buffer->params().setDocumentClass(docclass);
507 // we will use pasteSelectionHelper to copy the paragraphs into the
508 // temporary Buffer, since it does a lot of things to fix them up.
509 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
511 pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
513 // We don't want to produce images that are not used. Therefore,
514 // output formulas as MathML. Even if this is not understood by all
515 // applications, the number that can parse it should go up in the future.
516 buffer->params().html_math_output = BufferParams::MathML;
518 // Make sure MarkAsExporting is deleted before buffer is
520 // The Buffer is being used to export. This is necessary so that the
521 // updateMacros call will record the needed information.
522 MarkAsExporting mex(buffer);
524 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
525 buffer->updateMacros();
526 buffer->updateMacroInstances(OutputUpdate);
531 if (buffer->write(oslyx))
535 odocstringstream oshtml;
536 OutputParams runparams(encodings.fromLyXName("utf8"));
537 // We do not need to produce images, etc.
538 runparams.dryrun = true;
539 // We are not interested in errors (bug 8866)
540 runparams.silent = true;
541 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
543 theClipboard().put(lyx, oshtml.str(), plaintext);
551 /// return true if the whole ParagraphList is deleted
552 static bool isFullyDeleted(ParagraphList const & pars)
554 pit_type const pars_size = static_cast<pit_type>(pars.size());
556 // check all paragraphs
557 for (pit_type pit = 0; pit < pars_size; ++pit) {
558 if (!pars[pit].empty()) // prevent assertion failure
559 if (!pars[pit].isDeleted(0, pars[pit].size()))
566 void copySelectionHelper(Buffer const & buf, Text const & text,
567 pit_type startpit, pit_type endpit,
568 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
570 ParagraphList const & pars = text.paragraphs();
572 // In most of these cases, we can try to recover.
573 LASSERT(0 <= start, start = 0);
574 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
575 LASSERT(0 <= end, end = 0);
576 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
577 LASSERT(startpit != endpit || start <= end, return);
579 // Clone the paragraphs within the selection.
580 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
581 boost::next(pars.begin(), endpit + 1));
583 // Remove the end of the last paragraph; afterwards, remove the
584 // beginning of the first paragraph. Keep this order - there may only
585 // be one paragraph! Do not track deletions here; this is an internal
586 // action not visible to the user
588 Paragraph & back = copy_pars.back();
589 back.eraseChars(end, back.size(), false);
590 Paragraph & front = copy_pars.front();
591 front.eraseChars(0, start, false);
593 ParagraphList::iterator it = copy_pars.begin();
594 ParagraphList::iterator it_end = copy_pars.end();
596 for (; it != it_end; ++it) {
597 // Since we have a copy of the paragraphs, the insets
598 // do not have a proper buffer reference. It makes
599 // sense to add them temporarily, because the
600 // operations below depend on that (acceptChanges included).
601 it->setBuffer(const_cast<Buffer &>(buf));
602 // PassThru paragraphs have the Language
603 // latex_language. This is invalid for others, so we
604 // need to change it to the buffer language.
605 if (it->isPassThru())
606 it->changeLanguage(buf.params(),
607 latex_language, buf.language());
610 // do not copy text (also nested in insets) which is marked as
611 // deleted, unless the whole selection was deleted
612 if (!isFullyDeleted(copy_pars))
613 acceptChanges(copy_pars, buf.params());
615 rejectChanges(copy_pars, buf.params());
618 // do some final cleanup now, to make sure that the paragraphs
619 // are not linked to something else.
620 it = copy_pars.begin();
621 for (; it != it_end; ++it) {
622 it->setBuffer(*static_cast<Buffer *>(0));
623 it->setInsetOwner(0);
626 cutstack.push(make_pair(copy_pars, dc));
636 void region(CursorSlice const & i1, CursorSlice const & i2,
637 Inset::row_type & r1, Inset::row_type & r2,
638 Inset::col_type & c1, Inset::col_type & c2)
640 Inset & p = i1.inset();
641 c1 = p.col(i1.idx());
642 c2 = p.col(i2.idx());
645 r1 = p.row(i1.idx());
646 r2 = p.row(i2.idx());
652 docstring grabAndEraseSelection(Cursor & cur)
654 if (!cur.selection())
656 docstring res = grabSelection(cur);
662 bool reduceSelectionToOneCell(Cursor & cur)
664 if (!cur.selection() || !cur.inMathed())
667 CursorSlice i1 = cur.selBegin();
668 CursorSlice i2 = cur.selEnd();
669 if (!i1.inset().asInsetMath())
672 // the easy case: do nothing if only one cell is selected
673 if (i1.idx() == i2.idx())
678 cur.top().pos() = cur.top().lastpos();
684 bool multipleCellsSelected(Cursor const & cur)
686 if (!cur.selection() || !cur.inMathed())
689 CursorSlice i1 = cur.selBegin();
690 CursorSlice i2 = cur.selEnd();
691 if (!i1.inset().asInsetMath())
694 if (i1.idx() == i2.idx())
701 void switchBetweenClasses(DocumentClassConstPtr oldone,
702 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
706 LBUFERR(!in.paragraphs().empty());
707 if (oldone == newone)
710 DocumentClass const & oldtc = *oldone;
711 DocumentClass const & newtc = *newone;
714 ParIterator it = par_iterator_begin(in);
715 ParIterator end = par_iterator_end(in);
716 // for remembering which layouts we've had to add
717 set<docstring> newlayouts;
718 for (; it != end; ++it) {
719 docstring const name = it->layout().name();
721 // the pasted text will keep their own layout name. If this layout does
722 // not exist in the new document, it will behave like a standard layout.
723 bool const added_one = newtc.addLayoutIfNeeded(name);
725 newlayouts.insert(name);
727 if (added_one || newlayouts.find(name) != newlayouts.end()) {
729 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
731 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
734 if (in.usePlainLayout())
735 it->setLayout(newtc.plainLayout());
737 it->setLayout(newtc[name]);
740 // character styles and hidden table cells
741 InsetIterator const i_end = inset_iterator_end(in);
742 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
743 InsetCode const code = it->lyxCode();
744 if (code == FLEX_CODE) {
745 // FIXME: Should we verify all InsetCollapsable?
746 docstring const layoutName = it->layoutName();
747 docstring const & n = newone->insetLayout(layoutName).name();
748 bool const is_undefined = n.empty() ||
749 n == DocumentClass::plainInsetLayout().name();
753 // The flex inset is undefined in newtc
754 docstring const oldname = from_utf8(oldtc.name());
755 docstring const newname = from_utf8(newtc.name());
757 if (oldname == newname)
758 s = bformat(_("Flex inset %1$s is undefined after "
759 "reloading `%2$s' layout."), layoutName, oldname);
761 s = bformat(_("Flex inset %1$s is undefined because of "
762 "conversion from `%2$s' layout to `%3$s'."),
763 layoutName, oldname, newname);
764 // To warn the user that something had to be done.
765 errorlist.push_back(ErrorItem(
766 _("Undefined flex inset"),
767 s, it.paragraph().id(), it.pos(), it.pos() + 1));
768 } else if (code == TABULAR_CODE) {
769 // The recursion above does not catch paragraphs in "hidden" cells,
770 // i.e., ones that are part of a multirow or multicolum. So we need
771 // to handle those separately.
772 // This is the cause of bug #9049.
773 InsetTabular * table = it->asInsetTabular();
774 table->setLayoutForHiddenCells(newtc);
780 vector<docstring> availableSelections(Buffer const * buf)
782 vector<docstring> selList;
786 CutStack::const_iterator cit = theCuts.begin();
787 CutStack::const_iterator end = theCuts.end();
788 for (; cit != end; ++cit) {
789 // we do not use cit-> here because gcc 2.9x does not
791 ParagraphList const & pars = (*cit).first;
793 ParagraphList::const_iterator pit = pars.begin();
794 ParagraphList::const_iterator pend = pars.end();
795 for (; pit != pend; ++pit) {
796 Paragraph par(*pit, 0, 26);
797 // adapt paragraph to current buffer.
798 par.setBuffer(const_cast<Buffer &>(*buf));
799 asciiSel += par.asString(AS_STR_INSETS);
800 if (asciiSel.size() > 25) {
801 asciiSel.replace(22, docstring::npos,
807 selList.push_back(asciiSel);
814 size_type numberOfSelections()
816 return theCuts.size();
820 void cutSelection(Cursor & cur, bool doclear, bool realcut)
822 // This doesn't make sense, if there is no selection
823 if (!cur.selection())
826 // OK, we have a selection. This is always between cur.selBegin()
829 if (cur.inTexted()) {
830 Text * text = cur.text();
835 // make sure that the depth behind the selection are restored, too
836 cur.recordUndoSelection();
837 pit_type begpit = cur.selBegin().pit();
838 pit_type endpit = cur.selEnd().pit();
840 int endpos = cur.selEnd().pos();
842 BufferParams const & bp = cur.buffer()->params();
844 copySelectionHelper(*cur.buffer(),
847 cur.selBegin().pos(), endpos,
848 bp.documentClassPtr(), theCuts);
849 // Stuff what we got on the clipboard.
850 // Even if there is no selection.
851 putClipboard(theCuts[0].first, theCuts[0].second,
852 cur.selectionAsString(true));
855 if (begpit != endpit)
856 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
858 boost::tie(endpit, endpos) =
859 eraseSelectionHelper(bp,
862 cur.selBegin().pos(), endpos);
864 // cutSelection can invalidate the cursor so we need to set
866 // we prefer the end for when tracking changes
870 // sometimes necessary
872 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
875 // need a valid cursor. (Lgb)
876 cur.clearSelection();
878 // After a cut operation, we must make sure that the Buffer is updated
879 // because some further operation might need updated label information for
880 // example. So we cannot just use "cur.forceBufferUpdate()" here.
882 cur.buffer()->updateBuffer();
884 // tell tabular that a recent copy happened
885 dirtyTabularStack(false);
888 if (cur.inMathed()) {
889 if (cur.selBegin().idx() != cur.selEnd().idx()) {
890 // The current selection spans more than one cell.
892 cur.recordUndoInset();
894 // Record only the current cell to avoid a jumping
905 void copySelection(Cursor const & cur)
907 copySelection(cur, cur.selectionAsString(true));
911 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
915 BufferParams const & bp = cur.buffer()->params();
916 par.setLayout(bp.documentClass().plainLayout());
917 Font font(inherit_font, bp.language);
918 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
920 theCuts.push(make_pair(pars, bp.documentClassPtr()));
922 // stuff the selection onto the X clipboard, from an explicit copy request
923 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
929 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
931 // this doesn't make sense, if there is no selection
932 if (!cur.selection())
935 // copySelection can not yet handle the case of cross idx selection
936 if (cur.selBegin().idx() != cur.selEnd().idx())
939 if (cur.inTexted()) {
940 Text * text = cur.text();
942 // ok we have a selection. This is always between cur.selBegin()
943 // and sel_end cursor
945 // copy behind a space if there is one
946 ParagraphList & pars = text->paragraphs();
947 pos_type pos = cur.selBegin().pos();
948 pit_type par = cur.selBegin().pit();
949 while (pos < pars[par].size() &&
950 pars[par].isLineSeparator(pos) &&
951 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
954 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
955 pos, cur.selEnd().pos(),
956 cur.buffer()->params().documentClassPtr(), cutstack);
958 // Reset the dirty_tabular_stack_ flag only when something
959 // is copied to the clipboard (not to the selectionBuffer).
960 if (&cutstack == &theCuts)
961 dirtyTabularStack(false);
964 if (cur.inMathed()) {
965 //lyxerr << "copySelection in mathed" << endl;
968 BufferParams const & bp = cur.buffer()->params();
969 // FIXME This should be the plain layout...right?
970 par.setLayout(bp.documentClass().plainLayout());
971 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
973 cutstack.push(make_pair(pars, bp.documentClassPtr()));
980 void copySelectionToStack()
982 if (!selectionBuffer.empty())
983 theCuts.push(selectionBuffer[0]);
987 void copySelection(Cursor const & cur, docstring const & plaintext)
989 // In tablemode, because copy and paste actually use special table stack
990 // we do not attempt to get selected paragraphs under cursor. Instead, a
991 // paragraph with the plain text version is generated so that table cells
992 // can be pasted as pure text somewhere else.
993 if (cur.selBegin().idx() != cur.selEnd().idx()) {
996 BufferParams const & bp = cur.buffer()->params();
997 par.setLayout(bp.documentClass().plainLayout());
998 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1000 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1002 copySelectionToStack(cur, theCuts);
1005 // stuff the selection onto the X clipboard, from an explicit copy request
1006 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1010 void saveSelection(Cursor const & cur)
1012 // This function is called, not when a selection is formed, but when
1013 // a selection is cleared. Therefore, multiple keyboard selection
1014 // will not repeatively trigger this function (bug 3877).
1016 && cur.selBegin() == cur.bv().cursor().selBegin()
1017 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1018 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1019 copySelectionToStack(cur, selectionBuffer);
1026 return !selectionBuffer.empty();
1030 void clearSelection()
1032 selectionBuffer.clear();
1036 void clearCutStack()
1042 docstring selection(size_t sel_index)
1044 return sel_index < theCuts.size()
1045 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1050 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1051 DocumentClassConstPtr docclass, ErrorList & errorList)
1053 if (cur.inTexted()) {
1054 Text * text = cur.text();
1057 PasteReturnValue prv =
1058 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1059 cur.forceBufferUpdate();
1060 cur.clearSelection();
1061 text->setCursor(cur, prv.par, prv.pos);
1064 // mathed is handled in InsetMathNest/InsetMathGrid
1065 LATTEST(!cur.inMathed());
1069 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1071 // this does not make sense, if there is nothing to paste
1072 if (!checkPastePossible(sel_index))
1076 pasteParagraphList(cur, theCuts[sel_index].first,
1077 theCuts[sel_index].second, errorList);
1082 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1083 Clipboard::TextType type)
1085 // Use internal clipboard if it is the most recent one
1086 // This overrides asParagraphs and type on purpose!
1087 if (theClipboard().isInternal())
1088 return pasteFromStack(cur, errorList, 0);
1090 // First try LyX format
1091 if ((type == Clipboard::LyXTextType ||
1092 type == Clipboard::LyXOrPlainTextType ||
1093 type == Clipboard::AnyTextType) &&
1094 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1095 string lyx = theClipboard().getAsLyX();
1097 // For some strange reason gcc 3.2 and 3.3 do not accept
1098 // Buffer buffer(string(), false);
1099 Buffer buffer("", false);
1100 buffer.setUnnamed(true);
1101 if (buffer.readString(lyx)) {
1103 pasteParagraphList(cur, buffer.paragraphs(),
1104 buffer.params().documentClassPtr(), errorList);
1110 // Then try TeX and HTML
1111 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1112 string names[2] = {"html", "latexclipboard"};
1113 for (int i = 0; i < 2; ++i) {
1114 if (type != types[i] && type != Clipboard::AnyTextType)
1116 bool available = theClipboard().hasTextContents(types[i]);
1118 // If a specific type was explicitly requested, try to
1119 // interpret plain text: The user told us that the clipboard
1120 // contents is in the desired format
1121 if (!available && type == types[i]) {
1122 types[i] = Clipboard::PlainTextType;
1123 available = theClipboard().hasTextContents(types[i]);
1127 docstring text = theClipboard().getAsText(types[i]);
1128 available = !text.empty();
1130 // For some strange reason gcc 3.2 and 3.3 do not accept
1131 // Buffer buffer(string(), false);
1132 Buffer buffer("", false);
1133 buffer.setUnnamed(true);
1134 available = buffer.importString(names[i], text, errorList);
1136 available = !buffer.paragraphs().empty();
1137 if (available && !buffer.paragraphs()[0].empty()) {
1139 pasteParagraphList(cur, buffer.paragraphs(),
1140 buffer.params().documentClassPtr(), errorList);
1147 // Then try plain text
1148 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1153 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1155 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1160 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1163 // Use internal clipboard if it is the most recent one
1164 if (theClipboard().isInternal()) {
1165 if (!checkPastePossible(0))
1168 ParagraphList const & pars = theCuts[0].first;
1169 ParagraphList::const_iterator it = pars.begin();
1170 for (; it != pars.end(); ++it) {
1171 if (it != pars.begin())
1173 text += (*it).asString();
1175 asParagraphs = false;
1177 // Then try plain text
1178 text = theClipboard().getAsText(Clipboard::PlainTextType);
1185 cutSelection(cur, true, false);
1187 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1189 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1193 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1194 Clipboard::GraphicsType preferedType)
1196 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1198 // get picture from clipboard
1199 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1200 if (filename.empty())
1203 // create inset for graphic
1204 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1205 InsetGraphicsParams params;
1206 params.filename = support::DocFileName(filename.absFileName(), false);
1207 inset->setParams(params);
1213 void pasteSelection(Cursor & cur, ErrorList & errorList)
1215 if (selectionBuffer.empty())
1218 pasteParagraphList(cur, selectionBuffer[0].first,
1219 selectionBuffer[0].second, errorList);
1223 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1226 DocIterator selbeg = cur.selectionBegin();
1228 // Get font setting before we cut, we need a copy here, not a bare reference.
1230 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1232 // Insert the new string
1233 pos_type pos = cur.selEnd().pos();
1234 Paragraph & par = cur.selEnd().paragraph();
1235 docstring::const_iterator cit = str.begin();
1236 docstring::const_iterator end = str.end();
1237 for (; cit != end; ++cit, ++pos)
1238 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1240 // Cut the selection
1241 cutSelection(cur, true, false);
1245 void replaceSelection(Cursor & cur)
1247 if (cur.selection())
1248 cutSelection(cur, true, false);
1252 void eraseSelection(Cursor & cur)
1254 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1255 CursorSlice const & i1 = cur.selBegin();
1256 CursorSlice const & i2 = cur.selEnd();
1257 if (!i1.asInsetMath()) {
1258 LYXERR0("Can't erase this selection");
1264 InsetMath * p = i1.asInsetMath();
1265 if (i1.idx() == i2.idx()) {
1266 i1.cell().erase(i1.pos(), i2.pos());
1267 // We may have deleted i1.cell(cur.pos()).
1268 // Make sure that pos is valid.
1269 if (cur.pos() > cur.lastpos())
1270 cur.pos() = cur.lastpos();
1271 } else if (p->nrows() > 0 && p->ncols() > 0) {
1272 // This is a grid, delete a nice square region
1273 Inset::row_type r1, r2;
1274 Inset::col_type c1, c2;
1275 region(i1, i2, r1, r2, c1, c2);
1276 for (Inset::row_type row = r1; row <= r2; ++row)
1277 for (Inset::col_type col = c1; col <= c2; ++col)
1278 p->cell(p->index(row, col)).clear();
1279 // We've deleted the whole cell. Only pos 0 is valid.
1282 Inset::idx_type idx1 = i1.idx();
1283 Inset::idx_type idx2 = i2.idx();
1286 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1287 p->cell(idx).clear();
1288 // We've deleted the whole cell. Only pos 0 is valid.
1292 // need a valid cursor. (Lgb)
1293 cur.clearSelection();
1294 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1298 void selDel(Cursor & cur)
1300 //lyxerr << "cap::selDel" << endl;
1301 if (cur.selection())
1302 eraseSelection(cur);
1306 void selClearOrDel(Cursor & cur)
1308 //lyxerr << "cap::selClearOrDel" << endl;
1309 if (lyxrc.auto_region_delete)
1312 cur.setSelection(false);
1316 docstring grabSelection(Cursor const & cur)
1318 if (!cur.selection())
1322 // grab selection by glueing multiple cells together. This is not what
1323 // we want because selections spanning multiple cells will get "&" and "\\"
1326 for (DocIterator dit = cur.selectionBegin();
1327 dit != cur.selectionEnd(); dit.forwardPos())
1328 os << asString(dit.cell());
1332 CursorSlice i1 = cur.selBegin();
1333 CursorSlice i2 = cur.selEnd();
1335 if (i1.idx() == i2.idx()) {
1336 if (i1.inset().asInsetMath()) {
1337 MathData::const_iterator it = i1.cell().begin();
1338 Buffer * buf = cur.buffer();
1339 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1341 return from_ascii("unknown selection 1");
1345 Inset::row_type r1, r2;
1346 Inset::col_type c1, c2;
1347 region(i1, i2, r1, r2, c1, c2);
1350 if (i1.inset().asInsetMath()) {
1351 for (Inset::row_type row = r1; row <= r2; ++row) {
1354 for (Inset::col_type col = c1; col <= c2; ++col) {
1357 data += asString(i1.asInsetMath()->
1358 cell(i1.asInsetMath()->index(row, col)));
1362 data = from_ascii("unknown selection 2");
1368 void dirtyTabularStack(bool b)
1370 dirty_tabular_stack_ = b;
1374 bool tabularStackDirty()
1376 return dirty_tabular_stack_;