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 "bufferview_funcs.h"
24 #include "CoordCache.h"
25 #include "CutAndPaste.h"
27 #include "DispatchResult.h"
28 #include "ErrorList.h"
30 #include "FloatList.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
35 #include "InsetIterator.h"
37 #include "LaTeXFeatures.h"
38 #include "callback.h" // added for Dispatch functions
44 #include "TextClass.h"
47 #include "Paragraph.h"
48 #include "paragraph_funcs.h"
49 #include "ParagraphParameters.h"
50 #include "ParIterator.h"
55 #include "WordLangTuple.h"
56 #include "MetricsInfo.h"
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
67 #include "graphics/Previews.h"
69 #include "support/convert.h"
70 #include "support/FileFilterList.h"
71 #include "support/filetools.h"
72 #include "support/Package.h"
73 #include "support/types.h"
75 #include <boost/bind.hpp>
76 #include <boost/current_function.hpp>
84 using support::addPath;
85 using support::bformat;
86 using support::FileFilterList;
87 using support::FileName;
88 using support::fileSearch;
89 using support::isDirWriteable;
90 using support::isFileReadable;
91 using support::makeDisplayPath;
92 using support::package;
96 using std::istringstream;
100 using std::mem_fun_ref;
104 namespace Alert = frontend::Alert;
108 /// Return an inset of this class if it exists at the current cursor position
110 T * getInsetByCode(Cursor & cur, Inset::Code code)
113 DocIterator it = cur;
114 if (it.nextInset() &&
115 it.nextInset()->lyxCode() == code) {
116 inset = static_cast<T*>(it.nextInset());
124 BufferView::BufferView()
125 : width_(0), height_(0), buffer_(0), wh_(0),
127 multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
128 intl_(new Intl), last_inset_(0)
130 xsel_cache_.set = false;
131 intl_->initKeyMapper(lyxrc.use_kbmap);
135 BufferView::~BufferView()
140 Buffer * BufferView::buffer() const
146 void BufferView::setBuffer(Buffer * b)
148 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
149 << "[ b = " << b << "]" << endl;
152 // Save the actual cursor position and anchor inside the
153 // buffer so that it can be restored in case we rechange
154 // to this buffer later on.
155 buffer_->saveCursor(cursor_.selectionBegin(),
156 cursor_.selectionEnd());
157 // update bookmark pit of the current buffer before switch
158 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i) {
159 BookmarksSection::Bookmark const & bm = LyX::ref().session().bookmarks().bookmark(i);
160 if (buffer()->fileName() != bm.filename.absFilename())
162 // if top_id or bottom_pit, bottom_pos has been changed, update bookmark
163 // see http://bugzilla.lyx.org/show_bug.cgi?id=3092
167 boost::tie(new_pit, new_pos, new_id) = moveToPosition(bm.bottom_pit, bm.bottom_pos, bm.top_id, bm.top_pos);
168 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos || bm.top_id != new_id )
169 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(new_pit, new_pos, new_id);
171 // current buffer is going to be switched-off, save cursor pos
172 // Ideally, the whole cursor stack should be saved, but session
173 // currently can only handle bottom (whole document) level pit and pos.
174 // That is to say, if a cursor is in a nested inset, it will be
175 // restore to the left of the top level inset.
176 LyX::ref().session().lastFilePos().save(FileName(buffer_->fileName()),
177 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
180 // If we're quitting lyx, don't bother updating stuff
186 //FIXME Fix for bug 3440 is here.
187 // If we are closing current buffer, switch to the first in
190 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
191 << " No Buffer!" << endl;
192 // We are closing the buffer, use the first buffer as current
194 // if (last_buffer_) buffer_ = last_buffer_;
195 // also check that this is in theBufferList()?
196 buffer_ = theBufferList().first();
199 // last_buffer = buffer_;
200 // Set current buffer
205 cursor_ = Cursor(*this);
212 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
213 << "Buffer addr: " << buffer_ << endl;
214 cursor_.push(buffer_->inset());
215 cursor_.resetAnchor();
216 buffer_->text().setCurrentFont(cursor_);
217 if (buffer_->getCursor().size() > 0 &&
218 buffer_->getAnchor().size() > 0)
220 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
221 cursor_.resetAnchor();
222 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
223 cursor_.setSelection();
224 // do not set selection to the new buffer because we
225 // only paste recent selection.
227 // Make sure that the restored cursor is not broken. This can happen for
228 // example if this Buffer has been modified by another view.
229 cursor_.fixIfBroken();
231 updateMetrics(false);
232 if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
233 graphics::Previews::get().generateBufferPreviews(*buffer_);
237 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
239 // File already open?
240 if (theBufferList().exists(filename.absFilename())) {
241 docstring const file = makeDisplayPath(filename.absFilename(), 20);
242 docstring text = bformat(_("The document %1$s is already "
243 "loaded.\n\nDo you want to revert "
244 "to the saved version?"), file);
245 int const ret = Alert::prompt(_("Revert to saved document?"),
246 text, 0, 1, _("&Revert"), _("&Switch to document"));
249 setBuffer(theBufferList().getBuffer(filename.absFilename()));
252 // FIXME: should be LFUN_REVERT
253 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
255 // Fall through to new load. (Asger)
261 if (isFileReadable(filename)) {
262 b = theBufferList().newBuffer(filename.absFilename());
263 if (!lyx::loadLyXFile(b, filename)) {
264 theBufferList().release(b);
268 docstring text = bformat(_("The document %1$s does not yet "
269 "exist.\n\nDo you want to create "
270 "a new document?"), from_utf8(filename.absFilename()));
271 int const ret = Alert::prompt(_("Create new document?"),
272 text, 0, 1, _("&Create"), _("Cancel"));
275 b = newFile(filename.absFilename(), string(), true);
283 // Send the "errors" signal in case of parsing errors
286 // Update the labels and section numbering.
287 updateLabels(*buffer_);
288 // scroll to the position when the file was last closed
289 if (lyxrc.use_lastfilepos) {
292 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
293 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
294 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
296 updateMetrics(false);
297 buffer_->text().setCurrentFont(cursor_);
302 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
308 void BufferView::resize()
313 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
315 updateMetrics(false);
319 bool BufferView::fitCursor()
321 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
322 frontend::FontMetrics const & fm =
323 theFontMetrics(cursor_.getFont());
324 int const asc = fm.maxAscent();
325 int const des = fm.maxDescent();
326 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
327 if (p.y_ - asc >= 0 && p.y_ + des < height_)
335 bool BufferView::multiParSel()
337 if (!cursor_.selection())
339 bool ret = multiparsel_cache_;
340 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
341 // Either this, or previous selection spans paragraphs
342 return ret || multiparsel_cache_;
346 bool BufferView::update(Update::flags flags)
348 // last_inset_ points to the last visited inset. This pointer may become
349 // invalid because of keyboard editing. Since all such operations
350 // causes screen update(), I reset last_inset_ to avoid such a problem.
352 // This is close to a hot-path.
354 << BOOST_CURRENT_FUNCTION
355 << "[fitcursor = " << (flags & Update::FitCursor)
356 << ", forceupdate = " << (flags & Update::Force)
357 << ", singlepar = " << (flags & Update::SinglePar)
358 << "] buffer: " << buffer_ << endl;
360 // Check needed to survive LyX startup
364 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
366 // Update macro store
367 if (!(cursor().inMathed() && cursor().inMacroMode()))
368 buffer_->buildMacros();
370 // Now do the first drawing step if needed. This consists on updating
371 // the CoordCache in updateMetrics().
372 // The second drawing step is done in WorkArea::redraw() if needed.
374 // Case when no explicit update is requested.
376 // no need to redraw anything.
377 metrics_info_.update_strategy = NoScreenUpdate;
381 if (flags == Update::Decoration) {
382 metrics_info_.update_strategy = DecorationUpdate;
386 if (flags == Update::FitCursor
387 || flags == (Update::Decoration | Update::FitCursor)) {
388 bool const fit_cursor = fitCursor();
389 // tell the frontend to update the screen if needed.
391 updateMetrics(false);
394 if (flags & Update::Decoration) {
395 metrics_info_.update_strategy = DecorationUpdate;
398 // no screen update is needed.
399 metrics_info_.update_strategy = NoScreenUpdate;
403 bool full_metrics = flags & Update::Force;
404 if (flags & Update::MultiParSel)
405 full_metrics |= multiParSel();
407 bool const single_par = !full_metrics;
408 updateMetrics(single_par);
410 if (flags & Update::FitCursor && fitCursor())
411 updateMetrics(false);
413 // tell the frontend to update the screen.
418 void BufferView::updateScrollbar()
421 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
422 << " no text in updateScrollbar" << endl;
423 scrollbarParameters_.reset();
427 Text & t = buffer_->text();
428 TextMetrics & tm = text_metrics_[&t];
430 int const parsize = int(t.paragraphs().size() - 1);
431 if (anchor_ref_ > parsize) {
432 anchor_ref_ = parsize;
437 << BOOST_CURRENT_FUNCTION
438 << " Updating scrollbar: height: " << t.paragraphs().size()
439 << " curr par: " << cursor_.bottom().pit()
440 << " default height " << defaultRowHeight() << endl;
442 // It would be better to fix the scrollbar to understand
443 // values in [0..1] and divide everything by wh
445 // estimated average paragraph height:
449 int h = tm.parMetrics(anchor_ref_).height();
451 // Normalize anchor/offset (MV):
452 while (offset_ref_ > h && anchor_ref_ < parsize) {
455 h = tm.parMetrics(anchor_ref_).height();
457 // Look at paragraph heights on-screen
460 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
463 int const h2 = tm.parMetrics(pit).height();
469 int const hav = sumh / nh;
470 // More realistic average paragraph height
475 scrollbarParameters_.height = (parsize + 1) * wh_;
476 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
477 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
481 ScrollbarParameters const & BufferView::scrollbarParameters() const
483 return scrollbarParameters_;
487 void BufferView::scrollDocView(int value)
489 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
490 << "[ value = " << value << "]" << endl;
495 Text & t = buffer_->text();
496 TextMetrics & tm = text_metrics_[&t];
498 float const bar = value / float(wh_ * t.paragraphs().size());
500 anchor_ref_ = int(bar * t.paragraphs().size());
501 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
502 anchor_ref_ = int(t.paragraphs().size()) - 1;
504 tm.redoParagraph(anchor_ref_);
505 int const h = tm.parMetrics(anchor_ref_).height();
506 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
507 updateMetrics(false);
511 void BufferView::setCursorFromScrollbar()
516 Text & t = buffer_->text();
518 int const height = 2 * defaultRowHeight();
519 int const first = height;
520 int const last = height_ - height;
521 Cursor & cur = cursor_;
523 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
526 case bv_funcs::CUR_ABOVE:
527 // We reset the cursor because bv_funcs::status() does not
528 // work when the cursor is within mathed.
529 cur.reset(buffer_->inset());
530 t.setCursorFromCoordinates(cur, 0, first);
531 cur.clearSelection();
533 case bv_funcs::CUR_BELOW:
534 // We reset the cursor because bv_funcs::status() does not
535 // work when the cursor is within mathed.
536 cur.reset(buffer_->inset());
537 t.setCursorFromCoordinates(cur, 0, last);
538 cur.clearSelection();
540 case bv_funcs::CUR_INSIDE:
541 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
542 int const newy = min(last, max(y, first));
544 cur.reset(buffer_->inset());
545 t.setCursorFromCoordinates(cur, 0, newy);
551 Change const BufferView::getCurrentChange() const
553 if (!cursor_.selection())
554 return Change(Change::UNCHANGED);
556 DocIterator dit = cursor_.selectionBegin();
557 return dit.paragraph().lookupChange(dit.pos());
561 void BufferView::saveBookmark(unsigned int idx)
563 // tenatively save bookmark, id and pos will be used to
564 // acturately locate a bookmark in a 'live' lyx session.
565 // pit and pos will be updated with bottom level pit/pos
567 LyX::ref().session().bookmarks().save(
568 FileName(buffer_->fileName()),
569 cursor_.bottom().pit(),
570 cursor_.bottom().pos(),
571 cursor_.paragraph().id(),
576 // emit message signal.
577 message(_("Save bookmark"));
581 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
582 int top_id, pos_type top_pos)
584 cursor_.clearSelection();
586 // if a valid par_id is given, try it first
587 // This is the case for a 'live' bookmark when unique paragraph ID
588 // is used to track bookmarks.
590 ParIterator par = buffer_->getParFromID(top_id);
591 if (par != buffer_->par_iterator_end()) {
592 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
593 // Some slices of the iterator may not be
594 // reachable (e.g. closed collapsable inset)
595 // so the dociterator may need to be
596 // shortened. Otherwise, setCursor may crash
597 // lyx when the cursor can not be set to these
599 size_t const n = dit.depth();
600 for (size_t i = 0; i < n; ++i)
601 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
606 // Note: return bottom (document) level pit.
607 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
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 DocIterator it = doc_iterator_begin(buffer_->inset());
618 it.pit() = bottom_pit;
619 it.pos() = min(bottom_pos, it.paragraph().size());
621 return boost::make_tuple(it.pit(), it.pos(),
622 it.paragraph().id());
625 return boost::make_tuple(pit_type(0), pos_type(0), 0);
629 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
631 if (lyxrc.rtl_support) {
632 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
633 if (intl_->keymap == Intl::PRIMARY)
636 if (intl_->keymap == Intl::SECONDARY)
641 intl_->getTransManager().translateAndInsert(c, t, cur);
645 int BufferView::workWidth() const
651 void BufferView::center()
653 CursorSlice & bot = cursor_.bottom();
654 TextMetrics & tm = text_metrics_[bot.text()];
655 pit_type const pit = bot.pit();
656 tm.redoParagraph(pit);
657 ParagraphMetrics const & pm = tm.parMetrics(pit);
659 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
660 + pm.ascent() - height_ / 2;
664 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
668 Cursor & cur = cursor_;
670 switch (cmd.action) {
673 flag.enabled(!buffer_->undostack().empty());
676 flag.enabled(!buffer_->redostack().empty());
678 case LFUN_FILE_INSERT:
679 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
680 case LFUN_FILE_INSERT_PLAINTEXT:
681 case LFUN_BOOKMARK_SAVE:
682 // FIXME: Actually, these LFUNS should be moved to Text
683 flag.enabled(cur.inTexted());
685 case LFUN_FONT_STATE:
686 case LFUN_LABEL_INSERT:
687 case LFUN_PARAGRAPH_GOTO:
688 // FIXME handle non-trivially
689 case LFUN_OUTLINE_UP:
690 case LFUN_OUTLINE_DOWN:
691 case LFUN_OUTLINE_IN:
692 case LFUN_OUTLINE_OUT:
694 case LFUN_REFERENCE_NEXT:
698 case LFUN_MARK_TOGGLE:
699 case LFUN_SCREEN_RECENTER:
700 case LFUN_BIBTEX_DATABASE_ADD:
701 case LFUN_BIBTEX_DATABASE_DEL:
702 case LFUN_WORDS_COUNT:
703 case LFUN_NEXT_INSET_TOGGLE:
707 case LFUN_WORD_REPLACE:
708 flag.enabled(!cur.paragraph().isDeleted(cur.pos()));
711 case LFUN_LABEL_GOTO: {
712 flag.enabled(!cmd.argument().empty()
713 || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
717 case LFUN_CHANGES_TRACK:
719 flag.setOnOff(buffer_->params().trackChanges);
722 case LFUN_CHANGES_OUTPUT:
723 flag.enabled(buffer_);
724 flag.setOnOff(buffer_->params().outputChanges);
727 case LFUN_CHANGES_MERGE:
728 case LFUN_CHANGE_NEXT:
729 case LFUN_ALL_CHANGES_ACCEPT:
730 case LFUN_ALL_CHANGES_REJECT:
731 // TODO: context-sensitive enabling of LFUNs
732 // In principle, these command should only be enabled if there
733 // is a change in the document. However, without proper
734 // optimizations, this will inevitably result in poor performance.
735 flag.enabled(buffer_);
738 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
739 flag.setOnOff(buffer_->params().compressed);
751 Update::flags BufferView::dispatch(FuncRequest const & cmd)
753 //lyxerr << BOOST_CURRENT_FUNCTION
754 // << [ cmd = " << cmd << "]" << endl;
756 // Make sure that the cached BufferView is correct.
757 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
758 << " action[" << cmd.action << ']'
759 << " arg[" << to_utf8(cmd.argument()) << ']'
760 << " x[" << cmd.x << ']'
761 << " y[" << cmd.y << ']'
762 << " button[" << cmd.button() << ']'
765 // FIXME: this should not be possible.
769 Cursor & cur = cursor_;
770 // Default Update flags.
771 Update::flags updateFlags = Update::Force | Update::FitCursor;
773 switch (cmd.action) {
776 cur.message(_("Undo"));
777 cur.clearSelection();
778 if (!textUndo(*this)) {
779 cur.message(_("No further undo information"));
780 updateFlags = Update::None;
785 cur.message(_("Redo"));
786 cur.clearSelection();
787 if (!textRedo(*this)) {
788 cur.message(_("No further redo information"));
789 updateFlags = Update::None;
793 case LFUN_FILE_INSERT:
795 menuInsertLyXFile(to_utf8(cmd.argument()));
798 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
800 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
803 case LFUN_FILE_INSERT_PLAINTEXT:
805 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
808 case LFUN_FONT_STATE:
809 cur.message(cur.currentState());
812 case LFUN_BOOKMARK_SAVE:
813 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
816 case LFUN_LABEL_GOTO: {
817 docstring label = cmd.argument();
820 getInsetByCode<InsetRef>(cursor_,
823 label = inset->getParam("reference");
824 // persistent=false: use temp_bookmark
834 case LFUN_PARAGRAPH_GOTO: {
835 int const id = convert<int>(to_utf8(cmd.argument()));
837 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
838 ParIterator par = b->getParFromID(id);
839 if (par == b->par_iterator_end()) {
841 << "No matching paragraph found! ["
842 << id << "]." << endl;
845 << "Paragraph " << par->id()
846 << " found in buffer `"
847 << b->fileName() << "'." << endl;
851 setCursor(makeDocIterator(par, 0));
853 // Switch to other buffer view and resend cmd
854 theLyXFunc().dispatch(FuncRequest(
855 LFUN_BUFFER_SWITCH, b->fileName()));
856 theLyXFunc().dispatch(cmd);
857 updateFlags = Update::None;
866 case LFUN_OUTLINE_UP:
867 toc::outline(toc::Up, cursor_);
868 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
869 updateLabels(*buffer_);
871 case LFUN_OUTLINE_DOWN:
872 toc::outline(toc::Down, cursor_);
873 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
874 updateLabels(*buffer_);
876 case LFUN_OUTLINE_IN:
877 toc::outline(toc::In, cursor_);
878 updateLabels(*buffer_);
880 case LFUN_OUTLINE_OUT:
881 toc::outline(toc::Out, cursor_);
882 updateLabels(*buffer_);
886 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
889 case LFUN_REFERENCE_NEXT: {
890 vector<Inset_code> tmp;
891 tmp.push_back(Inset::LABEL_CODE);
892 tmp.push_back(Inset::REF_CODE);
893 bv_funcs::gotoInset(this, tmp, true);
897 case LFUN_CHANGES_TRACK:
898 buffer_->params().trackChanges = !buffer_->params().trackChanges;
901 case LFUN_CHANGES_OUTPUT:
902 buffer_->params().outputChanges = !buffer_->params().outputChanges;
903 if (buffer_->params().outputChanges) {
904 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
905 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
906 LaTeXFeatures::isAvailable("xcolor");
908 if (!dvipost && !xcolorsoul) {
909 Alert::warning(_("Changes not shown in LaTeX output"),
910 _("Changes will not be highlighted in LaTeX output, "
911 "because neither dvipost nor xcolor/soul are installed.\n"
912 "Please install these packages or redefine "
913 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
914 } else if (!xcolorsoul) {
915 Alert::warning(_("Changes not shown in LaTeX output"),
916 _("Changes will not be highlighted in LaTeX output "
917 "when using pdflatex, because xcolor and soul are not installed.\n"
918 "Please install both packages or redefine "
919 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
924 case LFUN_CHANGE_NEXT:
925 findNextChange(this);
928 case LFUN_CHANGES_MERGE:
929 if (findNextChange(this))
930 showDialog("changes");
933 case LFUN_ALL_CHANGES_ACCEPT:
934 // select complete document
935 cursor_.reset(buffer_->inset());
936 cursor_.selHandle(true);
937 buffer_->text().cursorBottom(cursor_);
938 // accept everything in a single step to support atomic undo
939 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
942 case LFUN_ALL_CHANGES_REJECT:
943 // select complete document
944 cursor_.reset(buffer_->inset());
945 cursor_.selHandle(true);
946 buffer_->text().cursorBottom(cursor_);
947 // reject everything in a single step to support atomic undo
948 // Note: reject does not work recursively; the user may have to repeat the operation
949 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
956 case LFUN_WORD_REPLACE:
961 cur.clearSelection();
963 cur.message(from_utf8(N_("Mark off")));
967 cur.clearSelection();
970 cur.message(from_utf8(N_("Mark on")));
973 case LFUN_MARK_TOGGLE:
974 cur.clearSelection();
977 cur.message(from_utf8(N_("Mark removed")));
980 cur.message(from_utf8(N_("Mark set")));
985 case LFUN_SCREEN_RECENTER:
989 case LFUN_BIBTEX_DATABASE_ADD: {
990 Cursor tmpcur = cursor_;
991 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
992 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
995 if (inset->addDatabase(to_utf8(cmd.argument())))
996 buffer_->updateBibfilesCache();
1001 case LFUN_BIBTEX_DATABASE_DEL: {
1002 Cursor tmpcur = cursor_;
1003 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
1004 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1005 Inset::BIBTEX_CODE);
1007 if (inset->delDatabase(to_utf8(cmd.argument())))
1008 buffer_->updateBibfilesCache();
1013 case LFUN_WORDS_COUNT: {
1014 DocIterator from, to;
1015 if (cur.selection()) {
1016 from = cur.selectionBegin();
1017 to = cur.selectionEnd();
1019 from = doc_iterator_begin(buffer_->inset());
1020 to = doc_iterator_end(buffer_->inset());
1022 int const count = countWords(from, to);
1025 if (cur.selection())
1026 message = bformat(_("%1$d words in selection."),
1029 message = bformat(_("%1$d words in document."),
1033 if (cur.selection())
1034 message = _("One word in selection.");
1036 message = _("One word in document.");
1039 Alert::information(_("Count words"), message);
1043 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1044 // turn compression on/off
1045 buffer_->params().compressed = !buffer_->params().compressed;
1048 case LFUN_NEXT_INSET_TOGGLE: {
1049 // this is the real function we want to invoke
1050 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1051 // if there is an inset at cursor, see whether it
1053 Inset * inset = cur.nextInset();
1054 if (inset && inset->isActive()) {
1055 Cursor tmpcur = cur;
1056 tmpcur.pushLeft(*inset);
1057 inset->dispatch(tmpcur, tmpcmd);
1058 if (tmpcur.result().dispatched()) {
1062 // if it did not work, try the underlying inset.
1063 if (!cur.result().dispatched())
1064 cur.dispatch(tmpcmd);
1066 if (cur.result().dispatched())
1067 cur.clearSelection();
1073 updateFlags = Update::None;
1080 docstring const BufferView::requestSelection()
1085 Cursor & cur = cursor_;
1087 if (!cur.selection()) {
1088 xsel_cache_.set = false;
1092 if (!xsel_cache_.set ||
1093 cur.top() != xsel_cache_.cursor ||
1094 cur.anchor_.top() != xsel_cache_.anchor)
1096 xsel_cache_.cursor = cur.top();
1097 xsel_cache_.anchor = cur.anchor_.top();
1098 xsel_cache_.set = cur.selection();
1099 return cur.selectionAsString(false);
1105 void BufferView::clearSelection()
1108 cursor_.clearSelection();
1109 // Clear the selection buffer. Otherwise a subsequent
1110 // middle-mouse-button paste would use the selection buffer,
1111 // not the more current external selection.
1112 cap::clearSelection();
1113 xsel_cache_.set = false;
1114 // The buffer did not really change, but this causes the
1115 // redraw we need because we cleared the selection above.
1121 void BufferView::workAreaResize(int width, int height)
1123 // Update from work area
1127 // The complete text metrics will be redone.
1128 text_metrics_.clear();
1135 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1137 pit_type pit = text.getPitNearY(*this, y);
1138 BOOST_ASSERT(pit != -1);
1139 Paragraph const & par = text.getPar(pit);
1141 LYXERR(Debug::DEBUG)
1142 << BOOST_CURRENT_FUNCTION
1147 InsetList::const_iterator iit = par.insetlist.begin();
1148 InsetList::const_iterator iend = par.insetlist.end();
1149 for (; iit != iend; ++iit) {
1150 Inset * const inset = iit->inset;
1151 if (inset->covers(*this, x, y)) {
1152 if (!inset->descendable())
1153 // No need to go further down if the inset is not
1157 size_t cell_number = inset->nargs();
1158 // Check all the inner cell.
1159 for (size_t i = 0; i != cell_number; ++i) {
1160 Text const * inner_text = inset->getText(i);
1163 Inset const * inset_deeper =
1164 getCoveringInset(*inner_text, x, y);
1166 return inset_deeper;
1170 LYXERR(Debug::DEBUG)
1171 << BOOST_CURRENT_FUNCTION
1172 << ": Hit inset: " << inset << endl;
1176 LYXERR(Debug::DEBUG)
1177 << BOOST_CURRENT_FUNCTION
1178 << ": No inset hit. " << endl;
1183 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1185 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1187 // This is only called for mouse related events including
1188 // LFUN_FILE_OPEN generated by drag-and-drop.
1189 FuncRequest cmd = cmd0;
1191 // E.g. Qt mouse press when no buffer
1196 cur.push(buffer_->inset());
1197 cur.selection() = cursor_.selection();
1199 // Either the inset under the cursor or the
1200 // surrounding Text will handle this event.
1202 // make sure we stay within the screen...
1203 cmd.y = min(max(cmd.y, -1), height_);
1205 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1207 // Get inset under mouse, if there is one.
1208 Inset const * covering_inset =
1209 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1210 if (covering_inset == last_inset_)
1211 // Same inset, no need to do anything...
1214 bool need_redraw = false;
1215 // const_cast because of setMouseHover().
1216 Inset * inset = const_cast<Inset *>(covering_inset);
1218 // Remove the hint on the last hovered inset (if any).
1219 need_redraw |= last_inset_->setMouseHover(false);
1221 // Highlighted the newly hovered inset (if any).
1222 need_redraw |= inset->setMouseHover(true);
1223 last_inset_ = inset;
1225 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1226 // not expose the button for redraw. We adjust here the metrics dimension
1227 // to enable a full redraw.
1228 // FIXME: It is possible to redraw only the area around the button!
1230 && metrics_info_.update_strategy == SingleParUpdate) {
1231 // FIXME: It should be possible to redraw only the area around
1232 // the button by doing this:
1234 //metrics_info_.singlepar = false;
1235 //metrics_info_.y1 = ymin of button;
1236 //metrics_info_.y2 = ymax of button;
1238 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1239 // between background updates and text updates. So we use the hammer
1240 // solution for now. We could also avoid the updateMetrics() below
1241 // by using the first and last pit of the CoordCache. Have a look
1242 // at Text::getPitNearY() to see what I mean.
1244 //metrics_info_.pit1 = first pit of CoordCache;
1245 //metrics_info_.pit2 = last pit of CoordCache;
1246 //metrics_info_.singlepar = false;
1247 //metrics_info_.y1 = 0;
1248 //metrics_info_.y2 = height_;
1250 updateMetrics(false);
1253 // This event (moving without mouse click) is not passed further.
1254 // This should be changed if it is further utilized.
1258 // Build temporary cursor.
1259 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1261 // Put anchor at the same position.
1264 // Try to dispatch to an non-editable inset near this position
1265 // via the temp cursor. If the inset wishes to change the real
1266 // cursor it has to do so explicitly by using
1267 // cur.bv().cursor() = cur; (or similar)
1269 inset->dispatch(cur, cmd);
1272 // Now dispatch to the temporary cursor. If the real cursor should
1273 // be modified, the inset's dispatch has to do so explicitly.
1274 if (!cur.result().dispatched())
1277 // Redraw if requested and necessary.
1278 if (cur.result().dispatched() && cur.result().update())
1279 return update(cur.result().update());
1285 void BufferView::scroll(int /*lines*/)
1290 // Text const * t = &buffer_->text();
1291 // int const line_height = defaultRowHeight();
1293 // // The new absolute coordinate
1294 // int new_top_y = top_y() + lines * line_height;
1296 // // Restrict to a valid value
1297 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1298 // new_top_y = std::max(0, new_top_y);
1300 // scrollDocView(new_top_y);
1305 void BufferView::setCursorFromRow(int row)
1310 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1313 buffer_->text().setCursor(cursor_, 0, 0);
1315 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1319 void BufferView::gotoLabel(docstring const & label)
1321 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1322 vector<docstring> labels;
1323 it->getLabelList(*buffer_, labels);
1324 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1333 TextMetrics const & BufferView::textMetrics(Text const * t) const
1335 return const_cast<BufferView *>(this)->textMetrics(t);
1339 TextMetrics & BufferView::textMetrics(Text const * t)
1341 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1342 if (tmc_it == text_metrics_.end()) {
1343 tmc_it = text_metrics_.insert(
1344 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1346 return tmc_it->second;
1350 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1353 return textMetrics(t).parMetrics(pit);
1357 int BufferView::workHeight() const
1363 void BufferView::setCursor(DocIterator const & dit)
1365 size_t const n = dit.depth();
1366 for (size_t i = 0; i < n; ++i)
1367 dit[i].inset().edit(cursor_, true);
1369 cursor_.setCursor(dit);
1370 cursor_.selection() = false;
1374 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1376 // Would be wrong to delete anything if we have a selection.
1377 if (cur.selection())
1380 bool need_anchor_change = false;
1381 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1382 need_anchor_change);
1384 if (need_anchor_change)
1390 updateLabels(*buffer_);
1392 updateMetrics(false);
1398 bool BufferView::mouseSetCursor(Cursor & cur)
1400 BOOST_ASSERT(&cur.bv() == this);
1402 // Has the cursor just left the inset?
1403 bool badcursor = false;
1404 bool leftinset = (&cursor_.inset() != &cur.inset());
1406 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1408 // do the dEPM magic if needed
1409 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1410 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1411 // the leftinset bool would not be necessary (badcursor instead).
1412 bool update = leftinset;
1413 if (!badcursor && cursor_.inTexted())
1414 update |= checkDepm(cur, cursor_);
1416 // if the cursor was in an empty script inset and the new
1417 // position is in the nucleus of the inset, notifyCursorLeaves
1418 // will kill the script inset itself. So we check all the
1419 // elements of the cursor to make sure that they are correct.
1420 // For an example, see bug 2933:
1421 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1422 // The code below could maybe be moved to a DocIterator method.
1423 //lyxerr << "cur before " << cur <<std::endl;
1424 DocIterator dit(cur.inset());
1425 dit.push_back(cur.bottom());
1427 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1428 dit.push_back(cur[i]);
1431 //lyxerr << "5 cur after" << dit <<std::endl;
1433 cursor_.setCursor(dit);
1434 cursor_.boundary(cur.boundary());
1435 cursor_.clearSelection();
1441 void BufferView::putSelectionAt(DocIterator const & cur,
1442 int length, bool backwards)
1444 cursor_.clearSelection();
1450 cursor_.pos() += length;
1451 cursor_.setSelection(cursor_, -length);
1453 cursor_.setSelection(cursor_, length);
1454 cap::saveSelection(cursor_);
1459 Cursor & BufferView::cursor()
1465 Cursor const & BufferView::cursor() const
1471 pit_type BufferView::anchor_ref() const
1477 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1479 return metrics_info_;
1483 // FIXME: We should split-up updateMetrics() for the singlepar case.
1484 void BufferView::updateMetrics(bool singlepar)
1486 Text & buftext = buffer_->text();
1487 TextMetrics & tm = textMetrics(&buftext);
1488 pit_type size = int(buftext.paragraphs().size());
1490 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1491 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1495 // If the paragraph metrics has changed, we can not
1496 // use the singlepar optimisation.
1498 // In Single Paragraph mode, rebreak only
1499 // the (main text, not inset!) paragraph containing the cursor.
1500 // (if this paragraph contains insets etc., rebreaking will
1501 // recursively descend)
1502 && tm.redoParagraph(cursor_.bottom().pit()))
1505 pit_type const pit = anchor_ref_;
1508 size_t const npit = buftext.paragraphs().size();
1510 // Rebreak anchor paragraph.
1512 tm.redoParagraph(pit);
1514 // Clear out the position cache in case of full screen redraw.
1516 coord_cache_.clear();
1518 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1520 // Redo paragraphs above anchor if necessary.
1522 while (y1 > 0 && pit1 > 0) {
1523 y1 -= tm.parMetrics(pit1).ascent();
1526 tm.redoParagraph(pit1);
1527 y1 -= tm.parMetrics(pit1).descent();
1531 // Take care of ascent of first line
1532 y1 -= tm.parMetrics(pit1).ascent();
1534 // Normalize anchor for next time
1538 // Grey at the beginning is ugly
1539 if (pit1 == 0 && y1 > 0) {
1545 // Redo paragraphs below the anchor if necessary.
1547 while (y2 < height_ && pit2 < int(npit) - 1) {
1548 y2 += tm.parMetrics(pit2).descent();
1551 tm.redoParagraph(pit2);
1552 y2 += tm.parMetrics(pit2).ascent();
1555 // Take care of descent of last line
1556 y2 += tm.parMetrics(pit2).descent();
1558 // The coordinates of all these paragraphs are correct, cache them
1560 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1561 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1562 ParagraphMetrics const & pm = tm.parMetrics(pit);
1564 parPos[pit] = Point(0, y);
1565 if (singlepar && pit == cursor_.bottom().pit()) {
1566 // In Single Paragraph mode, collect here the
1567 // y1 and y2 of the (one) paragraph the cursor is in
1568 y1 = y - pm.ascent();
1569 y2 = y + pm.descent();
1575 // collect cursor paragraph iter bounds
1576 pit1 = cursor_.bottom().pit();
1577 pit2 = cursor_.bottom().pit();
1580 LYXERR(Debug::DEBUG)
1581 << BOOST_CURRENT_FUNCTION
1584 << " pit1: " << pit1
1585 << " pit2: " << pit2
1586 << " npit: " << npit
1587 << " singlepar: " << singlepar
1591 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1592 singlepar? SingleParUpdate: FullScreenUpdate, size);
1594 if (lyxerr.debugging(Debug::WORKAREA)) {
1595 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1596 coord_cache_.dump();
1601 void BufferView::menuInsertLyXFile(string const & filenm)
1603 BOOST_ASSERT(cursor_.inTexted());
1604 string filename = filenm;
1606 if (filename.empty()) {
1607 // Launch a file browser
1609 string initpath = lyxrc.document_path;
1612 string const trypath = buffer_->filePath();
1613 // If directory is writeable, use this as default.
1614 if (isDirWriteable(FileName(trypath)))
1619 FileDialog fileDlg(_("Select LyX document to insert"),
1621 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1622 make_pair(_("Examples|#E#e"),
1623 from_utf8(addPath(package().system_support().absFilename(),
1626 FileDialog::Result result =
1627 fileDlg.open(from_utf8(initpath),
1628 FileFilterList(_("LyX Documents (*.lyx)")),
1631 if (result.first == FileDialog::Later)
1635 filename = to_utf8(result.second);
1637 // check selected filename
1638 if (filename.empty()) {
1639 // emit message signal.
1640 message(_("Canceled."));
1645 // Get absolute path of file and add ".lyx"
1646 // to the filename if necessary
1647 filename = fileSearch(string(), filename, "lyx").absFilename();
1649 docstring const disp_fn = makeDisplayPath(filename);
1650 // emit message signal.
1651 message(bformat(_("Inserting document %1$s..."), disp_fn));
1654 Buffer buf("", false);
1655 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1656 ErrorList & el = buffer_->errorList("Parse");
1657 // Copy the inserted document error list into the current buffer one.
1658 el = buf.errorList("Parse");
1659 recordUndo(cursor_);
1660 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1661 buf.params().textclass, el);
1662 res = _("Document %1$s inserted.");
1664 res = _("Could not insert document %1$s");
1666 // emit message signal.
1667 message(bformat(res, disp_fn));
1668 buffer_->errors("Parse");