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