]> git.lyx.org Git - lyx.git/blob - src/BufferView2.C
Martin's Per-buffer counters patch.
[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                 InsetList::iterator pit = par->insetlist.begin();
195                 InsetList::iterator pend = par->insetlist.end();
196
197                 while (pit != pend) {
198                         if (pit.getInset()->autoDelete()) {
199                                 removed = true;
200                                 pos_type const pos = pit.getPos();
201
202                                 par->erase(pos);
203                                 // We just invalidated par's inset iterators so
204                                 // we get the next valid iterator position
205                                 pit = par->insetlist.insetIterator(pos);
206                                 // and ensure we have a valid end iterator.
207                                 pend = par->insetlist.end();
208
209                                 if (cursor_par == par) {
210                                         // update the saved cursor position
211                                         if (cursor_pos > pos)
212                                                 --cursor_pos;
213                                 }
214                         } else {
215                                 ++pit;
216                         }
217                 }
218                 if (removed) {
219                         found = true;
220                         text->redoParagraph(this);
221                 }
222         }
223
224         // It is possible that the last line is empty if it was cursor_par
225         // and/or only had an error inset on it.  So we set the cursor to the
226         // start of the doc to force its removal and ensure a valid saved cursor
227         if (text->setCursor(this, text->ownerParagraph(), 0)
228             && 0 == cursor_par_next) {
229                 cursor_par = cursor_par_prev;
230                 cursor_pos = cursor_par->size();
231         } else if (cursor_pos > cursor_par->size()) {
232                 // Some C-Enter lines were removed by the setCursor call which
233                 // then invalidated cursor_pos. It could still be "wrong" because
234                 // the cursor may appear to have jumped but since we collapsed
235                 // some C-Enter lines this should be a reasonable compromise.
236                 cursor_pos = cursor_par->size();
237         }
238
239         // restore the original cursor in its corrected location.
240         text->setCursorIntern(this, cursor_par, cursor_pos);
241
242         return found;
243 }
244
245
246 void BufferView::insertErrors(TeXErrors & terr)
247 {
248         // Save the cursor position
249         LyXCursor cursor = text->cursor;
250
251         TeXErrors::Errors::const_iterator cit = terr.begin();
252         TeXErrors::Errors::const_iterator end = terr.end();
253         for (; cit != end; ++cit) {
254                 string const desctext(cit->error_desc);
255                 string const errortext(cit->error_text);
256                 string const msgtxt = desctext + '\n' + errortext;
257                 int const errorrow = cit->error_in_line;
258
259                 // Insert error string for row number
260                 int tmpid = -1;
261                 int tmppos = -1;
262
263                 if (buffer()->texrow.getIdFromRow(errorrow, tmpid, tmppos)) {
264                         buffer()->texrow.increasePos(tmpid, tmppos);
265                 }
266
267                 Paragraph * texrowpar = 0;
268
269                 if (tmpid == -1) {
270                         texrowpar = text->ownerParagraph();
271                         tmppos = 0;
272                 } else {
273                         texrowpar = buffer()->getParFromID(tmpid);
274                 }
275
276                 if (texrowpar == 0)
277                         continue;
278
279                 freezeUndo();
280                 InsetError * new_inset = new InsetError(msgtxt);
281                 text->setCursorIntern(this, texrowpar, tmppos);
282                 text->insertInset(this, new_inset);
283                 text->fullRebreak(this);
284                 unFreezeUndo();
285         }
286         // Restore the cursor position
287         text->setCursorIntern(this, cursor.par(), cursor.pos());
288 }
289
290
291 void BufferView::setCursorFromRow(int row)
292 {
293         int tmpid = -1;
294         int tmppos = -1;
295
296         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
297
298         Paragraph * texrowpar;
299
300         if (tmpid == -1) {
301                 texrowpar = text->ownerParagraph();
302                 tmppos = 0;
303         } else {
304                 texrowpar = buffer()->getParFromID(tmpid);
305         }
306         text->setCursor(this, texrowpar, tmppos);
307 }
308
309
310 bool BufferView::insertInset(Inset * inset, string const & lout)
311 {
312         return pimpl_->insertInset(inset, lout);
313 }
314
315
316 /* This is also a buffer property (ale) */
317 // Not so sure about that. a goto Label function can not be buffer local, just
318 // think how this will work in a multiwindo/buffer environment, all the
319 // cursors in all the views showing this buffer will move. (Lgb)
320 // OK, then no cursor action should be allowed in buffer. (ale)
321 bool BufferView::gotoLabel(string const & label)
322
323 {
324         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
325              it != buffer()->inset_iterator_end(); ++it) {
326                 vector<string> labels = (*it)->getLabelList();
327                 if (find(labels.begin(),labels.end(),label)
328                      != labels.end()) {
329                         beforeChange(text);
330                         text->setCursor(this, it.getPar(), it.getPos());
331                         text->selection.cursor = text->cursor;
332                         update(text, BufferView::SELECT|BufferView::FITCUR);
333                         return true;
334                 }
335         }
336         return false;
337 }
338
339
340 void BufferView::menuUndo()
341 {
342         if (!available())
343                 return;
344
345         owner()->message(_("Undo"));
346         hideCursor();
347         beforeChange(text);
348         update(text, BufferView::SELECT|BufferView::FITCUR);
349         if (!textUndo(this))
350                 owner()->message(_("No further undo information"));
351         else
352                 update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
353         switchKeyMap();
354 }
355
356
357 void BufferView::menuRedo()
358 {
359         if (!available())
360                 return;
361
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         switchKeyMap();
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         // bug 393
430         text->clearSelection();
431         update(text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
432 // why fake a selection only I think it should be a real one and not only
433 // a painted one (Jug 20020318).
434 #if 0
435         // clear the selection
436         toggleSelection();
437         text->clearSelection();
438         update(text, BufferView::SELECT|BufferView::FITCUR);
439 #endif
440 }
441
442
443 /* these functions are for the spellchecker */
444 WordLangTuple const BufferView::nextWord(float & value)
445 {
446         if (!available()) {
447                 value = 1;
448                 return WordLangTuple();
449         }
450
451         return text->selectNextWordToSpellcheck(this, value);
452 }
453
454
455 void BufferView::selectLastWord()
456 {
457         if (!available()) return;
458
459         LyXCursor cur = text->selection.cursor;
460         hideCursor();
461         beforeChange(text);
462         text->selection.cursor = cur;
463         text->selectSelectedWord(this);
464         toggleSelection(false);
465         update(text, BufferView::SELECT|BufferView::FITCUR);
466 }
467
468
469 void BufferView::endOfSpellCheck()
470 {
471         if (!available()) return;
472
473         hideCursor();
474         beforeChange(text);
475         text->selectSelectedWord(this);
476         text->clearSelection();
477         update(text, BufferView::SELECT|BufferView::FITCUR);
478 }
479
480
481 void BufferView::replaceWord(string const & replacestring)
482 {
483         if (!available()) return;
484
485         LyXText * tt = getLyXText();
486         hideCursor();
487         update(tt, BufferView::SELECT|BufferView::FITCUR);
488
489         /* clear the selection (if there is any) */
490         toggleSelection(false);
491         update(tt, BufferView::SELECT|BufferView::FITCUR);
492
493         /* clear the selection (if there is any) */
494         toggleSelection(false);
495         tt->replaceSelectionWithString(this, replacestring);
496
497         tt->setSelectionOverString(this, replacestring);
498
499         // Go back so that replacement string is also spellchecked
500         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
501                 tt->cursorLeft(this);
502         }
503         update(tt, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
504 }
505 // End of spellchecker stuff
506
507
508 bool BufferView::lockInset(UpdatableInset * inset)
509 {
510         if (!inset)
511                 return false;
512         // don't relock if we're already locked
513         if (theLockingInset() == inset)
514                 return true;
515         if (!theLockingInset()) {
516                 // first check if it's the inset under the cursor we want lock
517                 // should be most of the time
518                 char const c = text->cursor.par()->getChar(text->cursor.pos());
519                 if (c == Paragraph::META_INSET) {
520                         Inset * in = text->cursor.par()->getInset(text->cursor.pos());
521                         if (inset == in) {
522                                 theLockingInset(inset);
523                                 return true;
524                         }
525                 }
526                 // Then do a deep look of the inset and lock the right one
527                 Paragraph * par = &*(buffer()->paragraphs.begin());
528                 int const id = inset->id();
529                 while (par) {
530                         InsetList::iterator it =
531                                 par->insetlist.begin();
532                         InsetList::iterator const end =
533                                 par->insetlist.end();
534                         for (; it != end; ++it) {
535                                 if (it.getInset() == inset) {
536                                         text->setCursorIntern(this, par, it.getPos());
537                                         theLockingInset(inset);
538                                         return true;
539                                 }
540                                 if (it.getInset()->getInsetFromID(id)) {
541                                         text->setCursorIntern(this, par, it.getPos());
542                                         it.getInset()->edit(this);
543                                         return theLockingInset()->lockInsetInInset(this, inset);
544                                 }
545                         }
546                         par = par->next();
547                 }
548                 return false;
549         }
550         return theLockingInset()->lockInsetInInset(this, inset);
551 }
552
553
554 void BufferView::showLockedInsetCursor(int x, int y, int asc, int desc)
555 {
556         if (available() && theLockingInset() && !theLockingInset()->nodraw()) {
557                 LyXCursor cursor = text->cursor;
558                 Inset * locking_inset = theLockingInset()->getLockingInset();
559
560                 if ((cursor.pos() - 1 >= 0) &&
561                     cursor.par()->isInset(cursor.pos() - 1) &&
562                     (cursor.par()->getInset(cursor.pos() - 1) ==
563                      locking_inset))
564                         text->setCursor(this, cursor,
565                                         cursor.par(), cursor.pos() - 1);
566                 LyXScreen::Cursor_Shape shape = LyXScreen::BAR_SHAPE;
567                 LyXText * txt = getLyXText();
568                 if (locking_inset->isTextInset() &&
569                     locking_inset->lyxCode() != Inset::ERT_CODE &&
570                     (txt->real_current_font.language() !=
571                      buffer()->params.language
572                      || txt->real_current_font.isVisibleRightToLeft()
573                      != buffer()->params.language->RightToLeft()))
574                         shape = (txt->real_current_font.isVisibleRightToLeft())
575                                 ? LyXScreen::REVERSED_L_SHAPE
576                                 : LyXScreen::L_SHAPE;
577                 y += cursor.iy() + theLockingInset()->insetInInsetY();
578                 screen().showManualCursor(text, x, y, asc, desc,
579                                                   shape);
580         }
581 }
582
583
584 void BufferView::hideLockedInsetCursor()
585 {
586         if (theLockingInset() && available()) {
587                 screen().hideCursor();
588         }
589 }
590
591
592 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
593 {
594         if (theLockingInset() && available()) {
595                 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
596                 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
597                         updateScrollbar();
598                         return true;
599                 }
600         }
601         return false;
602 }
603
604
605 int BufferView::unlockInset(UpdatableInset * inset)
606 {
607         if (!inset)
608                 return 0;
609         if (inset && theLockingInset() == inset) {
610                 inset->insetUnlock(this);
611                 theLockingInset(0);
612                 // make sure we update the combo !
613                 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
614                 // Tell the paragraph dialog that we changed paragraph
615                 owner()->getDialogs()->updateParagraph();
616                 finishUndo();
617                 return 0;
618         } else if (inset && theLockingInset() &&
619                    theLockingInset()->unlockInsetInInset(this, inset)) {
620                 // Tell the paragraph dialog that we changed paragraph
621                 owner()->getDialogs()->updateParagraph();
622                 // owner inset has updated the layout combo
623                 finishUndo();
624                 return 0;
625         }
626         return bufferlist.unlockInset(inset);
627 }
628
629
630 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
631 {
632         if (!theLockingInset())
633                 return; // shouldn't happen
634         if (kind == Undo::EDIT) // in this case insets would not be stored!
635                 kind = Undo::FINISH;
636         setUndo(this, kind,
637                 text->cursor.par(),
638                 text->cursor.par()->next());
639 }
640
641
642 void BufferView::updateInset(Inset * inset, bool mark_dirty)
643 {
644         pimpl_->updateInset(inset, mark_dirty);
645 }
646
647
648 bool BufferView::ChangeInsets(Inset::Code code,
649                               string const & from, string const & to)
650 {
651         bool need_update = false;
652         LyXCursor cursor = text->cursor;
653         LyXCursor tmpcursor = cursor;
654         cursor.par(tmpcursor.par());
655         cursor.pos(tmpcursor.pos());
656
657         ParIterator end = buffer()->par_iterator_end();
658         for (ParIterator it = buffer()->par_iterator_begin();
659              it != end; ++it) {
660                 Paragraph * par = *it;
661                 bool changed_inset = false;
662                 for (InsetList::iterator it2 = par->insetlist.begin();
663                      it2 != par->insetlist.end(); ++it2) {
664                         if (it2.getInset()->lyxCode() == code) {
665                                 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
666                                 if (inset->getContents() == from) {
667                                         inset->setContents(to);
668                                         changed_inset = true;
669                                 }
670                         }
671                 }
672                 if (changed_inset) {
673                         need_update = true;
674
675                         // FIXME
676
677                         // The test it.size()==1 was needed to prevent crashes.
678                         // How to set the cursor corretly when it.size()>1 ??
679                         if (it.size() == 1) {
680                                 text->setCursorIntern(this, par, 0);
681                                 text->redoParagraphs(this, text->cursor,
682                                                      text->cursor.par()->next());
683                                 text->fullRebreak(this);
684                         }
685                 }
686         }
687         text->setCursorIntern(this, cursor.par(), cursor.pos());
688         return need_update;
689 }
690
691
692 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
693 {
694         // Check if the label 'from' appears more than once
695         vector<string> labels = buffer()->getLabelList();
696
697         if (lyx::count(labels.begin(), labels.end(), from) > 1)
698                 return false;
699
700         return ChangeInsets(Inset::REF_CODE, from, to);
701 }
702
703
704 bool BufferView::ChangeCitationsIfUnique(string const & from,
705                                          string const & to)
706 {
707         typedef pair<string, string> StringPair;
708
709         vector<StringPair> keys = buffer()->getBibkeyList();
710         if (count_if(keys.begin(), keys.end(),
711                      lyx::equal_1st_in_pair<StringPair>(from))
712             > 1)
713                 return false;
714
715         return ChangeInsets(Inset::CITE_CODE, from, to);
716 }
717
718
719 UpdatableInset * BufferView::theLockingInset() const
720 {
721         // If NULL is not allowed we should put an Assert here. (Lgb)
722         if (text)
723                 return text->the_locking_inset;
724         return 0;
725 }
726
727
728 void BufferView::theLockingInset(UpdatableInset * inset)
729 {
730         text->the_locking_inset = inset;
731 }
732
733
734 LyXText * BufferView::getLyXText() const
735 {
736         if (theLockingInset()) {
737                 LyXText * txt = theLockingInset()->getLyXText(this, true);
738                 if (txt)
739                         return txt;
740         }
741         return text;
742 }
743
744
745 LyXText * BufferView::getParentText(Inset * inset) const
746 {
747         if (inset->owner()) {
748                 LyXText * txt = inset->getLyXText(this);
749                 inset = inset->owner();
750                 while (inset && inset->getLyXText(this) == txt)
751                         inset = inset->owner();
752                 if (inset)
753                         return inset->getLyXText(this);
754         }
755         return text;
756 }
757
758
759 Language const * BufferView::getParentLanguage(Inset * inset) const
760 {
761         LyXText * text = getParentText(inset);
762         return text->cursor.par()->getFontSettings(buffer()->params,
763                                                    text->cursor.pos()).language();
764 }