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/Application.h"
62 #include "frontends/Delegates.h"
63 #include "frontends/FontMetrics.h"
64 #include "frontends/Painter.h"
65 #include "frontends/Selection.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/debug.h"
71 #include "support/FileFilterList.h"
72 #include "support/filetools.h"
73 #include "support/gettext.h"
74 #include "support/lstrings.h"
75 #include "support/Package.h"
76 #include "support/types.h"
85 using namespace lyx::support;
89 namespace Alert = frontend::Alert;
93 /// Return an inset of this class if it exists at the current cursor position
95 T * getInsetByCode(Cursor const & cur, InsetCode code)
98 Inset * inset = it.nextInset();
99 if (inset && inset->lyxCode() == code)
100 return static_cast<T*>(inset);
105 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
108 bool findNextInset(DocIterator & dit, vector<InsetCode> const & codes,
109 docstring const & contents)
111 DocIterator tmpdit = dit;
114 Inset const * inset = tmpdit.nextInset();
116 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
117 && (contents.empty() ||
118 static_cast<InsetCommand const *>(inset)->getFirstNonOptParam() == contents)) {
122 tmpdit.forwardInset();
129 /// Looks for next inset with one of the given codes.
130 bool findInset(DocIterator & dit, vector<InsetCode> const & codes,
134 DocIterator tmpdit = dit;
135 tmpdit.forwardInset();
140 Inset const * inset = tmpdit.nextInset();
142 && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
143 contents = static_cast<InsetCommand const *>(inset)->getFirstNonOptParam();
147 if (!findNextInset(tmpdit, codes, contents)) {
148 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
149 tmpdit = doc_iterator_begin(tmpdit.bottom().inset());
150 if (!findNextInset(tmpdit, codes, contents))
161 /// Looks for next inset with the given code
162 void findInset(DocIterator & dit, InsetCode code, bool same_content)
164 findInset(dit, vector<InsetCode>(1, code), same_content);
168 /// Moves cursor to the next inset with one of the given codes.
169 void gotoInset(BufferView * bv, vector<InsetCode> const & codes,
172 Cursor tmpcur = bv->cursor();
173 if (!findInset(tmpcur, codes, same_content)) {
174 bv->cursor().message(_("No more insets"));
178 tmpcur.clearSelection();
179 bv->setCursor(tmpcur);
184 /// Moves cursor to the next inset with given code.
185 void gotoInset(BufferView * bv, InsetCode code, bool same_content)
187 gotoInset(bv, vector<InsetCode>(1, code), same_content);
191 /// A map from a Text to the associated text metrics
192 typedef map<Text const *, TextMetrics> TextMetricsCache;
194 enum ScreenUpdateStrategy {
204 /////////////////////////////////////////////////////////////////////
208 /////////////////////////////////////////////////////////////////////
210 struct BufferView::Private
212 Private(BufferView & bv): wh_(0), cursor_(bv),
213 anchor_pit_(0), anchor_ypos_(0),
214 last_inset_(0), gui_(0)
218 ScrollbarParameters scrollbarParameters_;
220 ScreenUpdateStrategy update_strategy_;
222 CoordCache coord_cache_;
224 /// Estimated average par height for scrollbar.
226 /// this is used to handle XSelection events in the right manner.
235 pit_type anchor_pit_;
239 vector<int> par_height_;
241 /// keyboard mapping object.
244 /// last visited inset.
245 /** kept to send setMouseHover(false).
246 * Not owned, so don't delete.
250 mutable TextMetricsCache text_metrics_;
253 /** Not owned, so don't delete.
255 frontend::GuiBufferViewDelegate * gui_;
259 BufferView::BufferView(Buffer & buf)
260 : width_(0), height_(0), buffer_(buf), d(new Private(*this))
262 d->xsel_cache_.set = false;
263 d->intl_.initKeyMapper(lyxrc.use_kbmap);
265 d->cursor_.push(buffer_.inset());
266 d->cursor_.resetAnchor();
267 d->cursor_.setCurrentFont();
269 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
270 graphics::Previews::get().generateBufferPreviews(buffer_);
274 BufferView::~BufferView()
276 // current buffer is going to be switched-off, save cursor pos
277 // Ideally, the whole cursor stack should be saved, but session
278 // currently can only handle bottom (whole document) level pit and pos.
279 // That is to say, if a cursor is in a nested inset, it will be
280 // restore to the left of the top level inset.
281 LastFilePosSection::FilePos fp;
282 fp.pit = d->cursor_.bottom().pit();
283 fp.pos = d->cursor_.bottom().pos();
284 LyX::ref().session().lastFilePos().save(buffer_.fileName(), fp);
290 Intl & BufferView::getIntl()
296 Intl const & BufferView::getIntl() const
302 CoordCache & BufferView::coordCache()
304 return d->coord_cache_;
308 CoordCache const & BufferView::coordCache() const
310 return d->coord_cache_;
314 Buffer & BufferView::buffer()
320 Buffer const & BufferView::buffer() const
326 bool BufferView::fitCursor()
328 if (cursorStatus(d->cursor_) == CUR_INSIDE) {
329 frontend::FontMetrics const & fm =
330 theFontMetrics(d->cursor_.getFont().fontInfo());
331 int const asc = fm.maxAscent();
332 int const des = fm.maxDescent();
333 Point const p = getPos(d->cursor_, d->cursor_.boundary());
334 if (p.y_ - asc >= 0 && p.y_ + des < height_)
341 void BufferView::processUpdateFlags(Update::flags flags)
343 // last_inset_ points to the last visited inset. This pointer may become
344 // invalid because of keyboard editing. Since all such operations
345 // causes screen update(), I reset last_inset_ to avoid such a problem.
347 // This is close to a hot-path.
348 LYXERR(Debug::DEBUG, "BufferView::processUpdateFlags()"
349 << "[fitcursor = " << (flags & Update::FitCursor)
350 << ", forceupdate = " << (flags & Update::Force)
351 << ", singlepar = " << (flags & Update::SinglePar)
352 << "] buffer: " << &buffer_);
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());
428 if (d->par_height_.size() != parsize) {
429 d->par_height_.clear();
430 // FIXME: We assume a default paragraph height of 2 rows. This
431 // should probably be pondered with the screen width.
432 d->par_height_.resize(parsize, defaultRowHeight() * 2);
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)
447 first_visible_pit = pit;
448 LYXERR(Debug::SCROLLING, "first visible pit " << first_visible_pit);
449 // FIXME: we should look for the first visible row within
450 // the deepest inset!
451 int row_pos = pm.position();
452 size_t const nrows = pm.rows().size();
453 for (size_t i = 0; i != nrows; ++i) {
454 Row const & row = pm.rows()[i];
456 LYXERR(Debug::SCROLLING, "first visible row " << i
457 << "(row pos = " << row_pos << ");");
460 row_pos += row.height();
462 d->scrollbarParameters_.position = row_pos;
465 d->scrollbarParameters_.height = 0;
466 for (size_t i = 0; i != d->par_height_.size(); ++i) {
467 if (i == first_visible_pit)
468 d->scrollbarParameters_.position += d->scrollbarParameters_.height;
469 d->scrollbarParameters_.height += d->par_height_[i];
472 // We prefer fixed size line scrolling.
473 d->scrollbarParameters_.lineScrollHeight = defaultRowHeight();
477 ScrollbarParameters const & BufferView::scrollbarParameters() const
479 return d->scrollbarParameters_;
483 docstring BufferView::toolTip(int x, int y) const
485 // Get inset under mouse, if there is one.
486 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
488 // No inset, no tooltip...
490 return covering_inset->toolTip(*this, x, y);
494 docstring BufferView::contextMenu(int x, int y) const
496 // Get inset under mouse, if there is one.
497 Inset const * covering_inset = getCoveringInset(buffer_.text(), x, y);
499 return covering_inset->contextMenu(*this, x, y);
501 // FIXME: Do something more elaborate here.
502 return from_ascii("edit");
506 void BufferView::scrollDocView(int value)
508 int const offset = value - d->scrollbarParameters_.position;
509 // If the offset is less than 2 screen height, prefer to scroll instead.
510 if (abs(offset) <= 2 * height_) {
516 for (size_t i = 0; i != d->par_height_.size(); ++i) {
517 par_pos += d->par_height_[i];
518 if (par_pos >= value) {
519 d->anchor_pit_ = pit_type(i);
524 LYXERR(Debug::SCROLLING, "value = " << value
525 << "\tanchor_ref_ = " << d->anchor_pit_
526 << "\tpar_pos = " << par_pos);
528 d->anchor_ypos_ = par_pos - value;
534 // FIXME: this method is not working well.
535 void BufferView::setCursorFromScrollbar()
537 TextMetrics & tm = d->text_metrics_[&buffer_.text()];
539 int const height = 2 * defaultRowHeight();
540 int const first = height;
541 int const last = height_ - height;
542 Cursor & cur = d->cursor_;
544 switch (cursorStatus(cur)) {
546 // We reset the cursor because cursorStatus() does not
547 // work when the cursor is within mathed.
548 cur.reset(buffer_.inset());
549 tm.setCursorFromCoordinates(cur, 0, first);
550 cur.clearSelection();
553 // We reset the cursor because cursorStatus() does not
554 // work when the cursor is within mathed.
555 cur.reset(buffer_.inset());
556 tm.setCursorFromCoordinates(cur, 0, last);
557 cur.clearSelection();
560 int const y = getPos(cur, cur.boundary()).y_;
561 int const newy = min(last, max(y, first));
563 cur.reset(buffer_.inset());
564 tm.setCursorFromCoordinates(cur, 0, newy);
570 Change const BufferView::getCurrentChange() const
572 if (!d->cursor_.selection())
573 return Change(Change::UNCHANGED);
575 DocIterator dit = d->cursor_.selectionBegin();
576 return dit.paragraph().lookupChange(dit.pos());
580 // this could be used elsewhere as well?
581 // FIXME: This does not work within mathed!
582 CursorStatus BufferView::cursorStatus(DocIterator const & dit) const
584 Point const p = getPos(dit, dit.boundary());
587 if (p.y_ > workHeight())
593 void BufferView::saveBookmark(unsigned int idx)
595 // tenatively save bookmark, id and pos will be used to
596 // acturately locate a bookmark in a 'live' lyx session.
597 // pit and pos will be updated with bottom level pit/pos
599 LyX::ref().session().bookmarks().save(
601 d->cursor_.bottom().pit(),
602 d->cursor_.bottom().pos(),
603 d->cursor_.paragraph().id(),
608 // emit message signal.
609 message(_("Save bookmark"));
613 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
614 int top_id, pos_type top_pos)
616 bool success = false;
619 d->cursor_.clearSelection();
621 // if a valid par_id is given, try it first
622 // This is the case for a 'live' bookmark when unique paragraph ID
623 // is used to track bookmarks.
625 ParIterator par = buffer_.getParFromID(top_id);
626 if (par != buffer_.par_iterator_end()) {
627 doc_it = makeDocIterator(par, min(par->size(), top_pos));
628 // Some slices of the iterator may not be
629 // reachable (e.g. closed collapsable inset)
630 // so the dociterator may need to be
631 // shortened. Otherwise, setCursor may crash
632 // lyx when the cursor can not be set to these
634 size_t const n = doc_it.depth();
635 for (size_t i = 0; i < n; ++i)
636 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
644 // if top_id == 0, or searching through top_id failed
645 // This is the case for a 'restored' bookmark when only bottom
646 // (document level) pit was saved. Because of this, bookmark
647 // restoration is inaccurate. If a bookmark was within an inset,
648 // it will be restored to the left of the outmost inset that contains
650 if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
651 doc_it = doc_iterator_begin(buffer_.inset());
652 doc_it.pit() = bottom_pit;
653 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
658 // Note: only bottom (document) level pit is set.
660 // set the current font.
661 d->cursor_.setCurrentFont();
662 // To center the screen on this new position we need the
663 // paragraph position which is computed at draw() time.
664 // So we need a redraw!
674 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
676 if (lyxrc.rtl_support) {
677 if (d->cursor_.real_current_font.isRightToLeft()) {
678 if (d->intl_.keymap == Intl::PRIMARY)
679 d->intl_.keyMapSec();
681 if (d->intl_.keymap == Intl::SECONDARY)
682 d->intl_.keyMapPrim();
686 d->intl_.getTransManager().translateAndInsert(c, t, cur);
690 int BufferView::workWidth() const
696 void BufferView::showCursor()
698 // We are not properly started yet, delay until resizing is
703 LYXERR(Debug::SCROLLING, "recentering!");
705 CursorSlice & bot = d->cursor_.bottom();
706 TextMetrics & tm = d->text_metrics_[bot.text()];
708 pos_type const max_pit = pos_type(bot.text()->paragraphs().size() - 1);
709 int bot_pit = d->cursor_.bottom().pit();
710 if (bot_pit > max_pit) {
711 // FIXME: Why does this happen?
712 LYXERR0("bottom pit is greater that max pit: "
713 << bot_pit << " > " << max_pit);
717 if (bot_pit == tm.first().first - 1)
718 tm.newParMetricsUp();
719 else if (bot_pit == tm.last().first + 1)
720 tm.newParMetricsDown();
722 if (tm.has(bot_pit)) {
723 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
724 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
725 int ypos = pm.position() + offset;
726 Dimension const & row_dim = d->cursor_.textRow().dimension();
727 if (ypos - row_dim.ascent() < 0)
728 scrollUp(- ypos + row_dim.ascent());
729 else if (ypos + row_dim.descent() > height_)
730 scrollDown(ypos - height_ + row_dim.descent());
731 // else, nothing to do, the cursor is already visible so we just return.
735 tm.redoParagraph(bot_pit);
736 ParagraphMetrics const & pm = tm.parMetrics(bot_pit);
737 int offset = coordOffset(d->cursor_, d->cursor_.boundary()).y_;
739 d->anchor_pit_ = bot_pit;
740 Dimension const & row_dim = d->cursor_.textRow().dimension();
742 if (d->anchor_pit_ == 0)
743 d->anchor_ypos_ = offset + pm.ascent();
744 else if (d->anchor_pit_ == max_pit)
745 d->anchor_ypos_ = height_ - offset - row_dim.descent();
747 d->anchor_ypos_ = offset + pm.ascent() - height_ / 2;
754 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
758 Cursor & cur = d->cursor_;
760 switch (cmd.action) {
763 flag.enabled(buffer_.undo().hasUndoStack());
766 flag.enabled(buffer_.undo().hasRedoStack());
768 case LFUN_FILE_INSERT:
769 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
770 case LFUN_FILE_INSERT_PLAINTEXT:
771 case LFUN_BOOKMARK_SAVE:
772 // FIXME: Actually, these LFUNS should be moved to Text
773 flag.enabled(cur.inTexted());
775 case LFUN_FONT_STATE:
776 case LFUN_LABEL_INSERT:
777 case LFUN_INFO_INSERT:
778 case LFUN_PARAGRAPH_GOTO:
780 case LFUN_REFERENCE_NEXT:
782 case LFUN_WORD_REPLACE:
785 case LFUN_MARK_TOGGLE:
786 case LFUN_SCREEN_RECENTER:
787 case LFUN_BIBTEX_DATABASE_ADD:
788 case LFUN_BIBTEX_DATABASE_DEL:
789 case LFUN_WORDS_COUNT:
790 case LFUN_NEXT_INSET_TOGGLE:
794 case LFUN_LABEL_GOTO: {
795 flag.enabled(!cmd.argument().empty()
796 || getInsetByCode<InsetRef>(cur, REF_CODE));
800 case LFUN_CHANGES_TRACK:
802 flag.setOnOff(buffer_.params().trackChanges);
805 case LFUN_CHANGES_OUTPUT:
807 flag.setOnOff(buffer_.params().outputChanges);
810 case LFUN_CHANGES_MERGE:
811 case LFUN_CHANGE_NEXT:
812 case LFUN_ALL_CHANGES_ACCEPT:
813 case LFUN_ALL_CHANGES_REJECT:
814 // TODO: context-sensitive enabling of LFUNs
815 // In principle, these command should only be enabled if there
816 // is a change in the document. However, without proper
817 // optimizations, this will inevitably result in poor performance.
821 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
822 flag.setOnOff(buffer_.params().compressed);
826 case LFUN_BUFFER_TOGGLE_EMBEDDING: {
827 flag.setOnOff(buffer_.params().embedded);
832 case LFUN_SCREEN_DOWN:
836 // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
837 // everywhere else before this can enabled:
838 case LFUN_SCREEN_UP_SELECT:
839 case LFUN_SCREEN_DOWN_SELECT:
843 case LFUN_LAYOUT_TABULAR:
844 flag.enabled(cur.innerInsetOfType(TABULAR_CODE));
848 case LFUN_LAYOUT_PARAGRAPH:
849 flag.enabled(cur.inset().forceDefaultParagraphs(cur.idx()));
852 case LFUN_INSET_SETTINGS: {
853 InsetCode code = cur.inset().lyxCode();
857 enable = cmd.argument() == "tabular";
860 enable = cmd.argument() == "ert";
863 enable = cmd.argument() == "float";
866 enable = cmd.argument() == "wrap";
869 enable = cmd.argument() == "note";
872 enable = cmd.argument() == "branch";
875 enable = cmd.argument() == "box";
878 enable = cmd.argument() == "listings";
883 flag.enabled(enable);
887 case LFUN_DIALOG_SHOW_NEW_INSET:
888 flag.enabled(cur.inset().lyxCode() != ERT_CODE &&
889 cur.inset().lyxCode() != LISTINGS_CODE);
890 if (cur.inset().lyxCode() == CAPTION_CODE) {
892 if (cur.inset().getStatus(cur, cmd, flag))
905 bool BufferView::dispatch(FuncRequest const & cmd)
907 //lyxerr << [ cmd = " << cmd << "]" << endl;
909 // Make sure that the cached BufferView is correct.
910 LYXERR(Debug::ACTION, " action[" << cmd.action << ']'
911 << " arg[" << to_utf8(cmd.argument()) << ']'
912 << " x[" << cmd.x << ']'
913 << " y[" << cmd.y << ']'
914 << " button[" << cmd.button() << ']');
916 Cursor & cur = d->cursor_;
918 switch (cmd.action) {
921 cur.message(_("Undo"));
922 cur.clearSelection();
924 cur.message(_("No further undo information"));
926 processUpdateFlags(Update::Force | Update::FitCursor);
930 cur.message(_("Redo"));
931 cur.clearSelection();
933 cur.message(_("No further redo information"));
935 processUpdateFlags(Update::Force | Update::FitCursor);
938 case LFUN_FONT_STATE:
939 cur.message(cur.currentState());
942 case LFUN_BOOKMARK_SAVE:
943 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
946 case LFUN_LABEL_GOTO: {
947 docstring label = cmd.argument();
950 getInsetByCode<InsetRef>(d->cursor_,
953 label = inset->getParam("reference");
954 // persistent=false: use temp_bookmark
964 case LFUN_PARAGRAPH_GOTO: {
965 int const id = convert<int>(to_utf8(cmd.argument()));
967 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
968 b = theBufferList().next(b)) {
970 ParIterator par = b->getParFromID(id);
971 if (par == b->par_iterator_end()) {
972 LYXERR(Debug::INFO, "No matching paragraph found! [" << id << "].");
974 LYXERR(Debug::INFO, "Paragraph " << par->id()
975 << " found in buffer `"
976 << b->absFileName() << "'.");
980 setCursor(makeDocIterator(par, 0));
983 // Switch to other buffer view and resend cmd
984 theLyXFunc().dispatch(FuncRequest(
985 LFUN_BUFFER_SWITCH, b->absFileName()));
986 theLyXFunc().dispatch(cmd);
996 gotoInset(this, NOTE_CODE, false);
999 case LFUN_REFERENCE_NEXT: {
1000 vector<InsetCode> tmp;
1001 tmp.push_back(LABEL_CODE);
1002 tmp.push_back(REF_CODE);
1003 gotoInset(this, tmp, true);
1007 case LFUN_CHANGES_TRACK:
1008 buffer_.params().trackChanges = !buffer_.params().trackChanges;
1011 case LFUN_CHANGES_OUTPUT:
1012 buffer_.params().outputChanges = !buffer_.params().outputChanges;
1013 if (buffer_.params().outputChanges) {
1014 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
1015 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1016 LaTeXFeatures::isAvailable("xcolor");
1018 if (!dvipost && !xcolorsoul) {
1019 Alert::warning(_("Changes not shown in LaTeX output"),
1020 _("Changes will not be highlighted in LaTeX output, "
1021 "because neither dvipost nor xcolor/soul are installed.\n"
1022 "Please install these packages or redefine "
1023 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1024 } else if (!xcolorsoul) {
1025 Alert::warning(_("Changes not shown in LaTeX output"),
1026 _("Changes will not be highlighted in LaTeX output "
1027 "when using pdflatex, because xcolor and soul are not installed.\n"
1028 "Please install both packages or redefine "
1029 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1034 case LFUN_CHANGE_NEXT:
1035 findNextChange(this);
1038 case LFUN_CHANGES_MERGE:
1039 if (findNextChange(this))
1040 showDialog("changes");
1043 case LFUN_ALL_CHANGES_ACCEPT:
1044 // select complete document
1045 d->cursor_.reset(buffer_.inset());
1046 d->cursor_.selHandle(true);
1047 buffer_.text().cursorBottom(d->cursor_);
1048 // accept everything in a single step to support atomic undo
1049 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::ACCEPT);
1052 case LFUN_ALL_CHANGES_REJECT:
1053 // select complete document
1054 d->cursor_.reset(buffer_.inset());
1055 d->cursor_.selHandle(true);
1056 buffer_.text().cursorBottom(d->cursor_);
1057 // reject everything in a single step to support atomic undo
1058 // Note: reject does not work recursively; the user may have to repeat the operation
1059 buffer_.text().acceptOrRejectChanges(d->cursor_, Text::REJECT);
1062 case LFUN_WORD_FIND:
1066 case LFUN_WORD_REPLACE: {
1067 bool has_deleted = false;
1068 if (cur.selection()) {
1069 DocIterator beg = cur.selectionBegin();
1070 DocIterator end = cur.selectionEnd();
1071 if (beg.pit() == end.pit()) {
1072 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
1073 if (cur.paragraph().isDeleted(p))
1078 replace(this, cmd, has_deleted);
1083 cur.clearSelection();
1085 cur.message(from_utf8(N_("Mark off")));
1089 cur.clearSelection();
1092 cur.message(from_utf8(N_("Mark on")));
1095 case LFUN_MARK_TOGGLE:
1096 cur.clearSelection();
1099 cur.message(from_utf8(N_("Mark removed")));
1102 cur.message(from_utf8(N_("Mark set")));
1107 case LFUN_SCREEN_RECENTER:
1111 case LFUN_BIBTEX_DATABASE_ADD: {
1112 Cursor tmpcur = d->cursor_;
1113 findInset(tmpcur, BIBTEX_CODE, false);
1114 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1117 if (inset->addDatabase(to_utf8(cmd.argument())))
1118 buffer_.updateBibfilesCache();
1123 case LFUN_BIBTEX_DATABASE_DEL: {
1124 Cursor tmpcur = d->cursor_;
1125 findInset(tmpcur, BIBTEX_CODE, false);
1126 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1129 if (inset->delDatabase(to_utf8(cmd.argument())))
1130 buffer_.updateBibfilesCache();
1135 case LFUN_WORDS_COUNT: {
1136 DocIterator from, to;
1137 if (cur.selection()) {
1138 from = cur.selectionBegin();
1139 to = cur.selectionEnd();
1141 from = doc_iterator_begin(buffer_.inset());
1142 to = doc_iterator_end(buffer_.inset());
1144 int const count = countWords(from, to);
1147 if (cur.selection())
1148 message = bformat(_("%1$d words in selection."),
1151 message = bformat(_("%1$d words in document."),
1155 if (cur.selection())
1156 message = _("One word in selection.");
1158 message = _("One word in document.");
1161 Alert::information(_("Count words"), message);
1165 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1166 // turn compression on/off
1167 buffer_.params().compressed = !buffer_.params().compressed;
1170 case LFUN_BUFFER_TOGGLE_EMBEDDING:
1171 // turn embedding on/off
1172 buffer_.embeddedFiles().enable(!buffer_.params().embedded);
1175 case LFUN_NEXT_INSET_TOGGLE: {
1176 // this is the real function we want to invoke
1177 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1178 // if there is an inset at cursor, see whether it
1180 Inset * inset = cur.nextInset();
1182 if (inset->isActive()) {
1183 Cursor tmpcur = cur;
1184 tmpcur.pushBackward(*inset);
1185 inset->dispatch(tmpcur, tmpcmd);
1186 if (tmpcur.result().dispatched()) {
1189 } else if (inset->editable() == Inset::IS_EDITABLE) {
1190 inset->edit(cur, true);
1193 // if it did not work, try the underlying inset.
1194 if (!cur.result().dispatched())
1195 cur.dispatch(tmpcmd);
1197 if (cur.result().dispatched())
1198 cur.clearSelection();
1203 case LFUN_SCREEN_UP:
1204 case LFUN_SCREEN_DOWN: {
1205 Point p = getPos(cur, cur.boundary());
1206 if (p.y_ < 0 || p.y_ > height_) {
1207 // The cursor is off-screen so recenter before proceeding.
1209 p = getPos(cur, cur.boundary());
1211 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1212 cur.reset(buffer_.inset());
1213 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1214 //FIXME: what to do with cur.x_target()?
1219 case LFUN_SCREEN_UP_SELECT:
1220 case LFUN_SCREEN_DOWN_SELECT: {
1221 // Those two are not ready yet for consumption.
1224 cur.selHandle(true);
1225 size_t initial_depth = cur.depth();
1226 Point const p = getPos(cur, cur.boundary());
1227 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1228 // FIXME: We need to verify if the cursor stayed within an inset...
1229 //cur.reset(buffer_.inset());
1230 d->text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1232 while (cur.depth() > initial_depth) {
1235 // FIXME: we need to do a redraw again because of the selection
1236 // But no screen update is needed.
1237 d->update_strategy_ = NoScreenUpdate;
1250 docstring const BufferView::requestSelection()
1252 Cursor & cur = d->cursor_;
1254 if (!cur.selection()) {
1255 d->xsel_cache_.set = false;
1259 if (!d->xsel_cache_.set ||
1260 cur.top() != d->xsel_cache_.cursor ||
1261 cur.anchor_.top() != d->xsel_cache_.anchor)
1263 d->xsel_cache_.cursor = cur.top();
1264 d->xsel_cache_.anchor = cur.anchor_.top();
1265 d->xsel_cache_.set = cur.selection();
1266 return cur.selectionAsString(false);
1272 void BufferView::clearSelection()
1274 d->cursor_.clearSelection();
1275 // Clear the selection buffer. Otherwise a subsequent
1276 // middle-mouse-button paste would use the selection buffer,
1277 // not the more current external selection.
1278 cap::clearSelection();
1279 d->xsel_cache_.set = false;
1280 // The buffer did not really change, but this causes the
1281 // redraw we need because we cleared the selection above.
1286 void BufferView::resize(int width, int height)
1288 // Update from work area
1292 // Clear the paragraph height cache.
1293 d->par_height_.clear();
1299 Inset const * BufferView::getCoveringInset(Text const & text,
1302 TextMetrics & tm = d->text_metrics_[&text];
1303 Inset * inset = tm.checkInsetHit(x, y);
1307 if (!inset->descendable())
1308 // No need to go further down if the inset is not
1312 size_t cell_number = inset->nargs();
1313 // Check all the inner cell.
1314 for (size_t i = 0; i != cell_number; ++i) {
1315 Text const * inner_text = inset->getText(i);
1318 Inset const * inset_deeper =
1319 getCoveringInset(*inner_text, x, y);
1321 return inset_deeper;
1329 void BufferView::mouseEventDispatch(FuncRequest const & cmd0)
1331 //lyxerr << "[ cmd0 " << cmd0 << "]" << endl;
1333 // This is only called for mouse related events including
1334 // LFUN_FILE_OPEN generated by drag-and-drop.
1335 FuncRequest cmd = cmd0;
1338 cur.push(buffer_.inset());
1339 cur.selection() = d->cursor_.selection();
1341 // Either the inset under the cursor or the
1342 // surrounding Text will handle this event.
1344 // make sure we stay within the screen...
1345 cmd.y = min(max(cmd.y, -1), height_);
1347 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1349 // Get inset under mouse, if there is one.
1350 Inset const * covering_inset =
1351 getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1352 if (covering_inset == d->last_inset_)
1353 // Same inset, no need to do anything...
1356 bool need_redraw = false;
1357 // const_cast because of setMouseHover().
1358 Inset * inset = const_cast<Inset *>(covering_inset);
1360 // Remove the hint on the last hovered inset (if any).
1361 need_redraw |= d->last_inset_->setMouseHover(false);
1363 // Highlighted the newly hovered inset (if any).
1364 need_redraw |= inset->setMouseHover(true);
1365 d->last_inset_ = inset;
1369 LYXERR(Debug::PAINTING, "Mouse hover detected at: ("
1370 << cmd.x << ", " << cmd.y << ")");
1372 d->update_strategy_ = DecorationUpdate;
1374 // This event (moving without mouse click) is not passed further.
1375 // This should be changed if it is further utilized.
1380 // Build temporary cursor.
1381 Inset * inset = d->text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1383 // Put anchor at the same position.
1386 // Try to dispatch to an non-editable inset near this position
1387 // via the temp cursor. If the inset wishes to change the real
1388 // cursor it has to do so explicitly by using
1389 // cur.bv().cursor() = cur; (or similar)
1391 inset->dispatch(cur, cmd);
1393 // Now dispatch to the temporary cursor. If the real cursor should
1394 // be modified, the inset's dispatch has to do so explicitly.
1395 if (!cur.result().dispatched())
1398 //Do we have a selection?
1399 theSelection().haveSelection(cursor().selection());
1401 // If the command has been dispatched,
1402 if (cur.result().dispatched()
1403 // an update is asked,
1404 && cur.result().update())
1405 processUpdateFlags(cur.result().update());
1409 void BufferView::scroll(int y)
1418 void BufferView::scrollDown(int offset)
1420 Text * text = &buffer_.text();
1421 TextMetrics & tm = d->text_metrics_[text];
1422 int ymax = height_ + offset;
1424 pair<pit_type, ParagraphMetrics const *> last = tm.last();
1425 int bottom_pos = last.second->position() + last.second->descent();
1426 if (last.first + 1 == int(text->paragraphs().size())) {
1427 if (bottom_pos <= height_)
1429 offset = min(offset, bottom_pos - height_);
1432 if (bottom_pos > ymax)
1434 tm.newParMetricsDown();
1436 d->anchor_ypos_ -= offset;
1442 void BufferView::scrollUp(int offset)
1444 Text * text = &buffer_.text();
1445 TextMetrics & tm = d->text_metrics_[text];
1446 int ymin = - offset;
1448 pair<pit_type, ParagraphMetrics const *> first = tm.first();
1449 int top_pos = first.second->position() - first.second->ascent();
1450 if (first.first == 0) {
1453 offset = min(offset, - top_pos);
1458 tm.newParMetricsUp();
1460 d->anchor_ypos_ += offset;
1466 void BufferView::setCursorFromRow(int row)
1471 buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1473 d->cursor_.reset(buffer_.inset());
1475 buffer_.text().setCursor(d->cursor_, 0, 0);
1477 buffer_.text().setCursor(d->cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1481 void BufferView::gotoLabel(docstring const & label)
1483 for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1484 vector<docstring> labels;
1485 it->getLabelList(buffer_, labels);
1486 if (find(labels.begin(), labels.end(), label) != labels.end()) {
1495 TextMetrics const & BufferView::textMetrics(Text const * t) const
1497 return const_cast<BufferView *>(this)->textMetrics(t);
1501 TextMetrics & BufferView::textMetrics(Text const * t)
1503 TextMetricsCache::iterator tmc_it = d->text_metrics_.find(t);
1504 if (tmc_it == d->text_metrics_.end()) {
1505 tmc_it = d->text_metrics_.insert(
1506 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1508 return tmc_it->second;
1512 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1515 return textMetrics(t).parMetrics(pit);
1519 int BufferView::workHeight() const
1525 void BufferView::setCursor(DocIterator const & dit)
1527 size_t const n = dit.depth();
1528 for (size_t i = 0; i < n; ++i)
1529 dit[i].inset().edit(d->cursor_, true);
1531 d->cursor_.setCursor(dit);
1532 d->cursor_.selection() = false;
1536 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1538 // Would be wrong to delete anything if we have a selection.
1539 if (cur.selection())
1542 bool need_anchor_change = false;
1543 bool changed = d->cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1544 need_anchor_change);
1546 if (need_anchor_change)
1552 updateLabels(buffer_);
1560 bool BufferView::mouseSetCursor(Cursor & cur, bool select)
1562 BOOST_ASSERT(&cur.bv() == this);
1565 // this event will clear selection so we save selection for
1566 // persistent selection
1567 cap::saveSelection(cursor());
1569 // Has the cursor just left the inset?
1570 bool badcursor = false;
1571 bool leftinset = (&d->cursor_.inset() != &cur.inset());
1573 badcursor = notifyCursorLeaves(d->cursor_, cur);
1575 // FIXME: shift-mouse selection doesn't work well across insets.
1576 bool do_selection = select && &d->cursor_.anchor().inset() == &cur.inset();
1578 // do the dEPM magic if needed
1579 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1580 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1581 // the leftinset bool would not be necessary (badcursor instead).
1582 bool update = leftinset;
1583 if (!do_selection && !badcursor && d->cursor_.inTexted())
1584 update |= checkDepm(cur, d->cursor_);
1586 // if the cursor was in an empty script inset and the new
1587 // position is in the nucleus of the inset, notifyCursorLeaves
1588 // will kill the script inset itself. So we check all the
1589 // elements of the cursor to make sure that they are correct.
1590 // For an example, see bug 2933:
1591 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1592 // The code below could maybe be moved to a DocIterator method.
1593 //lyxerr << "cur before " << cur <<endl;
1594 DocIterator dit(cur.inset());
1595 dit.push_back(cur.bottom());
1597 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1598 dit.push_back(cur[i]);
1601 //lyxerr << "5 cur after" << dit <<endl;
1603 d->cursor_.setCursor(dit);
1604 d->cursor_.boundary(cur.boundary());
1606 d->cursor_.setSelection();
1608 d->cursor_.clearSelection();
1610 d->cursor_.finishUndo();
1611 d->cursor_.setCurrentFont();
1616 void BufferView::putSelectionAt(DocIterator const & cur,
1617 int length, bool backwards)
1619 d->cursor_.clearSelection();
1625 d->cursor_.pos() += length;
1626 d->cursor_.setSelection(d->cursor_, -length);
1628 d->cursor_.setSelection(d->cursor_, length);
1633 Cursor & BufferView::cursor()
1639 Cursor const & BufferView::cursor() const
1645 pit_type BufferView::anchor_ref() const
1647 return d->anchor_pit_;
1651 bool BufferView::singleParUpdate()
1653 Text & buftext = buffer_.text();
1654 pit_type const bottom_pit = d->cursor_.bottom().pit();
1655 TextMetrics & tm = textMetrics(&buftext);
1656 int old_height = tm.parMetrics(bottom_pit).height();
1658 // In Single Paragraph mode, rebreak only
1659 // the (main text, not inset!) paragraph containing the cursor.
1660 // (if this paragraph contains insets etc., rebreaking will
1661 // recursively descend)
1662 tm.redoParagraph(bottom_pit);
1663 ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);
1664 if (pm.height() != old_height)
1665 // Paragraph height has changed so we cannot proceed to
1666 // the singlePar optimisation.
1669 d->update_strategy_ = SingleParUpdate;
1671 LYXERR(Debug::PAINTING, "\ny1: " << pm.position() - pm.ascent()
1672 << " y2: " << pm.position() + pm.descent()
1673 << " pit: " << bottom_pit
1674 << " singlepar: 1");
1679 void BufferView::updateMetrics()
1681 Text & buftext = buffer_.text();
1682 pit_type const npit = int(buftext.paragraphs().size());
1684 // Clear out the position cache in case of full screen redraw,
1685 d->coord_cache_.clear();
1687 // Clear out paragraph metrics to avoid having invalid metrics
1688 // in the cache from paragraphs not relayouted below
1689 // The complete text metrics will be redone.
1690 d->text_metrics_.clear();
1692 TextMetrics & tm = textMetrics(&buftext);
1694 // Rebreak anchor paragraph.
1695 tm.redoParagraph(d->anchor_pit_);
1696 ParagraphMetrics & anchor_pm = tm.par_metrics_[d->anchor_pit_];
1697 anchor_pm.setPosition(d->anchor_ypos_);
1699 LYXERR(Debug::PAINTING, "metrics: "
1700 << " anchor pit = " << d->anchor_pit_
1701 << " anchor ypos = " << d->anchor_ypos_);
1703 // Redo paragraphs above anchor if necessary.
1704 int y1 = d->anchor_ypos_ - anchor_pm.ascent();
1705 // We are now just above the anchor paragraph.
1706 pit_type pit1 = d->anchor_pit_ - 1;
1707 for (; pit1 >= 0 && y1 >= 0; --pit1) {
1708 tm.redoParagraph(pit1);
1709 ParagraphMetrics & pm = tm.par_metrics_[pit1];
1711 // Save the paragraph position in the cache.
1716 // Redo paragraphs below the anchor if necessary.
1717 int y2 = d->anchor_ypos_ + anchor_pm.descent();
1718 // We are now just below the anchor paragraph.
1719 pit_type pit2 = d->anchor_pit_ + 1;
1720 for (; pit2 < npit && y2 <= height_; ++pit2) {
1721 tm.redoParagraph(pit2);
1722 ParagraphMetrics & pm = tm.par_metrics_[pit2];
1724 // Save the paragraph position in the cache.
1729 LYXERR(Debug::PAINTING, "Metrics: "
1730 << " anchor pit = " << d->anchor_pit_
1731 << " anchor ypos = " << d->anchor_ypos_
1734 << " pit1 = " << pit1
1735 << " pit2 = " << pit2);
1737 d->update_strategy_ = FullScreenUpdate;
1739 if (lyxerr.debugging(Debug::WORKAREA)) {
1740 LYXERR(Debug::WORKAREA, "BufferView::updateMetrics");
1741 d->coord_cache_.dump();
1746 void BufferView::insertLyXFile(FileName const & fname)
1748 BOOST_ASSERT(d->cursor_.inTexted());
1750 // Get absolute path of file and add ".lyx"
1751 // to the filename if necessary
1752 FileName filename = fileSearch(string(), fname.absFilename(), "lyx");
1754 docstring const disp_fn = makeDisplayPath(filename.absFilename());
1755 // emit message signal.
1756 message(bformat(_("Inserting document %1$s..."), disp_fn));
1759 Buffer buf("", false);
1760 if (buf.loadLyXFile(filename)) {
1761 ErrorList & el = buffer_.errorList("Parse");
1762 // Copy the inserted document error list into the current buffer one.
1763 el = buf.errorList("Parse");
1764 buffer_.undo().recordUndo(d->cursor_);
1765 cap::pasteParagraphList(d->cursor_, buf.paragraphs(),
1766 buf.params().getTextClassPtr(), el);
1767 res = _("Document %1$s inserted.");
1769 res = _("Could not insert document %1$s");
1774 // emit message signal.
1775 message(bformat(res, disp_fn));
1776 buffer_.errors("Parse");
1780 Point BufferView::coordOffset(DocIterator const & dit, bool boundary) const
1786 // Addup contribution of nested insets, from inside to outside,
1787 // keeping the outer paragraph for a special handling below
1788 for (size_t i = dit.depth() - 1; i >= 1; --i) {
1789 CursorSlice const & sl = dit[i];
1793 // get relative position inside sl.inset()
1794 sl.inset().cursorPos(*this, sl, boundary && (i + 1 == dit.depth()), xx, yy);
1796 // Make relative position inside of the edited inset relative to sl.inset()
1800 // In case of an RTL inset, the edited inset will be positioned to the left
1803 bool boundary_i = boundary && i + 1 == dit.depth();
1804 bool rtl = textMetrics(sl.text()).isRTL(sl, boundary_i);
1809 // remember width for the case that sl.inset() is positioned in an RTL inset
1810 if (i && dit[i - 1].text()) {
1811 // If this Inset is inside a Text Inset, retrieve the Dimension
1812 // from the containing text instead of using Inset::dimension() which
1813 // might not be implemented.
1814 // FIXME (Abdel 23/09/2007): this is a bit messy because of the
1815 // elimination of Inset::dim_ cache. This coordOffset() method needs
1816 // to be rewritten in light of the new design.
1817 Dimension const & dim = parMetrics(dit[i - 1].text(),
1818 dit[i - 1].pit()).insetDimension(&sl.inset());
1821 Dimension const dim = sl.inset().dimension(*this);
1825 //lyxerr << "Cursor::getPos, i: "
1826 // << i << " x: " << xx << " y: " << y << endl;
1829 // Add contribution of initial rows of outermost paragraph
1830 CursorSlice const & sl = dit[0];
1831 TextMetrics const & tm = textMetrics(sl.text());
1832 ParagraphMetrics const & pm = tm.parMetrics(sl.pit());
1833 BOOST_ASSERT(!pm.rows().empty());
1834 y -= pm.rows()[0].ascent();
1836 // FIXME: document this mess
1838 if (sl.pos() > 0 && dit.depth() == 1) {
1840 if (pos && boundary)
1842 // lyxerr << "coordOffset: boundary:" << boundary << " depth:" << dit.depth() << " pos:" << pos << " sl.pos:" << sl.pos() << endl;
1843 rend = pm.pos2row(pos);
1845 rend = pm.pos2row(sl.pos());
1847 size_t rend = pm.pos2row(sl.pos());
1849 for (size_t rit = 0; rit != rend; ++rit)
1850 y += pm.rows()[rit].height();
1851 y += pm.rows()[rend].ascent();
1853 TextMetrics const & bottom_tm = textMetrics(dit.bottom().text());
1855 // Make relative position from the nested inset now bufferview absolute.
1856 int xx = bottom_tm.cursorX(dit.bottom(), boundary && dit.depth() == 1);
1859 // In the RTL case place the nested inset at the left of the cursor in
1860 // the outer paragraph
1861 bool boundary_1 = boundary && 1 == dit.depth();
1862 bool rtl = bottom_tm.isRTL(dit.bottom(), boundary_1);
1870 Point BufferView::getPos(DocIterator const & dit, bool boundary) const
1872 CursorSlice const & bot = dit.bottom();
1873 TextMetrics const & tm = textMetrics(bot.text());
1874 if (!tm.has(bot.pit()))
1875 return Point(-1, -1);
1877 Point p = coordOffset(dit, boundary); // offset from outer paragraph
1878 p.y_ += tm.parMetrics(bot.pit()).position();
1883 void BufferView::draw(frontend::Painter & pain)
1885 LYXERR(Debug::PAINTING, "\t\t*** START DRAWING ***");
1886 Text & text = buffer_.text();
1887 TextMetrics const & tm = d->text_metrics_[&text];
1888 int const y = tm.first().second->position();
1889 PainterInfo pi(this, pain);
1891 switch (d->update_strategy_) {
1893 case NoScreenUpdate:
1894 // If no screen painting is actually needed, only some the different
1895 // coordinates of insets and paragraphs needs to be updated.
1896 pi.full_repaint = true;
1897 pi.pain.setDrawingEnabled(false);
1901 case SingleParUpdate:
1902 pi.full_repaint = false;
1903 // In general, only the current row of the outermost paragraph
1904 // will be redrawn. Particular cases where selection spans
1905 // multiple paragraph are correctly detected in TextMetrics.
1909 case DecorationUpdate:
1910 // FIXME: We should also distinguish DecorationUpdate to avoid text
1911 // drawing if possible. This is not possible to do easily right now
1912 // because of the single backing pixmap.
1914 case FullScreenUpdate:
1915 // The whole screen, including insets, will be refreshed.
1916 pi.full_repaint = true;
1918 // Clear background.
1919 pain.fillRectangle(0, 0, width_, height_,
1920 buffer_.inset().backgroundColor());
1925 // and possibly grey out below
1926 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1927 int const y2 = lastpm.second->position() + lastpm.second->descent();
1929 pain.fillRectangle(0, y2, width_, height_ - y2, Color_bottomarea);
1932 LYXERR(Debug::PAINTING, "\n\t\t*** END DRAWING ***");
1934 // The scrollbar needs an update.
1937 // Normalize anchor for next time
1938 pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1939 pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1940 for (pit_type pit = firstpm.first; pit <= lastpm.first; ++pit) {
1941 ParagraphMetrics const & pm = tm.parMetrics(pit);
1942 if (pm.position() + pm.descent() > 0) {
1943 d->anchor_pit_ = pit;
1944 d->anchor_ypos_ = pm.position();
1948 LYXERR(Debug::PAINTING, "Found new anchor pit = " << d->anchor_pit_
1949 << " anchor ypos = " << d->anchor_ypos_);
1953 void BufferView::message(docstring const & msg)
1956 d->gui_->message(msg);
1960 void BufferView::showDialog(string const & name)
1963 d->gui_->showDialog(name, string());
1967 void BufferView::showDialog(string const & name,
1968 string const & data, Inset * inset)
1971 d->gui_->showDialog(name, data, inset);
1975 void BufferView::updateDialog(string const & name, string const & data)
1978 d->gui_->updateDialog(name, data);
1982 void BufferView::setGuiDelegate(frontend::GuiBufferViewDelegate * gui)
1988 // FIXME: Move this out of BufferView again
1989 docstring BufferView::contentsOfPlaintextFile(FileName const & fname)
1991 if (!fname.isReadableFile()) {
1992 docstring const error = from_ascii(strerror(errno));
1993 docstring const file = makeDisplayPath(fname.absFilename(), 50);
1994 docstring const text =
1995 bformat(_("Could not read the specified document\n"
1996 "%1$s\ndue to the error: %2$s"), file, error);
1997 Alert::error(_("Could not read file"), text);
2001 if (!fname.isReadableFile()) {
2002 docstring const file = makeDisplayPath(fname.absFilename(), 50);
2003 docstring const text =
2004 bformat(_("%1$s\n is not readable."), file);
2005 Alert::error(_("Could not open file"), text);
2009 // FIXME UNICODE: We don't know the encoding of the file
2010 docstring file_content = fname.fileContents("UTF-8");
2011 if (file_content.empty()) {
2012 Alert::error(_("Reading not UTF-8 encoded file"),
2013 _("The file is not UTF-8 encoded.\n"
2014 "It will be read as local 8Bit-encoded.\n"
2015 "If this does not give the correct result\n"
2016 "then please change the encoding of the file\n"
2017 "to UTF-8 with a program other than LyX.\n"));
2018 file_content = fname.fileContents("local8bit");
2021 return normalize_c(file_content);
2025 void BufferView::insertPlaintextFile(FileName const & f, bool asParagraph)
2027 docstring const tmpstr = contentsOfPlaintextFile(f);
2032 Cursor & cur = cursor();
2033 cap::replaceSelection(cur);
2034 buffer_.undo().recordUndo(cur);
2036 cur.innerText()->insertStringAsParagraphs(cur, tmpstr);
2038 cur.innerText()->insertStringAsLines(cur, tmpstr);