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