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