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