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