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 // If we are closing current buffer, switch to the first in
189 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
190 << " No Buffer!" << endl;
191 // We are closing the buffer, use the first buffer as current
192 buffer_ = theBufferList().first();
194 // Set current buffer
199 cursor_ = Cursor(*this);
204 LYXERR(Debug::INFO) << BOOST_CURRENT_FUNCTION
205 << "Buffer addr: " << buffer_ << endl;
206 cursor_.push(buffer_->inset());
207 cursor_.resetAnchor();
208 buffer_->text().setCurrentFont(cursor_);
209 if (buffer_->getCursor().size() > 0 &&
210 buffer_->getAnchor().size() > 0)
212 cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
213 cursor_.resetAnchor();
214 cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
215 cursor_.setSelection();
216 // do not set selection to the new buffer because we
217 // only paste recent selection.
219 // Make sure that the restored cursor is not broken. This can happen for
220 // example if this Buffer has been modified by another view.
221 cursor_.fixIfBroken();
226 updateMetrics(false);
228 if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
229 graphics::Previews::get().generateBufferPreviews(*buffer_);
233 bool BufferView::loadLyXFile(FileName const & filename, bool tolastfiles)
235 // File already open?
236 if (theBufferList().exists(filename.absFilename())) {
237 docstring const file = makeDisplayPath(filename.absFilename(), 20);
238 docstring text = bformat(_("The document %1$s is already "
239 "loaded.\n\nDo you want to revert "
240 "to the saved version?"), file);
241 int const ret = Alert::prompt(_("Revert to saved document?"),
242 text, 0, 1, _("&Revert"), _("&Switch to document"));
245 setBuffer(theBufferList().getBuffer(filename.absFilename()));
248 // FIXME: should be LFUN_REVERT
249 if (!theBufferList().close(theBufferList().getBuffer(filename.absFilename()), false))
251 // Fall through to new load. (Asger)
257 if (isFileReadable(filename)) {
258 b = theBufferList().newBuffer(filename.absFilename());
259 if (!lyx::loadLyXFile(b, filename)) {
260 theBufferList().release(b);
264 docstring text = bformat(_("The document %1$s does not yet "
265 "exist.\n\nDo you want to create "
266 "a new document?"), from_utf8(filename.absFilename()));
267 int const ret = Alert::prompt(_("Create new document?"),
268 text, 0, 1, _("&Create"), _("Cancel"));
271 b = newFile(filename.absFilename(), string(), true);
279 // Send the "errors" signal in case of parsing errors
282 // Update the labels and section numbering.
283 updateLabels(*buffer_);
284 // scroll to the position when the file was last closed
285 if (lyxrc.use_lastfilepos) {
288 boost::tie(pit, pos) = LyX::ref().session().lastFilePos().load(filename);
289 // if successfully move to pit (returned par_id is not zero), update metrics and reset font
290 if (moveToPosition(pit, pos, 0, 0).get<1>()) {
292 updateMetrics(false);
293 buffer_->text().setCurrentFont(cursor_);
298 LyX::ref().session().lastFiles().add(FileName(b->fileName()));
304 void BufferView::resize()
309 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION << endl;
311 updateMetrics(false);
316 bool BufferView::fitCursor()
318 if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
319 frontend::FontMetrics const & fm =
320 theFontMetrics(cursor_.getFont());
321 int const asc = fm.maxAscent();
322 int const des = fm.maxDescent();
323 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
324 if (p.y_ - asc >= 0 && p.y_ + des < height_)
332 bool BufferView::multiParSel()
334 if (!cursor_.selection())
336 bool ret = multiparsel_cache_;
337 multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
338 // Either this, or previous selection spans paragraphs
339 return ret || multiparsel_cache_;
343 bool BufferView::update(Update::flags flags)
345 // last_inset_ points to the last visited inset. This pointer may become
346 // invalid because of keyboard editing. Since all such operations
347 // causes screen update(), I reset last_inset_ to avoid such a problem.
349 // This is close to a hot-path.
351 << BOOST_CURRENT_FUNCTION
352 << "[fitcursor = " << (flags & Update::FitCursor)
353 << ", forceupdate = " << (flags & Update::Force)
354 << ", singlepar = " << (flags & Update::SinglePar)
355 << "] buffer: " << buffer_ << endl;
357 // Check needed to survive LyX startup
361 LYXERR(Debug::WORKAREA) << "BufferView::update" << std::endl;
363 // Update macro store
364 if (!(cursor().inMathed() && cursor().inMacroMode()))
365 buffer_->buildMacros();
367 // Now do the first drawing step if needed. This consists on updating
368 // the CoordCache in updateMetrics().
369 // The second drawing step is done in WorkArea::redraw() if needed.
371 // Case when no explicit update is requested.
373 // no need to redraw anything.
374 metrics_info_.update_strategy = NoScreenUpdate;
378 if (flags == Update::Decoration) {
379 metrics_info_.update_strategy = DecorationUpdate;
383 if (flags == Update::FitCursor
384 || flags == (Update::Decoration | Update::FitCursor)) {
385 bool const fit_cursor = fitCursor();
386 // tell the frontend to update the screen if needed.
388 updateMetrics(false);
391 if (flags & Update::Decoration) {
392 metrics_info_.update_strategy = DecorationUpdate;
395 // no screen update is needed.
396 metrics_info_.update_strategy = NoScreenUpdate;
400 bool full_metrics = flags & Update::Force;
401 if (flags & Update::MultiParSel)
402 full_metrics |= multiParSel();
404 bool const single_par = !full_metrics;
405 updateMetrics(single_par);
407 if (flags & Update::FitCursor && fitCursor())
408 updateMetrics(false);
410 // tell the frontend to update the screen.
415 void BufferView::updateScrollbar()
418 LYXERR(Debug::DEBUG) << BOOST_CURRENT_FUNCTION
419 << " no text in updateScrollbar" << endl;
420 scrollbarParameters_.reset();
424 Text & t = buffer_->text();
425 TextMetrics & tm = text_metrics_[&t];
427 int const parsize = int(t.paragraphs().size() - 1);
428 if (anchor_ref_ > parsize) {
429 anchor_ref_ = parsize;
434 << BOOST_CURRENT_FUNCTION
435 << " Updating scrollbar: height: " << t.paragraphs().size()
436 << " curr par: " << cursor_.bottom().pit()
437 << " default height " << defaultRowHeight() << endl;
439 // It would be better to fix the scrollbar to understand
440 // values in [0..1] and divide everything by wh
442 // estimated average paragraph height:
446 int h = tm.parMetrics(anchor_ref_).height();
448 // Normalize anchor/offset (MV):
449 while (offset_ref_ > h && anchor_ref_ < parsize) {
452 h = tm.parMetrics(anchor_ref_).height();
454 // Look at paragraph heights on-screen
457 for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
460 int const h2 = tm.parMetrics(pit).height();
466 int const hav = sumh / nh;
467 // More realistic average paragraph height
472 scrollbarParameters_.height = (parsize + 1) * wh_;
473 scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
474 scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
478 ScrollbarParameters const & BufferView::scrollbarParameters() const
480 return scrollbarParameters_;
484 void BufferView::scrollDocView(int value)
486 LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
487 << "[ value = " << value << "]" << endl;
492 Text & t = buffer_->text();
493 TextMetrics & tm = text_metrics_[&t];
495 float const bar = value / float(wh_ * t.paragraphs().size());
497 anchor_ref_ = int(bar * t.paragraphs().size());
498 if (anchor_ref_ > int(t.paragraphs().size()) - 1)
499 anchor_ref_ = int(t.paragraphs().size()) - 1;
501 tm.redoParagraph(anchor_ref_);
502 int const h = tm.parMetrics(anchor_ref_).height();
503 offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
504 updateMetrics(false);
508 void BufferView::setCursorFromScrollbar()
513 Text & t = buffer_->text();
515 int const height = 2 * defaultRowHeight();
516 int const first = height;
517 int const last = height_ - height;
518 Cursor & cur = cursor_;
520 bv_funcs::CurStatus st = bv_funcs::status(this, cur);
523 case bv_funcs::CUR_ABOVE:
524 // We reset the cursor because bv_funcs::status() does not
525 // work when the cursor is within mathed.
526 cur.reset(buffer_->inset());
527 t.setCursorFromCoordinates(cur, 0, first);
528 cur.clearSelection();
530 case bv_funcs::CUR_BELOW:
531 // We reset the cursor because bv_funcs::status() does not
532 // work when the cursor is within mathed.
533 cur.reset(buffer_->inset());
534 t.setCursorFromCoordinates(cur, 0, last);
535 cur.clearSelection();
537 case bv_funcs::CUR_INSIDE:
538 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
539 int const newy = min(last, max(y, first));
541 cur.reset(buffer_->inset());
542 t.setCursorFromCoordinates(cur, 0, newy);
548 Change const BufferView::getCurrentChange() const
550 if (!cursor_.selection())
551 return Change(Change::UNCHANGED);
553 DocIterator dit = cursor_.selectionBegin();
554 return dit.paragraph().lookupChange(dit.pos());
558 void BufferView::saveBookmark(unsigned int idx)
560 // tenatively save bookmark, id and pos will be used to
561 // acturately locate a bookmark in a 'live' lyx session.
562 // pit and pos will be updated with bottom level pit/pos
564 LyX::ref().session().bookmarks().save(
565 FileName(buffer_->fileName()),
566 cursor_.bottom().pit(),
567 cursor_.bottom().pos(),
568 cursor_.paragraph().id(),
573 // emit message signal.
574 message(_("Save bookmark"));
578 boost::tuple<pit_type, pos_type, int> BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
579 int top_id, pos_type top_pos)
581 cursor_.clearSelection();
583 // if a valid par_id is given, try it first
584 // This is the case for a 'live' bookmark when unique paragraph ID
585 // is used to track bookmarks.
587 ParIterator par = buffer_->getParFromID(top_id);
588 if (par != buffer_->par_iterator_end()) {
589 DocIterator dit = makeDocIterator(par, min(par->size(), top_pos));
590 // Some slices of the iterator may not be
591 // reachable (e.g. closed collapsable inset)
592 // so the dociterator may need to be
593 // shortened. Otherwise, setCursor may crash
594 // lyx when the cursor can not be set to these
596 size_t const n = dit.depth();
597 for (size_t i = 0; i < n; ++i)
598 if (dit[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
603 // Note: return bottom (document) level pit.
604 return boost::make_tuple(cursor_.bottom().pit(), cursor_.bottom().pos(), top_id);
607 // if top_id == 0, or searching through top_id failed
608 // This is the case for a 'restored' bookmark when only bottom
609 // (document level) pit was saved. Because of this, bookmark
610 // restoration is inaccurate. If a bookmark was within an inset,
611 // it will be restored to the left of the outmost inset that contains
613 if (static_cast<size_t>(bottom_pit) < buffer_->paragraphs().size()) {
614 DocIterator it = doc_iterator_begin(buffer_->inset());
615 it.pit() = bottom_pit;
616 it.pos() = min(bottom_pos, it.paragraph().size());
618 return boost::make_tuple(it.pit(), it.pos(),
619 it.paragraph().id());
622 return boost::make_tuple(pit_type(0), pos_type(0), 0);
626 void BufferView::switchKeyMap()
628 if (!lyxrc.rtl_support)
631 if (cursor_.innerText()->real_current_font.isRightToLeft()) {
632 if (intl_->keymap == Intl::PRIMARY)
635 if (intl_->keymap == Intl::SECONDARY)
641 int BufferView::workWidth() const
647 void BufferView::center()
649 CursorSlice & bot = cursor_.bottom();
650 TextMetrics & tm = text_metrics_[bot.text()];
651 pit_type const pit = bot.pit();
652 tm.redoParagraph(pit);
653 ParagraphMetrics const & pm = tm.parMetrics(pit);
655 offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
656 + pm.ascent() - height_ / 2;
660 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
664 switch (cmd.action) {
667 flag.enabled(!buffer_->undostack().empty());
670 flag.enabled(!buffer_->redostack().empty());
672 case LFUN_FILE_INSERT:
673 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
674 case LFUN_FILE_INSERT_PLAINTEXT:
675 case LFUN_BOOKMARK_SAVE:
676 // FIXME: Actually, these LFUNS should be moved to Text
677 flag.enabled(cursor_.inTexted());
679 case LFUN_FONT_STATE:
680 case LFUN_LABEL_INSERT:
681 case LFUN_PARAGRAPH_GOTO:
682 // FIXME handle non-trivially
683 case LFUN_OUTLINE_UP:
684 case LFUN_OUTLINE_DOWN:
685 case LFUN_OUTLINE_IN:
686 case LFUN_OUTLINE_OUT:
688 case LFUN_REFERENCE_NEXT:
690 case LFUN_WORD_REPLACE:
693 case LFUN_MARK_TOGGLE:
694 case LFUN_SCREEN_RECENTER:
695 case LFUN_BIBTEX_DATABASE_ADD:
696 case LFUN_BIBTEX_DATABASE_DEL:
697 case LFUN_WORDS_COUNT:
698 case LFUN_NEXT_INSET_TOGGLE:
702 case LFUN_LABEL_GOTO: {
703 flag.enabled(!cmd.argument().empty()
704 || getInsetByCode<InsetRef>(cursor_, Inset::REF_CODE));
708 case LFUN_CHANGES_TRACK:
710 flag.setOnOff(buffer_->params().trackChanges);
713 case LFUN_CHANGES_OUTPUT:
714 flag.enabled(buffer_);
715 flag.setOnOff(buffer_->params().outputChanges);
718 case LFUN_CHANGES_MERGE:
719 case LFUN_CHANGE_NEXT:
720 case LFUN_ALL_CHANGES_ACCEPT:
721 case LFUN_ALL_CHANGES_REJECT:
722 // TODO: context-sensitive enabling of LFUNs
723 // In principle, these command should only be enabled if there
724 // is a change in the document. However, without proper
725 // optimizations, this will inevitably result in poor performance.
726 flag.enabled(buffer_);
729 case LFUN_BUFFER_TOGGLE_COMPRESSION: {
730 flag.setOnOff(buffer_->params().compressed);
742 Update::flags BufferView::dispatch(FuncRequest const & cmd)
744 //lyxerr << BOOST_CURRENT_FUNCTION
745 // << [ cmd = " << cmd << "]" << endl;
747 // Make sure that the cached BufferView is correct.
748 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
749 << " action[" << cmd.action << ']'
750 << " arg[" << to_utf8(cmd.argument()) << ']'
751 << " x[" << cmd.x << ']'
752 << " y[" << cmd.y << ']'
753 << " button[" << cmd.button() << ']'
756 // FIXME: this should not be possible.
760 Cursor & cur = cursor_;
761 // Default Update flags.
762 Update::flags updateFlags = Update::Force | Update::FitCursor;
764 switch (cmd.action) {
767 cur.message(_("Undo"));
768 cur.clearSelection();
769 if (!textUndo(*this)) {
770 cur.message(_("No further undo information"));
771 updateFlags = Update::None;
777 cur.message(_("Redo"));
778 cur.clearSelection();
779 if (!textRedo(*this)) {
780 cur.message(_("No further redo information"));
781 updateFlags = Update::None;
786 case LFUN_FILE_INSERT:
788 menuInsertLyXFile(to_utf8(cmd.argument()));
791 case LFUN_FILE_INSERT_PLAINTEXT_PARA:
793 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
796 case LFUN_FILE_INSERT_PLAINTEXT:
798 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
801 case LFUN_FONT_STATE:
802 cur.message(cur.currentState());
805 case LFUN_BOOKMARK_SAVE:
806 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
809 case LFUN_LABEL_GOTO: {
810 docstring label = cmd.argument();
813 getInsetByCode<InsetRef>(cursor_,
816 label = inset->getParam("reference");
817 // persistent=false: use temp_bookmark
827 case LFUN_PARAGRAPH_GOTO: {
828 int const id = convert<int>(to_utf8(cmd.argument()));
830 for (Buffer * b = buffer_; i == 0 || b != buffer_; b = theBufferList().next(b)) {
831 ParIterator par = b->getParFromID(id);
832 if (par == b->par_iterator_end()) {
834 << "No matching paragraph found! ["
835 << id << "]." << endl;
838 << "Paragraph " << par->id()
839 << " found in buffer `"
840 << b->fileName() << "'." << endl;
844 setCursor(makeDocIterator(par, 0));
847 // Switch to other buffer view and resend cmd
848 theLyXFunc().dispatch(FuncRequest(
849 LFUN_BUFFER_SWITCH, b->fileName()));
850 theLyXFunc().dispatch(cmd);
851 updateFlags = Update::None;
860 case LFUN_OUTLINE_UP:
861 toc::outline(toc::Up, cursor_);
862 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
863 updateLabels(*buffer_);
865 case LFUN_OUTLINE_DOWN:
866 toc::outline(toc::Down, cursor_);
867 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
868 updateLabels(*buffer_);
870 case LFUN_OUTLINE_IN:
871 toc::outline(toc::In, cursor_);
872 updateLabels(*buffer_);
874 case LFUN_OUTLINE_OUT:
875 toc::outline(toc::Out, cursor_);
876 updateLabels(*buffer_);
880 bv_funcs::gotoInset(this, Inset::NOTE_CODE, false);
883 case LFUN_REFERENCE_NEXT: {
884 vector<Inset_code> tmp;
885 tmp.push_back(Inset::LABEL_CODE);
886 tmp.push_back(Inset::REF_CODE);
887 bv_funcs::gotoInset(this, tmp, true);
891 case LFUN_CHANGES_TRACK:
892 buffer_->params().trackChanges = !buffer_->params().trackChanges;
895 case LFUN_CHANGES_OUTPUT:
896 buffer_->params().outputChanges = !buffer_->params().outputChanges;
897 if (buffer_->params().outputChanges) {
898 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
899 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
900 LaTeXFeatures::isAvailable("xcolor");
902 if (!dvipost && !xcolorsoul) {
903 Alert::warning(_("Changes not shown in LaTeX output"),
904 _("Changes will not be highlighted in LaTeX output, "
905 "because neither dvipost nor xcolor/soul are installed.\n"
906 "Please install these packages or redefine "
907 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
908 } else if (!xcolorsoul) {
909 Alert::warning(_("Changes not shown in LaTeX output"),
910 _("Changes will not be highlighted in LaTeX output "
911 "when using pdflatex, because xcolor and soul are not installed.\n"
912 "Please install both packages or redefine "
913 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
918 case LFUN_CHANGE_NEXT:
919 findNextChange(this);
922 case LFUN_CHANGES_MERGE:
923 if (findNextChange(this))
924 showDialog("changes");
927 case LFUN_ALL_CHANGES_ACCEPT:
928 // select complete document
929 cursor_.reset(buffer_->inset());
930 cursor_.selHandle(true);
931 buffer_->text().cursorBottom(cursor_);
932 // accept everything in a single step to support atomic undo
933 buffer_->text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
936 case LFUN_ALL_CHANGES_REJECT:
937 // select complete document
938 cursor_.reset(buffer_->inset());
939 cursor_.selHandle(true);
940 buffer_->text().cursorBottom(cursor_);
941 // reject everything in a single step to support atomic undo
942 // Note: reject does not work recursively; the user may have to repeat the operation
943 buffer_->text().acceptOrRejectChanges(cursor_, Text::REJECT);
950 case LFUN_WORD_REPLACE:
955 cur.clearSelection();
957 cur.message(from_utf8(N_("Mark off")));
961 cur.clearSelection();
964 cur.message(from_utf8(N_("Mark on")));
967 case LFUN_MARK_TOGGLE:
968 cur.clearSelection();
971 cur.message(from_utf8(N_("Mark removed")));
974 cur.message(from_utf8(N_("Mark set")));
979 case LFUN_SCREEN_RECENTER:
983 case LFUN_BIBTEX_DATABASE_ADD: {
984 Cursor tmpcur = cursor_;
985 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
986 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
989 if (inset->addDatabase(to_utf8(cmd.argument())))
990 buffer_->updateBibfilesCache();
995 case LFUN_BIBTEX_DATABASE_DEL: {
996 Cursor tmpcur = cursor_;
997 bv_funcs::findInset(tmpcur, Inset::BIBTEX_CODE, false);
998 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
1001 if (inset->delDatabase(to_utf8(cmd.argument())))
1002 buffer_->updateBibfilesCache();
1007 case LFUN_WORDS_COUNT: {
1008 DocIterator from, to;
1009 if (cur.selection()) {
1010 from = cur.selectionBegin();
1011 to = cur.selectionEnd();
1013 from = doc_iterator_begin(buffer_->inset());
1014 to = doc_iterator_end(buffer_->inset());
1016 int const count = countWords(from, to);
1019 if (cur.selection())
1020 message = bformat(_("%1$d words in selection."),
1023 message = bformat(_("%1$d words in document."),
1027 if (cur.selection())
1028 message = _("One word in selection.");
1030 message = _("One word in document.");
1033 Alert::information(_("Count words"), message);
1037 case LFUN_BUFFER_TOGGLE_COMPRESSION:
1038 // turn compression on/off
1039 buffer_->params().compressed = !buffer_->params().compressed;
1042 case LFUN_NEXT_INSET_TOGGLE: {
1043 // this is the real function we want to invoke
1044 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1045 // if there is an inset at cursor, see whether it
1047 Inset * inset = cur.nextInset();
1048 if (inset && inset->isActive()) {
1049 Cursor tmpcur = cur;
1050 tmpcur.pushLeft(*inset);
1051 inset->dispatch(tmpcur, tmpcmd);
1052 if (tmpcur.result().dispatched()) {
1056 // if it did not work, try the underlying inset.
1057 if (!cur.result().dispatched())
1058 cur.dispatch(tmpcmd);
1060 if (cur.result().dispatched())
1061 cur.clearSelection();
1067 updateFlags = Update::None;
1074 docstring const BufferView::requestSelection()
1079 Cursor & cur = cursor_;
1081 if (!cur.selection()) {
1082 xsel_cache_.set = false;
1086 if (!xsel_cache_.set ||
1087 cur.top() != xsel_cache_.cursor ||
1088 cur.anchor_.top() != xsel_cache_.anchor)
1090 xsel_cache_.cursor = cur.top();
1091 xsel_cache_.anchor = cur.anchor_.top();
1092 xsel_cache_.set = cur.selection();
1093 return cur.selectionAsString(false);
1099 void BufferView::clearSelection()
1102 cursor_.clearSelection();
1103 // Clear the selection buffer. Otherwise a subsequent
1104 // middle-mouse-button paste would use the selection buffer,
1105 // not the more current external selection.
1106 cap::clearSelection();
1107 xsel_cache_.set = false;
1108 // The buffer did not really change, but this causes the
1109 // redraw we need because we cleared the selection above.
1115 void BufferView::workAreaResize(int width, int height)
1117 // Update from work area
1121 // The complete text metrics will be redone.
1122 text_metrics_.clear();
1129 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1131 pit_type pit = text.getPitNearY(*this, y);
1132 BOOST_ASSERT(pit != -1);
1133 Paragraph const & par = text.getPar(pit);
1135 LYXERR(Debug::DEBUG)
1136 << BOOST_CURRENT_FUNCTION
1141 InsetList::const_iterator iit = par.insetlist.begin();
1142 InsetList::const_iterator iend = par.insetlist.end();
1143 for (; iit != iend; ++iit) {
1144 Inset * const inset = iit->inset;
1145 if (inset->covers(*this, x, y)) {
1146 if (!inset->descendable())
1147 // No need to go further down if the inset is not
1151 size_t cell_number = inset->nargs();
1152 // Check all the inner cell.
1153 for (size_t i = 0; i != cell_number; ++i) {
1154 Text const * inner_text = inset->getText(i);
1157 Inset const * inset_deeper =
1158 getCoveringInset(*inner_text, x, y);
1160 return inset_deeper;
1164 LYXERR(Debug::DEBUG)
1165 << BOOST_CURRENT_FUNCTION
1166 << ": Hit inset: " << inset << endl;
1170 LYXERR(Debug::DEBUG)
1171 << BOOST_CURRENT_FUNCTION
1172 << ": No inset hit. " << endl;
1177 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1179 //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1181 // This is only called for mouse related events including
1182 // LFUN_FILE_OPEN generated by drag-and-drop.
1183 FuncRequest cmd = cmd0;
1185 // E.g. Qt mouse press when no buffer
1190 cur.push(buffer_->inset());
1191 cur.selection() = cursor_.selection();
1193 // Either the inset under the cursor or the
1194 // surrounding Text will handle this event.
1196 // make sure we stay within the screen...
1197 cmd.y = min(max(cmd.y, -1), height_);
1199 if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1201 // Get inset under mouse, if there is one.
1202 Inset const * covering_inset =
1203 getCoveringInset(buffer_->text(), cmd.x, cmd.y);
1204 if (covering_inset == last_inset_)
1205 // Same inset, no need to do anything...
1208 bool need_redraw = false;
1209 // const_cast because of setMouseHover().
1210 Inset * inset = const_cast<Inset *>(covering_inset);
1212 // Remove the hint on the last hovered inset (if any).
1213 need_redraw |= last_inset_->setMouseHover(false);
1215 // Highlighted the newly hovered inset (if any).
1216 need_redraw |= inset->setMouseHover(true);
1217 last_inset_ = inset;
1219 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1220 // not expose the button for redraw. We adjust here the metrics dimension
1221 // to enable a full redraw.
1222 // FIXME: It is possible to redraw only the area around the button!
1224 && metrics_info_.update_strategy == SingleParUpdate) {
1225 // FIXME: It should be possible to redraw only the area around
1226 // the button by doing this:
1228 //metrics_info_.singlepar = false;
1229 //metrics_info_.y1 = ymin of button;
1230 //metrics_info_.y2 = ymax of button;
1232 // Unfortunately, rowpainter.cpp:paintText() does not distinguish
1233 // between background updates and text updates. So we use the hammer
1234 // solution for now. We could also avoid the updateMetrics() below
1235 // by using the first and last pit of the CoordCache. Have a look
1236 // at Text::getPitNearY() to see what I mean.
1238 //metrics_info_.pit1 = first pit of CoordCache;
1239 //metrics_info_.pit2 = last pit of CoordCache;
1240 //metrics_info_.singlepar = false;
1241 //metrics_info_.y1 = 0;
1242 //metrics_info_.y2 = height_;
1244 updateMetrics(false);
1247 // This event (moving without mouse click) is not passed further.
1248 // This should be changed if it is further utilized.
1252 // Build temporary cursor.
1253 Inset * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1255 // Put anchor at the same position.
1258 // Try to dispatch to an non-editable inset near this position
1259 // via the temp cursor. If the inset wishes to change the real
1260 // cursor it has to do so explicitly by using
1261 // cur.bv().cursor() = cur; (or similar)
1263 inset->dispatch(cur, cmd);
1266 // Now dispatch to the temporary cursor. If the real cursor should
1267 // be modified, the inset's dispatch has to do so explicitly.
1268 if (!cur.result().dispatched())
1271 // Redraw if requested and necessary.
1272 if (cur.result().dispatched() && cur.result().update())
1273 return update(cur.result().update());
1279 void BufferView::scroll(int /*lines*/)
1284 // Text const * t = &buffer_->text();
1285 // int const line_height = defaultRowHeight();
1287 // // The new absolute coordinate
1288 // int new_top_y = top_y() + lines * line_height;
1290 // // Restrict to a valid value
1291 // new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1292 // new_top_y = std::max(0, new_top_y);
1294 // scrollDocView(new_top_y);
1299 void BufferView::setCursorFromRow(int row)
1304 buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1307 buffer_->text().setCursor(cursor_, 0, 0);
1309 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1313 void BufferView::gotoLabel(docstring const & label)
1315 for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1316 vector<docstring> labels;
1317 it->getLabelList(*buffer_, labels);
1318 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1327 TextMetrics const & BufferView::textMetrics(Text const * t) const
1329 return const_cast<BufferView *>(this)->textMetrics(t);
1333 TextMetrics & BufferView::textMetrics(Text const * t)
1335 TextMetricsCache::iterator tmc_it = text_metrics_.find(t);
1336 if (tmc_it == text_metrics_.end()) {
1337 tmc_it = text_metrics_.insert(
1338 make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1340 return tmc_it->second;
1344 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1347 return textMetrics(t).parMetrics(pit);
1351 int BufferView::workHeight() const
1357 void BufferView::setCursor(DocIterator const & dit)
1359 size_t const n = dit.depth();
1360 for (size_t i = 0; i < n; ++i)
1361 dit[i].inset().edit(cursor_, true);
1363 cursor_.setCursor(dit);
1364 cursor_.selection() = false;
1368 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1370 // Would be wrong to delete anything if we have a selection.
1371 if (cur.selection())
1374 bool need_anchor_change = false;
1375 bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1376 need_anchor_change);
1378 if (need_anchor_change)
1384 updateLabels(*buffer_);
1386 updateMetrics(false);
1392 bool BufferView::mouseSetCursor(Cursor & cur)
1394 BOOST_ASSERT(&cur.bv() == this);
1396 // Has the cursor just left the inset?
1397 bool badcursor = false;
1398 bool leftinset = (&cursor_.inset() != &cur.inset());
1400 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1402 // do the dEPM magic if needed
1403 // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1404 // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1405 // the leftinset bool would not be necessary (badcursor instead).
1406 bool update = leftinset;
1407 if (!badcursor && cursor_.inTexted())
1408 update |= checkDepm(cur, cursor_);
1410 // if the cursor was in an empty script inset and the new
1411 // position is in the nucleus of the inset, notifyCursorLeaves
1412 // will kill the script inset itself. So we check all the
1413 // elements of the cursor to make sure that they are correct.
1414 // For an example, see bug 2933:
1415 // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1416 // The code below could maybe be moved to a DocIterator method.
1417 //lyxerr << "cur before " << cur <<std::endl;
1418 DocIterator dit(cur.inset());
1419 dit.push_back(cur.bottom());
1421 while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1422 dit.push_back(cur[i]);
1425 //lyxerr << "5 cur after" << dit <<std::endl;
1427 cursor_.setCursor(dit);
1428 cursor_.clearSelection();
1434 void BufferView::putSelectionAt(DocIterator const & cur,
1435 int length, bool backwards)
1437 cursor_.clearSelection();
1443 cursor_.pos() += length;
1444 cursor_.setSelection(cursor_, -length);
1446 cursor_.setSelection(cursor_, length);
1447 cap::saveSelection(cursor_);
1452 Cursor & BufferView::cursor()
1458 Cursor const & BufferView::cursor() const
1464 pit_type BufferView::anchor_ref() const
1470 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1472 return metrics_info_;
1476 // FIXME: We should split-up updateMetrics() for the singlepar case.
1477 void BufferView::updateMetrics(bool singlepar)
1479 Text & buftext = buffer_->text();
1480 TextMetrics & tm = textMetrics(&buftext);
1481 pit_type size = int(buftext.paragraphs().size());
1483 if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1484 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1488 // If the paragraph metrics has changed, we can not
1489 // use the singlepar optimisation.
1491 // In Single Paragraph mode, rebreak only
1492 // the (main text, not inset!) paragraph containing the cursor.
1493 // (if this paragraph contains insets etc., rebreaking will
1494 // recursively descend)
1495 && tm.redoParagraph(cursor_.bottom().pit()))
1498 pit_type const pit = anchor_ref_;
1501 size_t const npit = buftext.paragraphs().size();
1503 // Rebreak anchor paragraph.
1505 tm.redoParagraph(pit);
1507 // Clear out the position cache in case of full screen redraw.
1509 coord_cache_.clear();
1511 int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1513 // Redo paragraphs above anchor if necessary.
1515 while (y1 > 0 && pit1 > 0) {
1516 y1 -= tm.parMetrics(pit1).ascent();
1519 tm.redoParagraph(pit1);
1520 y1 -= tm.parMetrics(pit1).descent();
1524 // Take care of ascent of first line
1525 y1 -= tm.parMetrics(pit1).ascent();
1527 // Normalize anchor for next time
1531 // Grey at the beginning is ugly
1532 if (pit1 == 0 && y1 > 0) {
1538 // Redo paragraphs below the anchor if necessary.
1540 while (y2 < height_ && pit2 < int(npit) - 1) {
1541 y2 += tm.parMetrics(pit2).descent();
1544 tm.redoParagraph(pit2);
1545 y2 += tm.parMetrics(pit2).ascent();
1548 // Take care of descent of last line
1549 y2 += tm.parMetrics(pit2).descent();
1551 // The coordinates of all these paragraphs are correct, cache them
1553 CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1554 for (pit_type pit = pit1; pit <= pit2; ++pit) {
1555 ParagraphMetrics const & pm = tm.parMetrics(pit);
1557 parPos[pit] = Point(0, y);
1558 if (singlepar && pit == cursor_.bottom().pit()) {
1559 // In Single Paragraph mode, collect here the
1560 // y1 and y2 of the (one) paragraph the cursor is in
1561 y1 = y - pm.ascent();
1562 y2 = y + pm.descent();
1568 // collect cursor paragraph iter bounds
1569 pit1 = cursor_.bottom().pit();
1570 pit2 = cursor_.bottom().pit();
1573 LYXERR(Debug::DEBUG)
1574 << BOOST_CURRENT_FUNCTION
1577 << " pit1: " << pit1
1578 << " pit2: " << pit2
1579 << " npit: " << npit
1580 << " singlepar: " << singlepar
1584 metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1585 singlepar? SingleParUpdate: FullScreenUpdate, size);
1587 if (lyxerr.debugging(Debug::WORKAREA)) {
1588 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1589 coord_cache_.dump();
1594 void BufferView::menuInsertLyXFile(string const & filenm)
1596 BOOST_ASSERT(cursor_.inTexted());
1597 string filename = filenm;
1599 if (filename.empty()) {
1600 // Launch a file browser
1602 string initpath = lyxrc.document_path;
1605 string const trypath = buffer_->filePath();
1606 // If directory is writeable, use this as default.
1607 if (isDirWriteable(FileName(trypath)))
1612 FileDialog fileDlg(_("Select LyX document to insert"),
1614 make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1615 make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support().absFilename(), "examples"))));
1617 FileDialog::Result result =
1618 fileDlg.open(from_utf8(initpath),
1619 FileFilterList(_("LyX Documents (*.lyx)")),
1622 if (result.first == FileDialog::Later)
1626 filename = to_utf8(result.second);
1628 // check selected filename
1629 if (filename.empty()) {
1630 // emit message signal.
1631 message(_("Canceled."));
1636 // Get absolute path of file and add ".lyx"
1637 // to the filename if necessary
1638 filename = fileSearch(string(), filename, "lyx").absFilename();
1640 docstring const disp_fn = makeDisplayPath(filename);
1641 // emit message signal.
1642 message(bformat(_("Inserting document %1$s..."), disp_fn));
1645 Buffer buf("", false);
1646 if (lyx::loadLyXFile(&buf, FileName(filename))) {
1647 ErrorList & el = buffer_->errorList("Parse");
1648 // Copy the inserted document error list into the current buffer one.
1649 el = buf.errorList("Parse");
1650 recordUndo(cursor_);
1651 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1652 buf.params().textclass, el);
1653 res = _("Document %1$s inserted.");
1655 res = _("Could not insert document %1$s");
1657 // emit message signal.
1658 message(bformat(res, disp_fn));
1659 buffer_->errors("Parse");