]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
the ascent/descent/width -> dimensions() change
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * Copyright 1995-2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author unknown
7  * \author John Levon <moz@compsoc.man.ac.uk>
8  */
9
10 #include <config.h>
11
12 #include "BufferView.h"
13 #include "BufferView_pimpl.h"
14
15 #include "LaTeX.h"
16 #include "ParagraphParameters.h"
17 #include "WordLangTuple.h"
18 #include "buffer.h"
19 #include "bufferlist.h"
20 #include "debug.h"
21 #include "gettext.h"
22 #include "iterators.h"
23 #include "language.h"
24 #include "lyxcursor.h"
25 #include "lyxlex.h"
26 #include "lyxtext.h"
27 #include "undo_funcs.h"
28 #include "changes.h"
29 #include "paragraph_funcs.h"
30
31 #include "frontends/Alert.h"
32 #include "frontends/Dialogs.h"
33 #include "frontends/LyXView.h"
34 #include "frontends/WorkArea.h"
35 #include "frontends/screen.h"
36
37 #include "insets/insetcommand.h" // ChangeRefs
38 #include "insets/inseterror.h"
39 #include "insets/updatableinset.h"
40
41 #include "support/FileInfo.h"
42 #include "support/filetools.h"
43 #include "support/lyxfunctional.h" // equal_1st_in_pair
44 #include "support/types.h"
45 #include "support/lyxalgo.h" // lyx_count
46
47 #include <fstream>
48
49 extern BufferList bufferlist;
50
51 using lyx::pos_type;
52
53 using std::pair;
54 using std::endl;
55 using std::ifstream;
56 using std::vector;
57 using std::find;
58 using std::count_if;
59
60
61 BufferView::BufferView(LyXView * owner, int xpos, int ypos,
62                        int width, int height)
63         : pimpl_(new Pimpl(this, owner, xpos, ypos, width, height))
64 {
65         text = 0;
66 }
67
68
69 BufferView::~BufferView()
70 {
71         delete text;
72         delete pimpl_;
73 }
74
75
76 Buffer * BufferView::buffer() const
77 {
78         return pimpl_->buffer_;
79 }
80
81
82 LyXScreen & BufferView::screen() const
83 {
84         return pimpl_->screen();
85 }
86
87
88 LyXView * BufferView::owner() const
89 {
90         return pimpl_->owner_;
91 }
92
93
94 Painter & BufferView::painter() const
95 {
96         return pimpl_->painter();
97 }
98
99
100 void BufferView::buffer(Buffer * b)
101 {
102         pimpl_->buffer(b);
103 }
104
105
106 void BufferView::reload()
107 {
108         string const fn = buffer()->fileName();
109         if (bufferlist.close(buffer(), false))
110                 buffer(bufferlist.loadLyXFile(fn));
111 }
112
113
114 void BufferView::resize()
115 {
116         if (pimpl_->buffer_) {
117                 pimpl_->resizeCurrentBuffer();
118         }
119 }
120
121
122 void BufferView::repaint()
123 {
124         pimpl_->repaint();
125 }
126
127
128 bool BufferView::fitCursor()
129 {
130         return pimpl_->fitCursor();
131 }
132
133
134 void BufferView::update()
135 {
136         pimpl_->update();
137 }
138
139
140 void BufferView::updateScrollbar()
141 {
142         pimpl_->updateScrollbar();
143 }
144
145
146 void BufferView::scrollDocView(int value)
147 {
148         pimpl_->scrollDocView(value);
149 }
150
151
152 void BufferView::redoCurrentBuffer()
153 {
154         pimpl_->redoCurrentBuffer();
155 }
156
157
158 bool BufferView::available() const
159 {
160         return pimpl_->available();
161 }
162
163
164 Change const BufferView::getCurrentChange()
165 {
166         return pimpl_->getCurrentChange();
167 }
168
169
170 void BufferView::beforeChange(LyXText * text)
171 {
172         pimpl_->beforeChange(text);
173 }
174
175
176 void BufferView::savePosition(unsigned int i)
177 {
178         pimpl_->savePosition(i);
179 }
180
181
182 void BufferView::restorePosition(unsigned int i)
183 {
184         pimpl_->restorePosition(i);
185 }
186
187
188 bool BufferView::isSavedPosition(unsigned int i)
189 {
190         return pimpl_->isSavedPosition(i);
191 }
192
193
194 void BufferView::update(LyXText * text, UpdateCodes f)
195 {
196         pimpl_->update(text, f);
197 }
198
199
200 void BufferView::update(UpdateCodes f)
201 {
202         pimpl_->update(f);
203 }
204
205
206 void BufferView::switchKeyMap()
207 {
208         pimpl_->switchKeyMap();
209 }
210
211
212 void BufferView::insetUnlock()
213 {
214         pimpl_->insetUnlock();
215 }
216
217
218 int BufferView::workWidth() const
219 {
220         return pimpl_->workarea().workWidth();
221 }
222
223
224 void BufferView::toggleSelection(bool b)
225 {
226         pimpl_->toggleSelection(b);
227 }
228
229
230 void BufferView::toggleToggle()
231 {
232         pimpl_->toggleToggle();
233 }
234
235
236 void BufferView::center()
237 {
238         pimpl_->center();
239 }
240
241
242 string const BufferView::getClipboard() const
243 {
244         return pimpl_->workarea().getClipboard();
245 }
246
247
248 void BufferView::stuffClipboard(string const & stuff) const
249 {
250         pimpl_->stuffClipboard(stuff);
251 }
252
253
254 BufferView::UpdateCodes operator|(BufferView::UpdateCodes uc1,
255                                   BufferView::UpdateCodes uc2)
256 {
257         return static_cast<BufferView::UpdateCodes>
258                 (static_cast<int>(uc1) | static_cast<int>(uc2));
259 }
260
261
262 bool BufferView::dispatch(FuncRequest const & ev)
263 {
264         return pimpl_->dispatch(ev);
265 }
266
267
268 void BufferView::scroll(int lines)
269 {
270         pimpl_->scroll(lines);
271 }
272
273
274 // Inserts a file into current document
275 bool BufferView::insertLyXFile(string const & filen)
276         //
277         // Copyright CHT Software Service GmbH
278         // Uwe C. Schroeder
279         //
280         // Insert a LyXformat - file into current buffer
281         //
282         // Moved from lyx_cb.C (Lgb)
283 {
284         if (filen.empty())
285                 return false;
286
287         string const fname = MakeAbsPath(filen);
288
289         // check if file exist
290         FileInfo const fi(fname);
291
292         if (!fi.readable()) {
293                 string const file = MakeDisplayPath(fname, 50);
294                 string const text =
295                         bformat(_("The specified document\n%1$s\ncould not be read."), file);
296                 Alert::error(_("Could not read document"), text);
297                 return false;
298         }
299
300         beforeChange(text);
301
302         ifstream ifs(fname.c_str());
303         if (!ifs) {
304                 string const file = MakeDisplayPath(fname, 50);
305                 string const text =
306                         bformat(_("Could not open the specified document %1$s\n"), file);
307                 Alert::error(_("Could not open file"), text);
308                 return false;
309         }
310
311         int const c = ifs.peek();
312
313         LyXLex lex(0, 0);
314         lex.setStream(ifs);
315
316         bool res = true;
317
318         if (c == '#') {
319                 // FIXME: huh ? No we won't !
320                 lyxerr[Debug::INFO] << "Will insert file with header" << endl;
321                 res = buffer()->readFile(lex, fname, ParagraphList::iterator(text->cursor.par()));
322         } else {
323                 lyxerr[Debug::INFO] << "Will insert file without header"
324                                     << endl;
325                 res = buffer()->readBody(lex, ParagraphList::iterator(text->cursor.par()));
326         }
327
328         resize();
329         return res;
330 }
331
332
333 bool BufferView::removeAutoInsets()
334 {
335         // keep track of which pos and par the cursor was on
336         Paragraph * cursor_par = &*text->cursor.par();
337         Paragraph * cursor_par_prev = cursor_par ? cursor_par->previous() : 0;
338         Paragraph * cursor_par_next = cursor_par ? cursor_par->next() : 0;
339         pos_type cursor_pos = text->cursor.pos();
340
341         bool found = false;
342
343         // Trap the deletion of the paragraph the cursor is in.
344         // Iterate until we find a paragraph that won't be immediately deleted.
345         // In reality this should mean we only execute the body of the while
346         // loop once at most.  However for safety we iterate rather than just
347         // make this an if () conditional.
348         while ((cursor_par_prev || cursor_par_next)
349                && text->setCursor(
350                                   cursor_par_prev ? cursor_par_prev : cursor_par_next,
351                                   0)) {
352                 // We just removed cursor_par so have to fix the "cursor"
353                 if (cursor_par_prev) {
354                         // '.' = cursor_par
355                         //  a -> a.
356                         // .
357                         cursor_par = cursor_par_prev;
358                         cursor_pos = cursor_par->size();
359                 } else {
360                         // .  -> .a
361                         //  a
362                         cursor_par = cursor_par_next;
363                         cursor_pos = 0;
364                 }
365                 cursor_par_prev = cursor_par->previous();
366                 cursor_par_next = cursor_par->next();
367         }
368
369         // Iterate through the paragraphs removing autoDelete insets as we go.
370         // If the paragraph ends up empty after all the autoDelete insets are
371         // removed that paragraph will be removed by the next setCursor() call.
372         ParIterator it = buffer()->par_iterator_begin();
373         ParIterator end = buffer()->par_iterator_end();
374         for (; it != end; ++it) {
375                 Paragraph * par = *it;
376                 Paragraph * par_prev = par ? par->previous() : 0;
377                 bool removed = false;
378
379                 if (text->setCursor(par, 0)
380                     && cursor_par == par_prev) {
381                         // The previous setCursor line was deleted and that
382                         // was the cursor_par line.  This can only happen if an
383                         // error box was the sole item on cursor_par.
384                         // It is possible for cursor_par_prev to be stray if
385                         // the line it pointed to only had a error box on it
386                         // so we have to set it to a known correct value.
387                         // This is often the same value it already had.
388                         cursor_par_prev = par->previous();
389                         if (cursor_par_prev) {
390                                 // '|' = par, '.' = cursor_par, 'E' = error box
391                                 // First step below may occur before while{}
392                                 //  a    |a      a     a     a.
393                                 //  E -> .E -> |.E -> .  -> |b
394                                 // .      b      b    |b
395                                 //  b
396                                 cursor_par = cursor_par_prev;
397                                 cursor_pos = cursor_par_prev->size();
398                                 cursor_par_prev = cursor_par->previous();
399                                 // cursor_par_next remains the same
400                         } else if (cursor_par_next) {
401                                 // First step below may occur before while{}
402                                 // .
403                                 //  E -> |.E -> |.  -> . -> .|a
404                                 //  a      a      a    |a
405                                 cursor_par = cursor_par_next;
406                                 cursor_pos = 0;
407                                 // cursor_par_prev remains unset
408                                 cursor_par_next = cursor_par->next();
409                         } else {
410                                 // I can't find a way to trigger this
411                                 // so it should be unreachable code
412                                 // unless the buffer is corrupted.
413                                 lyxerr << "BufferView::removeAutoInsets() is bad\n";
414                         }
415                 }
416
417                 InsetList::iterator pit = par->insetlist.begin();
418                 InsetList::iterator pend = par->insetlist.end();
419
420                 while (pit != pend) {
421                         if (pit.getInset()->autoDelete()) {
422                                 removed = true;
423                                 pos_type const pos = pit.getPos();
424
425                                 par->erase(pos);
426                                 // We just invalidated par's inset iterators so
427                                 // we get the next valid iterator position
428                                 pit = par->insetlist.insetIterator(pos);
429                                 // and ensure we have a valid end iterator.
430                                 pend = par->insetlist.end();
431
432                                 if (cursor_par == par) {
433                                         // update the saved cursor position
434                                         if (cursor_pos > pos)
435                                                 --cursor_pos;
436                                 }
437                         } else {
438                                 ++pit;
439                         }
440                 }
441                 if (removed) {
442                         found = true;
443                         text->redoParagraph();
444                 }
445         }
446
447         // It is possible that the last line is empty if it was cursor_par
448         // and/or only had an error inset on it.  So we set the cursor to the
449         // start of the doc to force its removal and ensure a valid saved cursor
450         if (text->setCursor(&*text->ownerParagraphs().begin(), 0)
451             && 0 == cursor_par_next) {
452                 cursor_par = cursor_par_prev;
453                 cursor_pos = cursor_par->size();
454         } else if (cursor_pos > cursor_par->size()) {
455                 // Some C-Enter lines were removed by the setCursor call which
456                 // then invalidated cursor_pos. It could still be "wrong" because
457                 // the cursor may appear to have jumped but since we collapsed
458                 // some C-Enter lines this should be a reasonable compromise.
459                 cursor_pos = cursor_par->size();
460         }
461
462         // restore the original cursor in its corrected location.
463         text->setCursorIntern(cursor_par, cursor_pos);
464
465         return found;
466 }
467
468
469 void BufferView::showErrorList()
470 {
471         owner()->getDialogs().show("errorlist");
472 }
473
474
475 void BufferView::setCursorFromRow(int row)
476 {
477         int tmpid = -1;
478         int tmppos = -1;
479
480         buffer()->texrow.getIdFromRow(row, tmpid, tmppos);
481
482         Paragraph * texrowpar;
483
484         if (tmpid == -1) {
485                 texrowpar = &*text->ownerParagraphs().begin();
486                 tmppos = 0;
487         } else {
488                 texrowpar = &*buffer()->getParFromID(tmpid);
489         }
490         text->setCursor(texrowpar, tmppos);
491 }
492
493
494 bool BufferView::insertInset(Inset * inset, string const & lout)
495 {
496         return pimpl_->insertInset(inset, lout);
497 }
498
499
500 void BufferView::gotoLabel(string const & label)
501 {
502         for (Buffer::inset_iterator it = buffer()->inset_iterator_begin();
503              it != buffer()->inset_iterator_end(); ++it) {
504                 vector<string> labels = it->getLabelList();
505                 if (find(labels.begin(),labels.end(),label)
506                      != labels.end()) {
507                         beforeChange(text);
508                         text->setCursor(it.getPar(), it.getPos());
509                         text->selection.cursor = text->cursor;
510                         update(text, BufferView::SELECT);
511                         return;
512                 }
513         }
514 }
515
516
517 void BufferView::undo()
518 {
519         if (!available())
520                 return;
521
522         owner()->message(_("Undo"));
523         beforeChange(text);
524         update(text, BufferView::SELECT);
525         if (!textUndo(this))
526                 owner()->message(_("No further undo information"));
527         else
528                 update(text, BufferView::SELECT);
529         switchKeyMap();
530 }
531
532
533 void BufferView::redo()
534 {
535         if (!available())
536                 return;
537
538         owner()->message(_("Redo"));
539         beforeChange(text);
540         update(text, BufferView::SELECT);
541         if (!textRedo(this))
542                 owner()->message(_("No further redo information"));
543         else
544                 update(text, BufferView::SELECT);
545         switchKeyMap();
546 }
547
548
549 // these functions are for the spellchecker
550 WordLangTuple const BufferView::nextWord(float & value)
551 {
552         if (!available()) {
553                 value = 1;
554                 return WordLangTuple();
555         }
556
557         return text->selectNextWordToSpellcheck(value);
558 }
559
560
561 void BufferView::selectLastWord()
562 {
563         if (!available())
564                 return;
565
566         LyXCursor cur = text->selection.cursor;
567         beforeChange(text);
568         text->selection.cursor = cur;
569         text->selectSelectedWord();
570         toggleSelection(false);
571         update(text, BufferView::SELECT);
572 }
573
574
575 void BufferView::endOfSpellCheck()
576 {
577         if (!available()) return;
578
579         beforeChange(text);
580         text->selectSelectedWord();
581         text->clearSelection();
582         update(text, BufferView::SELECT);
583 }
584
585
586 void BufferView::replaceWord(string const & replacestring)
587 {
588         if (!available())
589                 return;
590
591         LyXText * tt = getLyXText();
592         update(tt, BufferView::SELECT);
593
594         // clear the selection (if there is any)
595         toggleSelection(false);
596         update(tt, BufferView::SELECT);
597
598         // clear the selection (if there is any)
599         toggleSelection(false);
600         tt->replaceSelectionWithString(replacestring);
601
602         tt->setSelectionRange(replacestring.length());
603
604         // Go back so that replacement string is also spellchecked
605         for (string::size_type i = 0; i < replacestring.length() + 1; ++i) {
606                 tt->cursorLeft(this);
607         }
608         update(tt, BufferView::SELECT);
609
610         // FIXME: should be done through LFUN
611         buffer()->markDirty();
612         fitCursor();
613 }
614 // End of spellchecker stuff
615
616
617 bool BufferView::lockInset(UpdatableInset * inset)
618 {
619         if (!inset)
620                 return false;
621         // don't relock if we're already locked
622         if (theLockingInset() == inset)
623                 return true;
624         if (!theLockingInset()) {
625                 // first check if it's the inset under the cursor we want lock
626                 // should be most of the time
627                 if (text->cursor.pos() < text->cursor.par()->size()
628                     && text->cursor.par()->getChar(text->cursor.pos()) ==
629                     Paragraph::META_INSET) {
630                         Inset * in = text->cursor.par()->getInset(text->cursor.pos());
631                         if (inset == in) {
632                                 theLockingInset(inset);
633                                 return true;
634                         }
635                 }
636                 // Then do a deep look of the inset and lock the right one
637                 int const id = inset->id();
638                 ParagraphList::iterator pit = buffer()->paragraphs.begin();
639                 ParagraphList::iterator pend = buffer()->paragraphs.end();
640                 for (; pit != pend; ++pit) {
641                         InsetList::iterator it = pit->insetlist.begin();
642                         InsetList::iterator end = pit->insetlist.end();
643                         for (; it != end; ++it) {
644                                 if (it.getInset() == inset) {
645                                         text->setCursorIntern(pit, it.getPos());
646                                         theLockingInset(inset);
647                                         return true;
648                                 }
649                                 if (it.getInset()->getInsetFromID(id)) {
650                                         text->setCursorIntern(pit, it.getPos());
651                                         FuncRequest cmd(this, LFUN_INSET_EDIT, "left");
652                                         it.getInset()->localDispatch(cmd);
653                                         return theLockingInset()->lockInsetInInset(this, inset);
654                                 }
655                         }
656                 }
657                 return false;
658         }
659         return theLockingInset()->lockInsetInInset(this, inset);
660 }
661
662
663 bool BufferView::fitLockedInsetCursor(int x, int y, int asc, int desc)
664 {
665         if (theLockingInset() && available()) {
666                 y += text->cursor.iy() + theLockingInset()->insetInInsetY();
667                 if (screen().fitManualCursor(this, text, x, y, asc, desc)) {
668                         updateScrollbar();
669                         return true;
670                 }
671         }
672         return false;
673 }
674
675
676 void BufferView::hideCursor()
677 {
678         screen().hideCursor();
679 }
680
681
682 int BufferView::unlockInset(UpdatableInset * inset)
683 {
684         if (!inset)
685                 return 0;
686         if (inset && theLockingInset() == inset) {
687                 inset->insetUnlock(this);
688                 theLockingInset(0);
689                 // make sure we update the combo !
690                 owner()->setLayout(getLyXText()->cursor.par()->layout()->name());
691                 // Tell the paragraph dialog that we changed paragraph
692                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
693                 finishUndo();
694                 return 0;
695         } else if (inset && theLockingInset() &&
696                    theLockingInset()->unlockInsetInInset(this, inset)) {
697                 // Tell the paragraph dialog that we changed paragraph
698                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
699                 // owner inset has updated the layout combo
700                 finishUndo();
701                 return 0;
702         }
703         return 1;
704 }
705
706
707 void BufferView::lockedInsetStoreUndo(Undo::undo_kind kind)
708 {
709         if (!theLockingInset())
710                 return; // shouldn't happen
711         if (kind == Undo::EDIT) // in this case insets would not be stored!
712                 kind = Undo::FINISH;
713         setUndo(this, kind,
714                 text->cursor.par(),
715                 boost::next(text->cursor.par()));
716 }
717
718
719 void BufferView::updateInset(Inset * inset)
720 {
721         pimpl_->updateInset(inset);
722 }
723
724
725 bool BufferView::ChangeInsets(Inset::Code code,
726                               string const & from, string const & to)
727 {
728         bool need_update = false;
729         LyXCursor cursor = text->cursor;
730         LyXCursor tmpcursor = cursor;
731         cursor.par(tmpcursor.par());
732         cursor.pos(tmpcursor.pos());
733
734         ParIterator end = buffer()->par_iterator_end();
735         for (ParIterator it = buffer()->par_iterator_begin();
736              it != end; ++it) {
737                 Paragraph * par = *it;
738                 bool changed_inset = false;
739                 for (InsetList::iterator it2 = par->insetlist.begin();
740                      it2 != par->insetlist.end(); ++it2) {
741                         if (it2.getInset()->lyxCode() == code) {
742                                 InsetCommand * inset = static_cast<InsetCommand *>(it2.getInset());
743                                 if (inset->getContents() == from) {
744                                         inset->setContents(to);
745                                         changed_inset = true;
746                                 }
747                         }
748                 }
749                 if (changed_inset) {
750                         need_update = true;
751
752                         // FIXME
753
754                         // The test it.size()==1 was needed to prevent crashes.
755                         // How to set the cursor corretly when it.size()>1 ??
756                         if (it.size() == 1) {
757                                 text->setCursorIntern(par, 0);
758                                 text->redoParagraphs(text->cursor,
759                                                      boost::next(text->cursor.par()));
760                                 text->fullRebreak();
761                         }
762                 }
763         }
764         text->setCursorIntern(cursor.par(), cursor.pos());
765         return need_update;
766 }
767
768
769 bool BufferView::ChangeRefsIfUnique(string const & from, string const & to)
770 {
771         // Check if the label 'from' appears more than once
772         vector<string> labels = buffer()->getLabelList();
773
774         if (lyx::count(labels.begin(), labels.end(), from) > 1)
775                 return false;
776
777         return ChangeInsets(Inset::REF_CODE, from, to);
778 }
779
780
781 bool BufferView::ChangeCitationsIfUnique(string const & from, string const & to)
782 {
783         typedef pair<string, string> StringPair;
784
785         vector<StringPair> keys;
786         buffer()->fillWithBibKeys(keys);
787         if (count_if(keys.begin(), keys.end(),
788                      lyx::equal_1st_in_pair<StringPair>(from))
789             > 1)
790                 return false;
791
792         return ChangeInsets(Inset::CITE_CODE, from, to);
793 }
794
795
796 UpdatableInset * BufferView::theLockingInset() const
797 {
798         // If NULL is not allowed we should put an Assert here. (Lgb)
799         if (text)
800                 return text->the_locking_inset;
801         return 0;
802 }
803
804
805 void BufferView::theLockingInset(UpdatableInset * inset)
806 {
807         text->the_locking_inset = inset;
808 }
809
810
811 LyXText * BufferView::getLyXText() const
812 {
813         if (theLockingInset()) {
814                 LyXText * txt = theLockingInset()->getLyXText(this, true);
815                 if (txt)
816                         return txt;
817         }
818         return text;
819 }
820
821
822 LyXText * BufferView::getParentText(Inset * inset) const
823 {
824         if (inset->owner()) {
825                 LyXText * txt = inset->getLyXText(this);
826                 inset = inset->owner();
827                 while (inset && inset->getLyXText(this) == txt)
828                         inset = inset->owner();
829                 if (inset)
830                         return inset->getLyXText(this);
831         }
832         return text;
833 }
834
835
836 Language const * BufferView::getParentLanguage(Inset * inset) const
837 {
838         LyXText * text = getParentText(inset);
839         return text->cursor.par()->getFontSettings(buffer()->params,
840                                                    text->cursor.pos()).language();
841 }
842
843
844 Encoding const * BufferView::getEncoding() const
845 {
846         LyXText * t = getLyXText();
847         if (!t)
848                 return 0;
849
850         LyXCursor const & c = t->cursor;
851         LyXFont const font = c.par()->getFont(buffer()->params, c.pos(),
852                                               outerFont(c.par(), t->ownerParagraphs()));
853         return font.language()->encoding();
854 }
855
856
857 void BufferView::haveSelection(bool sel)
858 {
859         pimpl_->workarea().haveSelection(sel);
860 }
861
862
863 int BufferView::workHeight() const
864 {
865         return pimpl_->workarea().workHeight();
866 }