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