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