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