3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alfredo Braunstein
7 * \author Lars Gullik Bjønnes
10 * \author Jürgen Vigna
12 * Full author contact details are available in file CREDITS.
17 #include "BufferView.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "CoordCache.h"
25 #include "CutAndPaste.h"
26 #include "DispatchResult.h"
27 #include "EmbeddedFiles.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
34 #include "InsetIterator.h"
36 #include "LaTeXFeatures.h"
42 #include "MetricsInfo.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "ParIterator.h"
49 #include "TextClass.h"
50 #include "TextMetrics.h"
53 #include "WordLangTuple.h"
55 #include "insets/InsetBibtex.h"
56 #include "insets/InsetCommand.h" // ChangeRefs
57 #include "insets/InsetRef.h"
58 #include "insets/InsetText.h"
60 #include "frontends/alert.h"
61 #include "frontends/Delegates.h"
62 #include "frontends/FontMetrics.h"
63 #include "frontends/Painter.h"
64 #include "frontends/Selection.h"
66 #include "graphics/Previews.h"
68 #include "support/convert.h"
69 #include "support/debug.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/gettext.h"
73 #include "support/lstrings.h"
74 #include "support/Package.h"
75 #include "support/types.h"
84 using namespace lyx::support;
88 namespace Alert = frontend::Alert;
92 /// Return an inset of this class if it exists at the current cursor position
94 T * getInsetByCode(Cursor const & cur, InsetCode code)
97 Inset * inset = it.nextInset();
98 if (inset && inset->lyxCode() == code)
99 return static_cast<T*>(inset);
104 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
107 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
108 docstring const & contents)
110 DocIterator tmpdit = dit;
113 Inset const * inset = tmpdit.nextInset();
115 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
116 && (contents.empty() ||
117 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
121 tmpdit.forwardInset();
128 /// Looks for next inset with one of the given codes.
129 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
133 DocIterator tmpdit = dit;
134 tmpdit.forwardInset();
139 Inset const * inset = tmpdit.nextInset();
141 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
142 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
146 if (!findNextInset(tmpdit, codes, contents)) {
147 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
148 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
149 if (!findNextInset(tmpdit, codes, contents))
160 /// Looks for next inset with the given code
161 void findInset(DocIterator & dit, InsetCode code, bool same_content)
163 findInset(dit, vector<InsetCode>(1, code), same_content);
167 /// Moves cursor to the next inset with one of the given codes.
168 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
171 Cursor tmpcur = bv->cursor();
172 if (!findInset(tmpcur, codes, same_content)) {
173 bv->cursor().message(_("No more insets"));
177 tmpcur.clearSelection();
178 bv->setCursor(tmpcur);
182 /// Moves cursor to the next inset with given code.
183 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
185 gotoInset(bv, vector<InsetCode>(1, code), same_content);
189 /// A map from a Text to the associated text metrics
190 typedef map<Text const *, TextMetrics> TextMetricsCache;
192 enum ScreenUpdateStrategy {
202 /////////////////////////////////////////////////////////////////////
206 /////////////////////////////////////////////////////////////////////
208 struct BufferView::Private
210 Private(BufferView & bv): wh_(0), cursor_(bv),
211 anchor_pit_(0), anchor_ypos_(0),
212 last_inset_(0), gui_(0)
216 ScrollbarParameters scrollbarParameters_;
218 ScreenUpdateStrategy update_strategy_;
220 CoordCache coord_cache_;
222 /// Estimated average par height for scrollbar.
224 /// this is used to handle XSelection events in the right manner.
233 pit_type anchor_pit_;
237 vector<int> par_height_;
239 /// keyboard mapping object.
242 /// last visited inset.
243 /** kept to send setMouseHover(false).
244 * Not owned, so don't delete.
248 mutable TextMetricsCache text_metrics_;
251 /** Not owned, so don't delete.
253 frontend::GuiBufferViewDelegate * gui_;
257 BufferView::BufferView(Buffer & buf)
258 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
260 d->xsel_cache_.set = false;
261 d->intl_.initKeyMapper(lyxrc.use_kbmap);
263 d->cursor_.push(buffer_.inset());
264 d->cursor_.resetAnchor();
265 d->cursor_.setCurrentFont();
267 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
268 graphics::Previews::get().generateBufferPreviews(buffer_);
272 BufferView::~BufferView()
274 // current buffer is going to be switched-off, save cursor pos
275 // Ideally, the whole cursor stack should be saved, but session
276 // currently can only handle bottom (whole document) level pit and pos.
277 // That is to say, if a cursor is in a nested inset, it will be
278 // restore to the left of the top level inset.
279 LastFilePosSection::FilePos fp;
280 fp.pit = d->cursor_.bottom().pit();
281 fp.pos = d->cursor_.bottom().pos();
282 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
288 Intl & BufferView::getIntl()
294 Intl const & BufferView::getIntl() const
300 CoordCache & BufferView::coordCache()
302 return d->coord_cache_;
306 CoordCache const & BufferView::coordCache() const
308 return d->coord_cache_;
312 Buffer & BufferView::buffer()
318 Buffer const & BufferView::buffer() const
324 bool BufferView::fitCursor()
326 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
327 frontend::FontMetrics const & fm =
328 theFontMetrics(d->cursor_.getFont().fontInfo());
329 int const asc = fm.maxAscent();
330 int const des = fm.maxDescent();
331 Point const p = getPos(d->cursor_, d->cursor_.boundary());
332 if (p.y_ - asc >= 0 && p.y_ + des < height_)
339 void BufferView::processUpdateFlags(Update::flags flags)
341 // last_inset_ points to the last visited inset. This pointer may become
342 // invalid because of keyboard editing. Since all such operations
343 // causes screen update(), I reset last_inset_ to avoid such a problem.
345 // This is close to a hot-path.
346 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
347 << "[fitcursor = " << (flags & Update::FitCursor)
348 << ", forceupdate = " << (flags & Update::Force)
349 << ", singlepar = " << (flags & Update::SinglePar)
350 << "] buffer: " << &buffer_);
352 // Update macro store
353 if (!(cursor().inMathed() && cursor().inMacroMode()))
354 buffer_.updateMacros();
356 // Now do the first drawing step if needed. This consists on updating
357 // the CoordCache in updateMetrics().
358 // The second drawing step is done in WorkArea::redraw() if needed.
360 // Case when no explicit update is requested.
362 // no need to redraw anything.
363 d->update_strategy_ = NoScreenUpdate;
367 if (flags == Update::Decoration) {
368 d->update_strategy_ = DecorationUpdate;
373 if (flags == Update::FitCursor
374 || flags == (Update::Decoration | Update::FitCursor)) {
375 // tell the frontend to update the screen if needed.
380 if (flags & Update::Decoration) {
381 d->update_strategy_ = DecorationUpdate;
385 // no screen update is needed.
386 d->update_strategy_ = NoScreenUpdate;
390 bool const full_metrics = flags & Update::Force || !singleParUpdate();
393 // We have to update the full screen metrics.
396 if (!(flags & Update::FitCursor)) {
397 // Nothing to do anymore. Trigger a redraw and return
402 // updateMetrics() does not update paragraph position
403 // This is done at draw() time. So we need a redraw!
407 // The cursor is off screen so ensure it is visible.
414 void BufferView::updateScrollbar()
419 Text & t = buffer_.text();
420 TextMetrics & tm = d->text_metrics_[&t];
422 LYXERR(Debug::GUI, " Updating scrollbar: height: "
423 << t.paragraphs().size()
424 << " curr par: " << d->cursor_.bottom().pit()
425 << " default height " << defaultRowHeight());
427 int const parsize = int(t.paragraphs().size() - 1);
428 if (d->par_height_.size() != parsize) {
429 d->par_height_.clear();
430 // FIXME: We assume a default paragraph height of 4 rows. This
431 // should probably be pondered with the screen width.
432 d->par_height_.resize(parsize, defaultRowHeight() * 4);
435 // It would be better to fix the scrollbar to understand
436 // values in [0..1] and divide everything by wh
438 // Look at paragraph heights on-screen
439 pit_type first_visible_pit = -1;
440 pair<pit_type, ParagraphMetrics const *> first = tm.first();
441 pair<pit_type, ParagraphMetrics const *> last = tm.last();
442 for (pit_type pit = first.first; pit <= last.first; ++pit) {
443 ParagraphMetrics const & pm = tm.parMetrics(pit);
444 d->par_height_[pit] = pm.height();
445 if (first_visible_pit < 0 && pm.position() + pm.descent() > 0)
446 first_visible_pit = pit;
449 LYXERR(Debug::SCROLLING, "first_visible_pit " << first_visible_pit);
451 d->scrollbarParameters_.height = 0;
452 for (size_t i = 0; i != d->par_height_.size(); ++i) {
453 d->scrollbarParameters_.height += d->par_height_[i];
454 if (i != first_visible_pit)
456 // FIXME: we should look for the first visible row within
457 // the deepest inset!
458 d->scrollbarParameters_.position = d->scrollbarParameters_.height;
461 d->scrollbarParameters_.lineScrollHeight =
462 tm.parMetrics(first_visible_pit).rows()[0].height();
466 ScrollbarParameters const & BufferView::scrollbarParameters() const
468 return d->scrollbarParameters_;
472 void BufferView::scrollDocView(int value)
474 int const offset = value - d->scrollbarParameters_.position;
475 //TextMetrics & tm = d->text_metrics_[&buffer_.text()];
476 if (abs(offset) <= 3*height_) {
482 for (size_t i = 0; i != d->par_height_.size(); ++i) {
483 par_pos += d->par_height_[i];
484 if (par_pos >= value) {
485 d->anchor_pit_ = pit_type(i);
490 LYXERR(Debug::SCROLLING, "value = " << value
491 << "\tanchor_ref_ = " << d->anchor_pit_
492 << "\tpar_pos = " << par_pos);
494 d->anchor_ypos_ = par_pos - value;
500 // FIXME: this method is not working well.
501 void BufferView::setCursorFromScrollbar()
503 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
505 int const height = 2 * defaultRowHeight();
506 int const first = height;
507 int const last = height_ - height;
508 Cursor & cur = d->cursor_;
510 switch (cursorStatus(cur)) {
512 // We reset the cursor because cursorStatus() does not
513 // work when the cursor is within mathed.
514 cur.reset(buffer_.inset());
515 tm.setCursorFromCoordinates(cur, 0, first);
516 cur.clearSelection();
519 // We reset the cursor because cursorStatus() does not
520 // work when the cursor is within mathed.
521 cur.reset(buffer_.inset());
522 tm.setCursorFromCoordinates(cur, 0, last);
523 cur.clearSelection();
526 int const y = getPos(cur, cur.boundary()).y_;
527 int const newy = min(last, max(y, first));
529 cur.reset(buffer_.inset());
530 tm.setCursorFromCoordinates(cur, 0, newy);
536 Change const BufferView::getCurrentChange() const
538 if (!d->cursor_.selection())
539 return Change(Change::UNCHANGED);
541 DocIterator dit = d->cursor_.selectionBegin();
542 return dit.paragraph().lookupChange(dit.pos());
546 // this could be used elsewhere as well?
547 // FIXME: This does not work within mathed!
548 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
550 Point const p = getPos(dit, dit.boundary());
553 if (p.y_ > workHeight())
559 void BufferView::saveBookmark(unsigned int idx)
561 // tenatively save bookmark, id and pos will be used to
562 // acturately locate a bookmark in a 'live' lyx session.
563 // pit and pos will be updated with bottom level pit/pos
565 LyX::ref().session().bookmarks().save(
567 d->cursor_.bottom().pit(),
568 d->cursor_.bottom().pos(),
569 d->cursor_.paragraph().id(),
574 // emit message signal.
575 message(_("Save bookmark"));
579 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
580 int top_id, pos_type top_pos)
582 bool success = false;
585 d->cursor_.clearSelection();
587 // if a valid par_id is given, try it first
588 // This is the case for a 'live' bookmark when unique paragraph ID
589 // is used to track bookmarks.
591 ParIterator par = buffer_.getParFromID(top_id);
592 if (par != buffer_.par_iterator_end()) {
593 doc_it = makeDocIterator(par, min(par->size(), top_pos));
594 // Some slices of the iterator may not be
595 // reachable (e.g. closed collapsable inset)
596 // so the dociterator may need to be
597 // shortened. Otherwise, setCursor may crash
598 // lyx when the cursor can not be set to these
600 size_t const n = doc_it.depth();
601 for (size_t i = 0; i < n; ++i)
602 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
610 // if top_id == 0, or searching through top_id failed
611 // This is the case for a 'restored' bookmark when only bottom
612 // (document level) pit was saved. Because of this, bookmark
613 // restoration is inaccurate. If a bookmark was within an inset,
614 // it will be restored to the left of the outmost inset that contains
616 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
617 doc_it = doc_iterator_begin(buffer_.inset());
618 doc_it.pit() = bottom_pit;
619 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
624 // Note: only bottom (document) level pit is set.
626 // set the current font.
627 d->cursor_.setCurrentFont();
628 // To center the screen on this new position we need the
629 // paragraph position which is computed at draw() time.
630 // So we need a redraw!
640 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
642 if (lyxrc.rtl_support) {
643 if (d->cursor_.real_current_font.isRightToLeft()) {
644 if (d->intl_.keymap == Intl::PRIMARY)
645 d->intl_.keyMapSec();
647 if (d->intl_.keymap == Intl::SECONDARY)
648 d->intl_.keyMapPrim();
652 d->intl_.getTransManager().translateAndInsert(c, t, cur);
656 int BufferView::workWidth() const
662 void BufferView::showCursor()
664 // We are not properly started yet, delay until resizing is
669 LYXERR(Debug::SCROLLING, "recentering!");
671 CursorSlice & bot = d->cursor_.bottom();
672 TextMetrics & tm = d->text_metrics_[bot.text()];
674 int const bot_pit = d->cursor_.bottom().pit();
675 if (bot_pit == tm.first().first - 1)
676 tm.newParMetricsUp();
677 else if (bot_pit == tm.last().first + 1)
678 tm.newParMetricsDown();
680 if (tm.has(bot_pit)) {
681 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
682 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
683 int ypos = pm.position() + offset;
684 Dimension const & row_dim = d->cursor_.textRow().dimension();
685 if (ypos - row_dim.ascent() < 0)
686 scrollUp(- ypos + row_dim.ascent());
687 else if (ypos + row_dim.descent() > height_)
688 scrollDown(ypos - height_ + row_dim.descent());
689 // else, nothing to do, the cursor is already visible so we just return.
693 tm.redoParagraph(bot_pit);
694 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
695 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
697 d->anchor_pit_ = bot_pit;
699 if (d->anchor_pit_ == 0)
700 d->anchor_ypos_ = offset + pm.ascent();
701 else if (d->anchor_pit_ >= pos_type(bot.text()->paragraphs().size() - 1)) {
702 d->anchor_pit_ = bot.text()->paragraphs().size() - 1;
703 d->anchor_ypos_ = offset + pm.height() - height_;
705 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
713 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
717 Cursor & cur = d->cursor_;
719 switch (cmd.action) {
722 flag.enabled(buffer_.undo().hasUndoStack());
725 flag.enabled(buffer_.undo().hasRedoStack());
727 case LFUN_FILE_INSERT:
728 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
729 case LFUN_FILE_INSERT_PLAINTEXT:
730 case LFUN_BOOKMARK_SAVE:
731 // FIXME: Actually, these LFUNS should be moved to Text
732 flag.enabled(cur.inTexted());
734 case LFUN_FONT_STATE:
735 case LFUN_LABEL_INSERT:
736 case LFUN_INFO_INSERT:
737 case LFUN_PARAGRAPH_GOTO:
739 case LFUN_REFERENCE_NEXT:
741 case LFUN_WORD_REPLACE:
744 case LFUN_MARK_TOGGLE:
745 case LFUN_SCREEN_RECENTER:
746 case LFUN_BIBTEX_DATABASE_ADD:
747 case LFUN_BIBTEX_DATABASE_DEL:
748 case LFUN_WORDS_COUNT:
749 case LFUN_NEXT_INSET_TOGGLE:
753 case LFUN_LABEL_GOTO: {
754 flag.enabled(!cmd.argument().empty()
755 || getInsetByCode<InsetRef>(cur, REF_CODE));
759 case LFUN_CHANGES_TRACK:
761 flag.setOnOff(buffer_.params().trackChanges);
764 case LFUN_CHANGES_OUTPUT:
766 flag.setOnOff(buffer_.params().outputChanges);
769 case LFUN_CHANGES_MERGE:
770 case LFUN_CHANGE_NEXT:
771 case LFUN_ALL_CHANGES_ACCEPT:
772 case LFUN_ALL_CHANGES_REJECT:
773 // TODO: context-sensitive enabling of LFUNs
774 // In principle, these command should only be enabled if there
775 // is a change in the document. However, without proper
776 // optimizations, this will inevitably result in poor performance.
780 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
781 flag.setOnOff(buffer_.params().compressed);
785 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
786 flag.setOnOff(buffer_.params().embedded);
791 case LFUN_SCREEN_DOWN:
795 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
796 // everywhere else before this can enabled:
797 case LFUN_SCREEN_UP_SELECT:
798 case LFUN_SCREEN_DOWN_SELECT:
802 case LFUN_LAYOUT_TABULAR:
803 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
807 case LFUN_LAYOUT_PARAGRAPH:
808 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
811 case LFUN_INSET_SETTINGS: {
812 InsetCode code = cur.inset().lyxCode();
816 enable = cmd.argument() == "tabular";
819 enable = cmd.argument() == "ert";
822 enable = cmd.argument() == "float";
825 enable = cmd.argument() == "wrap";
828 enable = cmd.argument() == "note";
831 enable = cmd.argument() == "branch";
834 enable = cmd.argument() == "box";
837 enable = cmd.argument() == "listings";
842 flag.enabled(enable);
846 case LFUN_DIALOG_SHOW_NEW_INSET:
847 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
848 cur.inset().lyxCode() != LISTINGS_CODE);
849 if (cur.inset().lyxCode() == CAPTION_CODE) {
851 if (cur.inset().getStatus(cur, cmd, flag))
864 Update::flags BufferView::dispatch(FuncRequest const & cmd)
866 //lyxerr << [ cmd = " << cmd << "]" << endl;
868 // Make sure that the cached BufferView is correct.
869 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
870 << " arg[" << to_utf8(cmd.argument()) << ']'
871 << " x[" << cmd.x << ']'
872 << " y[" << cmd.y << ']'
873 << " button[" << cmd.button() << ']');
875 Cursor & cur = d->cursor_;
876 // Default Update flags.
877 Update::flags updateFlags = Update::Force | Update::FitCursor;
879 switch (cmd.action) {
882 cur.message(_("Undo"));
883 cur.clearSelection();
884 if (!cur.textUndo()) {
885 cur.message(_("No further undo information"));
886 updateFlags = Update::None;
891 cur.message(_("Redo"));
892 cur.clearSelection();
893 if (!cur.textRedo()) {
894 cur.message(_("No further redo information"));
895 updateFlags = Update::None;
899 case LFUN_FONT_STATE:
900 cur.message(cur.currentState());
903 case LFUN_BOOKMARK_SAVE:
904 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
907 case LFUN_LABEL_GOTO: {
908 docstring label = cmd.argument();
911 getInsetByCode<InsetRef>(d->cursor_,
914 label = inset->getParam("reference");
915 // persistent=false: use temp_bookmark
925 case LFUN_PARAGRAPH_GOTO: {
926 int const id = convert<int>(to_utf8(cmd.argument()));
928 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
929 b = theBufferList().next(b)) {
931 ParIterator par = b->getParFromID(id);
932 if (par == b->par_iterator_end()) {
933 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
935 LYXERR(Debug::INFO, "Paragraph " << par->id()
936 << " found in buffer `"
937 << b->absFileName() << "'.");
941 setCursor(makeDocIterator(par, 0));
943 // Switch to other buffer view and resend cmd
944 theLyXFunc().dispatch(FuncRequest(
945 LFUN_BUFFER_SWITCH, b->absFileName()));
946 theLyXFunc().dispatch(cmd);
947 updateFlags = Update::None;
957 gotoInset(this, NOTE_CODE, false);
960 case LFUN_REFERENCE_NEXT: {
961 vector<InsetCode> tmp;
962 tmp.push_back(LABEL_CODE);
963 tmp.push_back(REF_CODE);
964 gotoInset(this, tmp, true);
968 case LFUN_CHANGES_TRACK:
969 buffer_.params().trackChanges = !buffer_.params().trackChanges;
972 case LFUN_CHANGES_OUTPUT:
973 buffer_.params().outputChanges = !buffer_.params().outputChanges;
974 if (buffer_.params().outputChanges) {
975 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
976 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
977 LaTeXFeatures::isAvailable("xcolor");
979 if (!dvipost && !xcolorsoul) {
980 Alert::warning(_("Changes not shown in LaTeX output"),
981 _("Changes will not be highlighted in LaTeX output, "
982 "because neither dvipost nor xcolor/soul are installed.\n"
983 "Please install these packages or redefine "
984 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
985 } else if (!xcolorsoul) {
986 Alert::warning(_("Changes not shown in LaTeX output"),
987 _("Changes will not be highlighted in LaTeX output "
988 "when using pdflatex, because xcolor and soul are not installed.\n"
989 "Please install both packages or redefine "
990 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
995 case LFUN_CHANGE_NEXT:
996 findNextChange(this);
999 case LFUN_CHANGES_MERGE:
1000 if (findNextChange(this))
1001 showDialog("changes");
1004 case LFUN_ALL_CHANGES_ACCEPT:
1005 // select complete document
1006 d->cursor_.reset(buffer_.inset());
1007 d->cursor_.selHandle(true);
1008 buffer_.text().cursorBottom(d->cursor_);
1009 // accept everything in a single step to support atomic undo
1010 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1013 case LFUN_ALL_CHANGES_REJECT:
1014 // select complete document
1015 d->cursor_.reset(buffer_.inset());
1016 d->cursor_.selHandle(true);
1017 buffer_.text().cursorBottom(d->cursor_);
1018 // reject everything in a single step to support atomic undo
1019 // Note: reject does not work recursively; the user may have to repeat the operation
1020 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1023 case LFUN_WORD_FIND:
1027 case LFUN_WORD_REPLACE: {
1028 bool has_deleted = false;
1029 if (cur.selection()) {
1030 DocIterator beg = cur.selectionBegin();
1031 DocIterator end = cur.selectionEnd();
1032 if (beg.pit() == end.pit()) {
1033 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1034 if (cur.paragraph().isDeleted(p))
1039 replace(this, cmd, has_deleted);
1044 cur.clearSelection();
1046 cur.message(from_utf8(N_("Mark off")));
1050 cur.clearSelection();
1053 cur.message(from_utf8(N_("Mark on")));
1056 case LFUN_MARK_TOGGLE:
1057 cur.clearSelection();
1060 cur.message(from_utf8(N_("Mark removed")));
1063 cur.message(from_utf8(N_("Mark set")));
1068 case LFUN_SCREEN_RECENTER:
1072 case LFUN_BIBTEX_DATABASE_ADD: {
1073 Cursor tmpcur = d->cursor_;
1074 findInset(tmpcur, BIBTEX_CODE, false);
1075 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1078 if (inset->addDatabase(to_utf8(cmd.argument())))
1079 buffer_.updateBibfilesCache();
1084 case LFUN_BIBTEX_DATABASE_DEL: {
1085 Cursor tmpcur = d->cursor_;
1086 findInset(tmpcur, BIBTEX_CODE, false);
1087 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1090 if (inset->delDatabase(to_utf8(cmd.argument())))
1091 buffer_.updateBibfilesCache();
1096 case LFUN_WORDS_COUNT: {
1097 DocIterator from, to;
1098 if (cur.selection()) {
1099 from = cur.selectionBegin();
1100 to = cur.selectionEnd();
1102 from = doc_iterator_begin(buffer_.inset());
1103 to = doc_iterator_end(buffer_.inset());
1105 int const count = countWords(from, to);
1108 if (cur.selection())
1109 message = bformat(_("%1$d words in selection."),
1112 message = bformat(_("%1$d words in document."),
1116 if (cur.selection())
1117 message = _("One word in selection.");
1119 message = _("One word in document.");
1122 Alert::information(_("Count words"), message);
1126 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1127 // turn compression on/off
1128 buffer_.params().compressed = !buffer_.params().compressed;
1131 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1132 // turn embedding on/off
1133 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1136 case LFUN_NEXT_INSET_TOGGLE: {
1137 // this is the real function we want to invoke
1138 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1139 // if there is an inset at cursor, see whether it
1141 Inset * inset = cur.nextInset();
1143 if (inset->isActive()) {
1144 Cursor tmpcur = cur;
1145 tmpcur.pushBackward(*inset);
1146 inset->dispatch(tmpcur, tmpcmd);
1147 if (tmpcur.result().dispatched()) {
1150 } else if (inset->editable() == Inset::IS_EDITABLE) {
1151 inset->edit(cur, true);
1154 // if it did not work, try the underlying inset.
1155 if (!cur.result().dispatched())
1156 cur.dispatch(tmpcmd);
1158 if (cur.result().dispatched())
1159 cur.clearSelection();
1164 case LFUN_SCREEN_UP:
1165 case LFUN_SCREEN_DOWN: {
1166 Point p = getPos(cur, cur.boundary());
1167 if (p.y_ < 0 || p.y_ > height_) {
1168 // The cursor is off-screen so recenter before proceeding.
1170 p = getPos(cur, cur.boundary());
1172 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1173 cur.reset(buffer_.inset());
1174 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1175 //FIXME: what to do with cur.x_target()?
1177 // The metrics are already up to date. see scroll()
1178 updateFlags = Update::None;
1182 case LFUN_SCREEN_UP_SELECT:
1183 case LFUN_SCREEN_DOWN_SELECT: {
1184 cur.selHandle(true);
1185 size_t initial_depth = cur.depth();
1186 Point const p = getPos(cur, cur.boundary());
1187 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1188 // FIXME: We need to verify if the cursor stayed within an inset...
1189 //cur.reset(buffer_.inset());
1190 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1192 while (cur.depth() > initial_depth) {
1195 // FIXME: we need to do a redraw again because of the selection
1196 // But no screen update is needed.
1197 d->update_strategy_ = NoScreenUpdate;
1199 updateFlags = Update::Force | Update::FitCursor;
1204 updateFlags = Update::None;
1211 docstring const BufferView::requestSelection()
1213 Cursor & cur = d->cursor_;
1215 if (!cur.selection()) {
1216 d->xsel_cache_.set = false;
1220 if (!d->xsel_cache_.set ||
1221 cur.top() != d->xsel_cache_.cursor ||
1222 cur.anchor_.top() != d->xsel_cache_.anchor)
1224 d->xsel_cache_.cursor = cur.top();
1225 d->xsel_cache_.anchor = cur.anchor_.top();
1226 d->xsel_cache_.set = cur.selection();
1227 return cur.selectionAsString(false);
1233 void BufferView::clearSelection()
1235 d->cursor_.clearSelection();
1236 // Clear the selection buffer. Otherwise a subsequent
1237 // middle-mouse-button paste would use the selection buffer,
1238 // not the more current external selection.
1239 cap::clearSelection();
1240 d->xsel_cache_.set = false;
1241 // The buffer did not really change, but this causes the
1242 // redraw we need because we cleared the selection above.
1247 void BufferView::resize(int width, int height)
1249 // Update from work area
1253 // Clear the paragraph height cache.
1254 d->par_height_.clear();
1260 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1262 TextMetrics & tm = d->text_metrics_[&text];
1263 Inset * inset = tm.checkInsetHit(x, y);
1267 if (!inset->descendable())
1268 // No need to go further down if the inset is not
1272 size_t cell_number = inset->nargs();
1273 // Check all the inner cell.
1274 for (size_t i = 0; i != cell_number; ++i) {
1275 Text const * inner_text = inset->getText(i);
1278 Inset const * inset_deeper =
1279 getCoveringInset(*inner_text, x, y);
1281 return inset_deeper;
1289 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1291 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1293 // This is only called for mouse related events including
1294 // LFUN_FILE_OPEN generated by drag-and-drop.
1295 FuncRequest cmd = cmd0;
1298 cur.push(buffer_.inset());
1299 cur.selection() = d->cursor_.selection();
1301 // Either the inset under the cursor or the
1302 // surrounding Text will handle this event.
1304 // make sure we stay within the screen...
1305 cmd.y = min(max(cmd.y, -1), height_);
1307 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1309 // Get inset under mouse, if there is one.
1310 Inset const * covering_inset =
1311 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1312 if (covering_inset == d->last_inset_)
1313 // Same inset, no need to do anything...
1316 bool need_redraw = false;
1317 // const_cast because of setMouseHover().
1318 Inset * inset = const_cast<Inset *>(covering_inset);
1320 // Remove the hint on the last hovered inset (if any).
1321 need_redraw |= d->last_inset_->setMouseHover(false);
1323 // Highlighted the newly hovered inset (if any).
1324 need_redraw |= inset->setMouseHover(true);
1325 d->last_inset_ = inset;
1329 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1330 << cmd.x << ", " << cmd.y << ")");
1332 d->update_strategy_ = DecorationUpdate;
1334 // This event (moving without mouse click) is not passed further.
1335 // This should be changed if it is further utilized.
1340 // Build temporary cursor.
1341 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1343 // Put anchor at the same position.
1346 // Try to dispatch to an non-editable inset near this position
1347 // via the temp cursor. If the inset wishes to change the real
1348 // cursor it has to do so explicitly by using
1349 // cur.bv().cursor() = cur; (or similar)
1351 inset->dispatch(cur, cmd);
1353 // Now dispatch to the temporary cursor. If the real cursor should
1354 // be modified, the inset's dispatch has to do so explicitly.
1355 if (!cur.result().dispatched())
1358 //Do we have a selection?
1359 theSelection().haveSelection(cursor().selection());
1361 // If the command has been dispatched,
1362 if (cur.result().dispatched()
1363 // an update is asked,
1364 && cur.result().update())
1365 processUpdateFlags(cur.result().update());
1369 void BufferView::scroll(int y)
1378 void BufferView::scrollDown(int offset)
1380 Text * text = &buffer_.text();
1381 TextMetrics & tm = d->text_metrics_[text];
1382 int ymax = height_ + offset;
1384 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1385 int bottom_pos = last.second->position() + last.second->descent();
1386 if (last.first + 1 == int(text->paragraphs().size())) {
1387 if (bottom_pos <= height_)
1389 offset = min(offset, bottom_pos - height_);
1392 if (bottom_pos > ymax)
1394 tm.newParMetricsDown();
1396 d->anchor_ypos_ -= offset;
1402 void BufferView::scrollUp(int offset)
1404 Text * text = &buffer_.text();
1405 TextMetrics & tm = d->text_metrics_[text];
1406 int ymin = - offset;
1408 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1409 int top_pos = first.second->position() - first.second->ascent();
1410 if (first.first == 0) {
1413 offset = min(offset, - top_pos);
1418 tm.newParMetricsUp();
1420 d->anchor_ypos_ += offset;
1426 void BufferView::setCursorFromRow(int row)
1431 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1433 d->cursor_.reset(buffer_.inset());
1435 buffer_.text().setCursor(d->cursor_, 0, 0);
1437 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1441 void BufferView::gotoLabel(docstring const & label)
1443 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1444 vector<docstring> labels;
1445 it->getLabelList(buffer_, labels);
1446 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1448 processUpdateFlags(Update::FitCursor);
1455 TextMetrics const & BufferView::textMetrics(Text const * t) const
1457 return const_cast<BufferView *>(this)->textMetrics(t);
1461 TextMetrics & BufferView::textMetrics(Text const * t)
1463 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1464 if (tmc_it == d->text_metrics_.end()) {
1465 tmc_it = d->text_metrics_.insert(
1466 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1468 return tmc_it->second;
1472 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1475 return textMetrics(t).parMetrics(pit);
1479 int BufferView::workHeight() const
1485 void BufferView::setCursor(DocIterator const & dit)
1487 size_t const n = dit.depth();
1488 for (size_t i = 0; i < n; ++i)
1489 dit[i].inset().edit(d->cursor_, true);
1491 d->cursor_.setCursor(dit);
1492 d->cursor_.selection() = false;
1496 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1498 // Would be wrong to delete anything if we have a selection.
1499 if (cur.selection())
1502 bool need_anchor_change = false;
1503 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1504 need_anchor_change);
1506 if (need_anchor_change)
1512 updateLabels(buffer_);
1520 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1522 BOOST_ASSERT(&cur.bv() == this);
1525 // this event will clear selection so we save selection for
1526 // persistent selection
1527 cap::saveSelection(cursor());
1529 // Has the cursor just left the inset?
1530 bool badcursor = false;
1531 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1533 badcursor = notifyCursorLeaves(d->cursor_, cur);
1535 // FIXME: shift-mouse selection doesn't work well across insets.
1536 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1538 // do the dEPM magic if needed
1539 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1540 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1541 // the leftinset bool would not be necessary (badcursor instead).
1542 bool update = leftinset;
1543 if (!do_selection && !badcursor && d->cursor_.inTexted())
1544 update |= checkDepm(cur, d->cursor_);
1546 // if the cursor was in an empty script inset and the new
1547 // position is in the nucleus of the inset, notifyCursorLeaves
1548 // will kill the script inset itself. So we check all the
1549 // elements of the cursor to make sure that they are correct.
1550 // For an example, see bug 2933:
1551 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1552 // The code below could maybe be moved to a DocIterator method.
1553 //lyxerr << "cur before " << cur <<endl;
1554 DocIterator dit(cur.inset());
1555 dit.push_back(cur.bottom());
1557 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1558 dit.push_back(cur[i]);
1561 //lyxerr << "5 cur after" << dit <<endl;
1563 d->cursor_.setCursor(dit);
1564 d->cursor_.boundary(cur.boundary());
1566 d->cursor_.setSelection();
1568 d->cursor_.clearSelection();
1570 d->cursor_.finishUndo();
1571 d->cursor_.setCurrentFont();
1576 void BufferView::putSelectionAt(DocIterator const & cur,
1577 int length, bool backwards)
1579 d->cursor_.clearSelection();
1585 d->cursor_.pos() += length;
1586 d->cursor_.setSelection(d->cursor_, -length);
1588 d->cursor_.setSelection(d->cursor_, length);
1593 Cursor & BufferView::cursor()
1599 Cursor const & BufferView::cursor() const
1605 pit_type BufferView::anchor_ref() const
1607 return d->anchor_pit_;
1611 bool BufferView::singleParUpdate()
1613 Text & buftext = buffer_.text();
1614 pit_type const bottom_pit = d->cursor_.bottom().pit();
1615 TextMetrics & tm = textMetrics(&buftext);
1616 int old_height = tm.parMetrics(bottom_pit).height();
1618 // In Single Paragraph mode, rebreak only
1619 // the (main text, not inset!) paragraph containing the cursor.
1620 // (if this paragraph contains insets etc., rebreaking will
1621 // recursively descend)
1622 tm.redoParagraph(bottom_pit);
1623 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1624 if (pm.height() != old_height)
1625 // Paragraph height has changed so we cannot proceed to
1626 // the singlePar optimisation.
1629 d->update_strategy_ = SingleParUpdate;
1631 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1632 << " y2: " << pm.position() + pm.descent()
1633 << " pit: " << bottom_pit
1634 << " singlepar: 1");
1639 void BufferView::updateMetrics()
1641 Text & buftext = buffer_.text();
1642 pit_type const npit = int(buftext.paragraphs().size());
1644 // Clear out the position cache in case of full screen redraw,
1645 d->coord_cache_.clear();
1647 // Clear out paragraph metrics to avoid having invalid metrics
1648 // in the cache from paragraphs not relayouted below
1649 // The complete text metrics will be redone.
1650 d->text_metrics_.clear();
1652 TextMetrics & tm = textMetrics(&buftext);
1654 // Rebreak anchor paragraph.
1655 tm.redoParagraph(d->anchor_pit_);
1656 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1657 anchor_pm.setPosition(d->anchor_ypos_);
1659 LYXERR(Debug::PAINTING, "metrics: "
1660 << " anchor pit = " << d->anchor_pit_
1661 << " anchor ypos = " << d->anchor_ypos_);
1663 // Redo paragraphs above anchor if necessary.
1664 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1665 // We are now just above the anchor paragraph.
1666 pit_type pit1 = d->anchor_pit_ - 1;
1667 for (; pit1 >= 0 && y1 > 0; --pit1) {
1668 tm.redoParagraph(pit1);
1669 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1671 // Save the paragraph position in the cache.
1676 // Redo paragraphs below the anchor if necessary.
1677 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1678 // We are now just below the anchor paragraph.
1679 pit_type pit2 = d->anchor_pit_ + 1;
1680 for (; pit2 < npit && y2 < height_; ++pit2) {
1681 tm.redoParagraph(pit2);
1682 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1684 // Save the paragraph position in the cache.
1689 LYXERR(Debug::PAINTING, "Metrics: "
1690 << " anchor pit = " << d->anchor_pit_
1691 << " anchor ypos = " << d->anchor_ypos_
1694 << " pit1 = " << pit1
1695 << " pit2 = " << pit2);
1697 d->update_strategy_ = FullScreenUpdate;
1699 if (lyxerr.debugging(Debug::WORKAREA)) {
1700 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1701 d->coord_cache_.dump();
1706 void BufferView::insertLyXFile(FileName const & fname)
1708 BOOST_ASSERT(d->cursor_.inTexted());
1710 // Get absolute path of file and add ".lyx"
1711 // to the filename if necessary
1712 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1714 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1715 // emit message signal.
1716 message(bformat(_("Inserting document %1$s..."), disp_fn));
1719 Buffer buf("", false);
1720 if (buf.loadLyXFile(filename)) {
1721 ErrorList & el = buffer_.errorList("Parse");
1722 // Copy the inserted document error list into the current buffer one.
1723 el = buf.errorList("Parse");
1724 buffer_.undo().recordUndo(d->cursor_);
1725 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1726 buf.params().getTextClassPtr(), el);
1727 res = _("Document %1$s inserted.");
1729 res = _("Could not insert document %1$s");
1734 // emit message signal.
1735 message(bformat(res, disp_fn));
1736 buffer_.errors("Parse");
1740 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1746 // Addup contribution of nested insets, from inside to outside,
1747 // keeping the outer paragraph for a special handling below
1748 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1749 CursorSlice const & sl = dit[i];
1753 // get relative position inside sl.inset()
1754 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1756 // Make relative position inside of the edited inset relative to sl.inset()
1760 // In case of an RTL inset, the edited inset will be positioned to the left
1763 bool boundary_i = boundary && i + 1 == dit.depth();
1764 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1769 // remember width for the case that sl.inset() is positioned in an RTL inset
1770 if (i && dit[i - 1].text()) {
1771 // If this Inset is inside a Text Inset, retrieve the Dimension
1772 // from the containing text instead of using Inset::dimension() which
1773 // might not be implemented.
1774 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1775 // elimination of Inset::dim_ cache. This coordOffset() method needs
1776 // to be rewritten in light of the new design.
1777 Dimension const & dim = parMetrics(dit[i - 1].text(),
1778 dit[i - 1].pit()).insetDimension(&sl.inset());
1781 Dimension const dim = sl.inset().dimension(*this);
1785 //lyxerr << "Cursor::getPos, i: "
1786 // << i << " x: " << xx << " y: " << y << endl;
1789 // Add contribution of initial rows of outermost paragraph
1790 CursorSlice const & sl = dit[0];
1791 TextMetrics const & tm = textMetrics(sl.text());
1792 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1793 BOOST_ASSERT(!pm.rows().empty());
1794 y -= pm.rows()[0].ascent();
1796 // FIXME: document this mess
1798 if (sl.pos() > 0 && dit.depth() == 1) {
1800 if (pos && boundary)
1802 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1803 rend = pm.pos2row(pos);
1805 rend = pm.pos2row(sl.pos());
1807 size_t rend = pm.pos2row(sl.pos());
1809 for (size_t rit = 0; rit != rend; ++rit)
1810 y += pm.rows()[rit].height();
1811 y += pm.rows()[rend].ascent();
1813 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1815 // Make relative position from the nested inset now bufferview absolute.
1816 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1819 // In the RTL case place the nested inset at the left of the cursor in
1820 // the outer paragraph
1821 bool boundary_1 = boundary && 1 == dit.depth();
1822 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1830 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1832 CursorSlice const & bot = dit.bottom();
1833 TextMetrics const & tm = textMetrics(bot.text());
1834 if (!tm.has(bot.pit()))
1835 return Point(-1, -1);
1837 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1838 p.y_ += tm.parMetrics(bot.pit()).position();
1843 void BufferView::draw(frontend::Painter & pain)
1845 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1846 Text & text = buffer_.text();
1847 TextMetrics const & tm = d->text_metrics_[&text];
1848 int const y = tm.first().second->position();
1849 PainterInfo pi(this, pain);
1851 switch (d->update_strategy_) {
1853 case NoScreenUpdate:
1854 // If no screen painting is actually needed, only some the different
1855 // coordinates of insets and paragraphs needs to be updated.
1856 pi.full_repaint = true;
1857 pi.pain.setDrawingEnabled(false);
1861 case SingleParUpdate:
1862 pi.full_repaint = false;
1863 // In general, only the current row of the outermost paragraph
1864 // will be redrawn. Particular cases where selection spans
1865 // multiple paragraph are correctly detected in TextMetrics.
1869 case DecorationUpdate:
1870 // FIXME: We should also distinguish DecorationUpdate to avoid text
1871 // drawing if possible. This is not possible to do easily right now
1872 // because of the single backing pixmap.
1874 case FullScreenUpdate:
1875 // The whole screen, including insets, will be refreshed.
1876 pi.full_repaint = true;
1878 // Clear background.
1879 pain.fillRectangle(0, 0, width_, height_,
1880 buffer_.inset().backgroundColor());
1885 // and possibly grey out below
1886 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1887 int const y2 = lastpm.second->position() + lastpm.second->descent();
1889 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1892 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1894 // The scrollbar needs an update.
1897 // Normalize anchor for next time
1898 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1899 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1900 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1901 ParagraphMetrics const & pm = tm.parMetrics(pit);
1902 if (pm.position() + pm.descent() > 0) {
1903 d->anchor_pit_ = pit;
1904 d->anchor_ypos_ = pm.position();
1908 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1909 << " anchor ypos = " << d->anchor_ypos_);
1913 void BufferView::message(docstring const & msg)
1916 d->gui_->message(msg);
1920 void BufferView::showDialog(string const & name)
1923 d->gui_->showDialog(name, string());
1927 void BufferView::showDialog(string const & name,
1928 string const & data, Inset * inset)
1931 d->gui_->showDialog(name, data, inset);
1935 void BufferView::updateDialog(string const & name, string const & data)
1938 d->gui_->updateDialog(name, data);
1942 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1948 // FIXME: Move this out of BufferView again
1949 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1951 if (!fname.isReadableFile()) {
1952 docstring const error = from_ascii(strerror(errno));
1953 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1954 docstring const text =
1955 bformat(_("Could not read the specified document\n"
1956 "%1$s\ndue to the error: %2$s"), file, error);
1957 Alert::error(_("Could not read file"), text);
1961 if (!fname.isReadableFile()) {
1962 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1963 docstring const text =
1964 bformat(_("%1$s\n is not readable."), file);
1965 Alert::error(_("Could not open file"), text);
1969 // FIXME UNICODE: We don't know the encoding of the file
1970 docstring file_content = fname.fileContents("UTF-8");
1971 if (file_content.empty()) {
1972 Alert::error(_("Reading not UTF-8 encoded file"),
1973 _("The file is not UTF-8 encoded.\n"
1974 "It will be read as local 8Bit-encoded.\n"
1975 "If this does not give the correct result\n"
1976 "then please change the encoding of the file\n"
1977 "to UTF-8 with a program other than LyX.\n"));
1978 file_content = fname.fileContents("local8bit");
1981 return normalize_c(file_content);
1985 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
1987 docstring const tmpstr = contentsOfPlaintextFile(f);
1992 Cursor & cur = cursor();
1993 cap::replaceSelection(cur);
1994 buffer_.undo().recordUndo(cur);
1996 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
1998 cur.innerText()->insertStringAsLines(cur, tmpstr);