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