]> git.lyx.org Git - lyx.git/blob - src/BufferView2.C
Missed some.
[lyx.git] / src / BufferView2.C
1 /* This file is part of
2  * ======================================================
3  *
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  * ====================================================== */
10
11 #include <config.h>
12
13 #include "BufferView.h"
14 #include "buffer.h"
15 #include "lyxcursor.h"
16 #include "lyxtext.h"
17 #include "frontends/LyXView.h"
18 #include "bufferlist.h"
19 #include "frontends/screen.h"
20 #include "LaTeX.h"
21 #include "BufferView_pimpl.h"
22 #include "language.h"
23 #include "gettext.h"
24 #include "undo_funcs.h"
25 #include "debug.h"
26 #include "iterators.h"
27 #include "lyxlex.h"
28
29 #include "frontends/Alert.h"
30 #include "frontends/Dialogs.h"
31
32 #include "insets/insetcommand.h" //ChangeRefs
33 #include "insets/inseterror.h"
34
35 #include "support/FileInfo.h"
36 #include "support/filetools.h"
37 #include "support/lyxfunctional.h" //equal_1st_in_pair
38 #include "support/types.h"
39 #include "support/lyxalgo.h" // lyx_count
40
41 #include <fstream>
42
43 extern BufferList bufferlist;
44
45 using lyx::pos_type;
46
47 using std::pair;
48 using std::endl;
49 using std::ifstream;
50 using std::vector;
51 using std::find;
52 using std::count_if;
53
54
55 // Inserts a file into current document
56 bool BufferView::insertLyXFile(string const & filen)
57         //
58         // Copyright CHT Software Service GmbH
59         // Uwe C. Schroeder
60         //
61         // Insert a LyXformat - file into current buffer
62         //
63         // Moved from lyx_cb.C (Lgb)
64 {
65         if (filen.empty()) return false;
66
67         string const fname = MakeAbsPath(filen);
68
69         // check if file exist
70         FileInfo const fi(fname);
71
72         if (!fi.readable()) {
73                 Alert::alert(_("Error!"),
74                            _("Specified file is unreadable: "),
75                            MakeDisplayPath(fname, 50));
76                 return false;
77         }
78
79         beforeChange(text);
80
81         ifstream ifs(fname.c_str());
82         if (!ifs) {
83                 Alert::alert(_("Error!"),
84                            _("Cannot open specified file: "),
85                            MakeDisplayPath(fname, 50));
86                 return false;
87         }
88
89         int const c = ifs.peek();
90
91         LyXLex lex(0, 0);
92         lex.setStream(ifs);
93
94         bool res = true;
95
96         if (c == '#') {
97                 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
98                 res = buffer()->readFile(lex, text->cursor.par());
99         } else {
100                 lyxerr[Debug::INFO] << "Will insert file without header"
101                                     << endl;
102                 res = buffer()->readLyXformat2(lex, text->cursor.par());
103         }
104
105         resize();
106         return res;
107 }
108
109
110 bool BufferView::removeAutoInsets()
111 {
112         // keep track of which pos and par the cursor was on
113         Paragraph * cursor_par = text->cursor.par();
114         Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
115         Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
116         pos_type cursor_pos = text->cursor.pos();
117
118         bool found = false;
119
120         // Trap the deletion of the paragraph the cursor is in.
121         // Iterate until we find a paragraph that won't be immediately deleted.
122         // In reality this should mean we only execute the body of the while
123         // loop once at most.  However for safety we iterate rather than just
124         // make this an if () conditional.
125         while ((cursor_par_prev || cursor_par_next)
126                && text->setCursor(this,
127                                   cursor_par_prev ? cursor_par_prev : cursor_par_next,
128                                   0)) {
129                 // We just removed cursor_par so have to fix the "cursor"
130                 if (cursor_par_prev) {
131                         // '.' = cursor_par
132                         //  a -> a.
133                         // .
134                         cursor_par = cursor_par_prev;
135                         cursor_pos = cursor_par->size();
136                 } else {
137                         // .  -> .a
138                         //  a
139                         cursor_par = cursor_par_next;
140                         cursor_pos = 0;
141                 }
142                 cursor_par_prev = cursor_par->previous();
143                 cursor_par_next = cursor_par->next();
144         }
145
146         // Iterate through the paragraphs removing autoDelete insets as we go.
147         // If the paragraph ends up empty after all the autoDelete insets are
148         // removed that paragraph will be removed by the next setCursor() call.
149         ParIterator it = buffer()->par_iterator_begin();
150         ParIterator end = buffer()->par_iterator_end();
151         for (; it != end; ++it) {
152                 Paragraph * par = *it;
153                 Paragraph * par_prev = par ? par->previous() : 0;
154                 bool removed = false;
155
156                 if (text->setCursor(this, par, 0)
157                     && cursor_par == par_prev) {
158                         // The previous setCursor line was deleted and that
159                         // was the cursor_par line.  This can only happen if an
160                         // error box was the sole item on cursor_par.
161                         // It is possible for cursor_par_prev to be stray if
162                         // the line it pointed to only had a error box on it
163                         // so we have to set it to a known correct value.
164                         // This is often the same value it already had.
165                         cursor_par_prev = par->previous();
166                         if (cursor_par_prev) {
167                                 // '|' = par, '.' = cursor_par, 'E' = error box
168                                 // First step below may occur before while{}
169                                 //  a    |a      a     a     a.
170                                 //  E -> .E -> |.E -> .  -> |b
171                                 // .      b      b    |b
172                                 //  b
173                                 cursor_par = cursor_par_prev;
174                                 cursor_pos = cursor_par_prev->size();
175                                 cursor_par_prev = cursor_par->previous();
176                                 // cursor_par_next remains the same
177                         } else if (cursor_par_next) {
178                                 // First step below may occur before while{}
179                                 // .
180                                 //  E -> |.E -> |.  -> . -> .|a
181                                 //  a      a      a    |a
182                                 cursor_par = cursor_par_next;
183                                 cursor_pos = 0;
184                                 // cursor_par_prev remains unset
185                                 cursor_par_next = cursor_par->next();
186                         } else {
187                                 // I can't find a way to trigger this
188                                 // so it should be unreachable code
189                                 // unless the buffer is corrupted.
190                                 lyxerr << "BufferView::removeAutoInsets() is bad\n";
191                         }
192                 }
193
194                 Paragraph::inset_iterator pit = par->inset_iterator_begin();
195                 Paragraph::inset_iterator pend = par->inset_iterator_end();
196                 while (pit != pend) {
197                         if (pit->autoDelete()) {
198                                 removed = true;
199                                 pos_type const pos = pit.getPos();
200
201                                 par->erase(pos);
202                                 // We just invalidated par's inset iterators so
203                                 // we get the next valid iterator position
204                                 pit = par->InsetIterator(pos);
205                                 // and ensure we have a valid end iterator.
206                                 pend = par->inset_iterator_end();
207
208                                 if (cursor_par == par) {
209                                         // update the saved cursor position
210                                         if (cursor_pos > pos)
211                                                 --cursor_pos;
212                                 }
213                         } else {
214                                 ++pit;
215                         }
216                 }
217                 if (removed) {
218                         found = true;
219                         text->redoParagraph(this);
220                 }
221         }
222
223         // It is possible that the last line is empty if it was cursor_par
224         // and/or only had an error inset on it.  So we set the cursor to the
225         // start of the doc to force its removal and ensure a valid saved cursor
226         if (text->setCursor(this, text->ownerParagraph(), 0)
227             && 0 == cursor_par_next) {
228                 cursor_par = cursor_par_prev;
229                 cursor_pos = cursor_par->size();
230         } else if (cursor_pos > cursor_par->size()) {
231                 // Some C-Enter lines were removed by the setCursor call which
232                 // then invalidated cursor_pos. It could still be "wrong" because
233                 // the cursor may appear to have jumped but since we collapsed
234                 // some C-Enter lines this should be a reasonable compromise.
235                 cursor_pos = cursor_par->size();
236         }
237
238         // restore the original cursor in its corrected location.
239         text->setCursorIntern(this, cursor_par, cursor_pos);
240
241         return found;
242 }
243
244
245 void BufferView::insertErrors(TeXErrors & terr)
246 {
247         // Save the cursor position
248         LyXCursor cursor = text->cursor;
249
250         TeXErrors::Errors::const_iterator cit = terr.begin();
251         TeXErrors::Errors::const_iterator end = terr.end();
252         for (; cit != end; ++cit) {
253                 string const desctext(cit->error_desc);
254                 string const errortext(cit->error_text);
255                 string const msgtxt = desctext + '\n' + errortext;
256                 int const errorrow = cit->error_in_line;
257
258                 // Insert error string for row number
259                 int tmpid = -1;
260                 int tmppos = -1;
261
262                 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
263                         buffer()->texrow.increasePos(tmpid, tmppos);
264                 }
265
266                 Paragraph * texrowpar = 0;
267
268                 if (tmpid == -1) {
269                         texrowpar = text->ownerParagraph();
270                         tmppos = 0;
271                 } else {
272                         texrowpar = buffer()->getParFromID(tmpid);
273                 }
274
275                 if (texrowpar == 0)
276                         continue;
277
278                 InsetError * new_inset = new InsetError(msgtxt);
279                 text->setCursorIntern(this, texrowpar, tmppos);
280                 text->insertInset(this, new_inset);
281                 text->fullRebreak(this);
282         }
283         // Restore the cursor position
284         text->setCursorIntern(this, cursor.par(), cursor.pos());
285 }
286
287
288 void BufferView::setCursorFromRow(int row)
289 {
290         int tmpid = -1;
291         int tmppos = -1;
292
293         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
294
295         Paragraph * texrowpar;
296
297         if (tmpid == -1) {
298                 texrowpar = text->ownerParagraph();
299                 tmppos = 0;
300         } else {
301                 texrowpar = buffer()->getParFromID(tmpid);
302         }
303         text->setCursor(this, texrowpar, tmppos);
304 }
305
306
307 bool BufferView::insertInset(Inset * inset, string const & lout)
308 {
309         return pimpl_->insertInset(inset, lout);
310 }
311
312
313 /* This is also a buffer property (ale) */
314 // Not so sure about that. a goto Label function can not be buffer local, just
315 // think how this will work in a multiwindo/buffer environment, all the
316 // cursors in all the views showing this buffer will move. (Lgb)
317 // OK, then no cursor action should be allowed in buffer. (ale)
318 bool BufferView::gotoLabel(string const & label)
319
320 {
321         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
322              it != buffer()->inset_iterator_end(); ++it) {
323                 vector<string> labels = (*it)->getLabelList();
324                 if (find(labels.begin(),labels.end(),label)
325                      != labels.end()) {
326                         beforeChange(text);
327                         text->setCursor(this, it.getPar(), it.getPos());
328                         text->selection.cursor = text->cursor;
329                         update(text, BufferView::SELECT|BufferView::FITCUR);
330                         return true;
331                 }
332         }
333         return false;
334 }
335
336
337 void BufferView::menuUndo()
338 {
339         if (!available())
340                 return;
341  
342         owner()->message(_("Undo"));
343         hideCursor();
344         beforeChange(text);
345         update(text, BufferView::SELECT|BufferView::FITCUR);
346         if (!textUndo(this))
347                 owner()->message(_("No further undo information"));
348         else
349                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
350         switchKeyMap();
351 }
352
353
354 void BufferView::menuRedo()
355 {
356         if (!available())
357                 return;
358  
359         owner()->message(_("Redo"));
360         hideCursor();
361         beforeChange(text);
362         update(text, BufferView::SELECT|BufferView::FITCUR);
363         if (!textRedo(this))
364                 owner()->message(_("No further redo information"));
365         else
366                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
367         switchKeyMap();
368 }
369
370
371 void BufferView::copyEnvironment()
372 {
373         if (available()) {
374                 text->copyEnvironmentType();
375                 owner()->message(_("Paragraph environment type copied"));
376         }
377 }
378
379
380 void BufferView::pasteEnvironment()
381 {
382         if (available()) {
383                 text->pasteEnvironmentType(this);
384                 owner()->message(_("Paragraph environment type set"));
385                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
386         }
387 }
388
389
390 void BufferView::copy()
391 {
392         if (available()) {
393                 getLyXText()->copySelection(this);
394                 owner()->message(_("Copy"));
395         }
396 }
397
398
399 void BufferView::cut(bool realcut)
400 {
401         if (available()) {
402                 hideCursor();
403                 update(text, BufferView::SELECT|BufferView::FITCUR);
404                 text->cutSelection(this, true, realcut);
405                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
406                 owner()->message(_("Cut"));
407         }
408 }
409
410
411 void BufferView::paste()
412 {
413         if (!available())
414                 return;
415
416         owner()->message(_("Paste"));
417
418         hideCursor();
419         // clear the selection
420         toggleSelection();
421         text->clearSelection();
422         update(text, BufferView::SELECT|BufferView::FITCUR);
423
424         // paste
425         text->pasteSelection(this);
426         // bug 393
427         text->clearSelection();
428         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
429 // why fake a selection only I think it should be a real one and not only
430 // a painted one (Jug 20020318).
431 #if 0
432         // clear the selection
433         toggleSelection();
434         text->clearSelection();
435         update(text, BufferView::SELECT|BufferView::FITCUR);
436 #endif
437 }
438
439
440 /* these functions are for the spellchecker */
441 WordLangTuple const BufferView::nextWord(float & value)
442 {
443         if (!available()) {
444                 value = 1;
445                 return WordLangTuple();
446         }
447
448         return text->selectNextWordToSpellcheck(this, value);
449 }
450
451
452 void BufferView::selectLastWord()
453 {
454         if (!available()) return;
455
456         LyXCursor cur = text->selection.cursor;
457         hideCursor();
458         beforeChange(text);
459         text->selection.cursor = cur;
460         text->selectSelectedWord(this);
461         toggleSelection(false);
462         update(text, BufferView::SELECT|BufferView::FITCUR);
463 }
464
465
466 void BufferView::endOfSpellCheck()
467 {
468         if (!available()) return;
469
470         hideCursor();
471         beforeChange(text);
472         text->selectSelectedWord(this);
473         text->clearSelection();
474         update(text, BufferView::SELECT|BufferView::FITCUR);
475 }
476
477
478 void BufferView::replaceWord(string const & replacestring)
479 {
480         if (!available()) return;
481
482         LyXText * tt = getLyXText();
483         hideCursor();
484         update(tt, BufferView::SELECT|BufferView::FITCUR);
485
486         /* clear the selection (if there is any) */
487         toggleSelection(false);
488         update(tt, BufferView::SELECT|BufferView::FITCUR);
489
490         /* clear the selection (if there is any) */
491         toggleSelection(false);
492         tt->replaceSelectionWithString(this, replacestring);
493
494         tt->setSelectionOverString(this, replacestring);
495
496         // Go back so that replacement string is also spellchecked
497         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
498                 tt->cursorLeft(this);
499         }
500         update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
501 }
502 // End of spellchecker stuff
503
504
505 bool BufferView::lockInset(UpdatableInset * inset)
506 {
507         if (!inset)
508                 return false;
509         // don't relock if we're already locked
510         if (theLockingInset() == inset)
511                 return true;
512         if (!theLockingInset()) {
513                 // first check if it's the inset under the cursor we want lock
514                 // should be most of the time
515                 char const c = text->cursor.par()->getChar(text->cursor.pos());
516                 if (c == Paragraph::META_INSET) {
517                         Inset * in = text->cursor.par()->getInset(text->cursor.pos());
518                         if (inset == in) {
519                                 theLockingInset(inset);
520                                 return true;
521                         }
522                 }
523                 // Then do a deep look of the inset and lock the right one
524                 Paragraph * par = buffer()->paragraph;
525                 int const id = inset->id();
526                 while(par) {
527                         Paragraph::inset_iterator it =
528                                 par->inset_iterator_begin();
529                         Paragraph::inset_iterator const end =
530                                 par->inset_iterator_end();
531                         for (; it != end; ++it) {
532                                 if ((*it) == inset) {
533                                         text->setCursorIntern(this, par, it.getPos());
534                                         theLockingInset(inset);
535                                         return true;
536                                 }
537                                 if ((*it)->getInsetFromID(id)) {
538                                         text->setCursorIntern(this, par, it.getPos());
539                                         (*it)->edit(this);
540                                         return theLockingInset()->lockInsetInInset(this, inset);
541                                 }
542                         }
543                         par = par->next();
544                 }
545                 return false;
546         }
547         return theLockingInset()->lockInsetInInset(this, inset);
548 }
549
550
551 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
552 {
553         if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
554                 LyXCursor cursor = text->cursor;
555                 Inset * locking_inset = theLockingInset()->getLockingInset();
556
557                 if ((cursor.pos() - 1 >= 0) &&
558                     cursor.par()->isInset(cursor.pos() - 1) &&
559                     (cursor.par()->getInset(cursor.pos() - 1) ==
560                      locking_inset))
561                         text->setCursor(this, cursor,
562                                         cursor.par(), cursor.pos() - 1);
563                 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
564                 LyXText * txt = getLyXText();
565                 if (locking_inset->isTextInset() &&
566                     locking_inset->lyxCode() != Inset::ERT_CODE &&
567                     (txt->real_current_font.language() !=
568                      buffer()->params.language
569                      || txt->real_current_font.isVisibleRightToLeft()
570                      != buffer()->params.language->RightToLeft()))
571                         shape = (txt->real_current_font.isVisibleRightToLeft())
572                                 ? LyXScreen::REVERSED_L_SHAPE
573                                 : LyXScreen::L_SHAPE;
574                 y += cursor.iy() + theLockingInset()->insetInInsetY();
575                 screen().showManualCursor(text, x, y, asc, desc,
576                                                   shape);
577         }
578 }
579
580
581 void BufferView::hideLockedInsetCursor()
582 {
583         if (theLockingInset() && available()) {
584                 screen().hideCursor();
585         }
586 }
587
588
589 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
590 {
591         if (theLockingInset() && available()) {
592                 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
593                 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
594                         updateScrollbar();
595                         return true;
596                 }
597         }
598         return false;
599 }
600
601
602 int BufferView::unlockInset(UpdatableInset * inset)
603 {
604         if (!inset)
605                 return 0;
606         if (inset && theLockingInset() == inset) {
607                 inset->insetUnlock(this);
608                 theLockingInset(0);
609                 // make sure we update the combo !
610                 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
611                 // Tell the paragraph dialog that we changed paragraph
612                 owner()->getDialogs()->updateParagraph();
613                 finishUndo();
614                 return 0;
615         } else if (inset && theLockingInset() &&
616                    theLockingInset()->unlockInsetInInset(this, inset)) {
617                 // Tell the paragraph dialog that we changed paragraph
618                 owner()->getDialogs()->updateParagraph();
619                 // owner inset has updated the layout combo
620                 finishUndo();
621                 return 0;
622         }
623         return bufferlist.unlockInset(inset);
624 }
625
626
627 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
628 {
629         if (!theLockingInset())
630                 return; // shouldn't happen
631         if (kind == Undo::EDIT) // in this case insets would not be stored!
632                 kind = Undo::FINISH;
633         setUndo(this, kind,
634                 text->cursor.par(),
635                 text->cursor.par()->next());
636 }
637
638
639 void BufferView::updateInset(Inset * inset, bool mark_dirty)
640 {
641         pimpl_->updateInset(inset, mark_dirty);
642 }
643
644
645 bool BufferView::ChangeInsets(Inset::Code code,
646                               string const & from, string const & to)
647 {
648         bool need_update = false;
649         LyXCursor cursor = text->cursor;
650         LyXCursor tmpcursor = cursor;
651         cursor.par(tmpcursor.par());
652         cursor.pos(tmpcursor.pos());
653
654         ParIterator end = buffer()->par_iterator_end();
655         for (ParIterator it = buffer()->par_iterator_begin();
656              it != end; ++it) {
657                 Paragraph * par = *it;
658                 bool changed_inset = false;
659                 for (Paragraph::inset_iterator it2 = par->inset_iterator_begin();
660                      it2 != par->inset_iterator_end(); ++it2) {
661                         if ((*it2)->lyxCode() == code) {
662                                 InsetCommand * inset = static_cast<InsetCommand *>(*it2);
663                                 if (inset->getContents() == from) {
664                                         inset->setContents(to);
665                                         changed_inset = true;
666                                 }
667                         }
668                 }
669                 if (changed_inset) {
670                         need_update = true;
671
672                         // FIXME
673
674                         // The test it.size()==1 was needed to prevent crashes.
675                         // How to set the cursor corretly when it.size()>1 ??
676                         if (it.size() == 1) {
677                                 text->setCursorIntern(this, par, 0);
678                                 text->redoParagraphs(this, text->cursor,
679                                                      text->cursor.par()->next());
680                                 text->fullRebreak(this);
681                         }
682                 }
683         }
684         text->setCursorIntern(this, cursor.par(), cursor.pos());
685         return need_update;
686 }
687
688
689 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
690 {
691         // Check if the label 'from' appears more than once
692         vector<string> labels = buffer()->getLabelList();
693
694         if (lyx::count(labels.begin(), labels.end(), from) > 1)
695                 return false;
696
697         return ChangeInsets(Inset::REF_CODE, from, to);
698 }
699
700
701 bool BufferView::ChangeCitationsIfUnique(string const & from,
702                                          string const & to)
703 {
704         typedef pair<string, string> StringPair;
705
706         vector<StringPair> keys = buffer()->getBibkeyList();
707         if (count_if(keys.begin(), keys.end(),
708                      lyx::equal_1st_in_pair<StringPair>(from))
709             > 1)
710                 return false;
711
712         return ChangeInsets(Inset::CITE_CODE, from, to);
713 }
714
715
716 UpdatableInset * BufferView::theLockingInset() const
717 {
718         // If NULL is not allowed we should put an Assert here. (Lgb)
719         if (text)
720                 return text->the_locking_inset;
721         return 0;
722 }
723
724
725 void BufferView::theLockingInset(UpdatableInset * inset)
726 {
727         text->the_locking_inset = inset;
728 }
729
730
731 LyXText * BufferView::getLyXText() const
732 {
733         if (theLockingInset()) {
734                 LyXText * txt = theLockingInset()->getLyXText(this, true);
735                 if (txt)
736                         return txt;
737         }
738         return text;
739 }
740
741
742 LyXText * BufferView::getParentText(Inset * inset) const
743 {
744         if (inset->owner()) {
745                 LyXText * txt = inset->getLyXText(this);
746                 inset = inset->owner();
747                 while (inset && inset->getLyXText(this) == txt)
748                         inset = inset->owner();
749                 if (inset)
750                         return inset->getLyXText(this);
751         }
752         return text;
753 }
754
755
756 Language const * BufferView::getParentLanguage(Inset * inset) const
757 {
758         LyXText * text = getParentText(inset);
759         return text->cursor.par()->getFontSettings(buffer()->params,
760                                                    text->cursor.pos()).language();
761 }