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