3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/PathChanger.h"
103 #include "support/Systemcall.h"
104 #include "support/TempFile.h"
105 #include "support/textutils.h"
106 #include "support/types.h"
108 #include "support/bind.h"
109 #include "support/shared_ptr.h"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
221 typedef pair<DocIterator, MacroData> ScopeMacro;
222 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224 /// map from the macro name to the position map,
225 /// which maps the macro definition position to the scope and the MacroData.
226 NamePositionScopeMacroMap macros;
227 /// This seem to change the way Buffer::getMacro() works
228 mutable bool macro_lock;
230 /// positions of child buffers in the buffer
231 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Container for all sort of Buffer dependant errors.
240 map<string, ErrorList> errorLists;
242 /// timestamp and checksum used to test if the file has been externally
243 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable support::FileNameList bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// whether the bibinfo cache is valid
266 mutable bool bibinfo_cache_valid_;
267 /// whether the bibfile cache is valid
268 mutable bool bibfile_cache_valid_;
269 /// Cache of timestamps of .bib files
270 map<FileName, time_t> bibfile_status_;
271 /// Indicates whether the bibinfo has changed since the last time
272 /// we ran updateBuffer(), i.e., whether citation labels may need
274 mutable bool cite_labels_valid_;
276 mutable RefCache ref_cache_;
278 /// our Text that should be wrapped in an InsetText
282 PreviewLoader * preview_loader_;
284 /// This is here to force the test to be done whenever parent_buffer
286 Buffer const * parent() const
288 // ignore_parent temporarily "orphans" a buffer
289 // (e.g. if a child is compiled standalone)
292 // if parent_buffer is not loaded, then it has been unloaded,
293 // which means that parent_buffer is an invalid pointer. So we
294 // set it to null in that case.
295 // however, the BufferList doesn't know about cloned buffers, so
296 // they will always be regarded as unloaded. in that case, we hope
298 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
300 return parent_buffer;
304 void setParent(Buffer const * pb)
306 if (parent_buffer == pb)
309 if (!cloned_buffer_ && parent_buffer && pb)
310 LYXERR0("Warning: a buffer should not have two parents!");
312 if (!cloned_buffer_ && parent_buffer) {
313 parent_buffer->invalidateBibfileCache();
314 parent_buffer->invalidateBibinfoCache();
318 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
319 /// This one is useful for preview detached in a thread.
320 Buffer const * cloned_buffer_;
322 CloneList * clone_list_;
323 /// are we in the process of exporting this buffer?
324 mutable bool doing_export;
326 /// compute statistics
327 /// \p from initial position
328 /// \p to points to the end position
329 void updateStatistics(DocIterator & from, DocIterator & to,
330 bool skipNoOutput = true);
331 /// statistics accessor functions
332 int wordCount() const
336 int charCount(bool with_blanks) const
339 + (with_blanks ? blank_count_ : 0);
343 /// So we can force access via the accessors.
344 mutable Buffer const * parent_buffer;
353 /// Creates the per buffer temporary directory
354 static FileName createBufferTmpDir()
358 // We are in our own directory. Why bother to mangle name?
359 // In fact I wrote this code to circumvent a problematic behaviour
360 // (bug?) of EMX mkstemp().
361 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
362 convert<string>(count++));
364 if (!tmpfl.createDirectory(0777)) {
365 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
366 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
367 from_utf8(tmpfl.absFileName())));
373 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
374 Buffer const * cloned_buffer)
375 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
376 internal_buffer(false), read_only(readonly_), filename(file),
377 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
378 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
379 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
380 cite_labels_valid_(false), preview_loader_(0),
381 cloned_buffer_(cloned_buffer), clone_list_(0),
382 doing_export(false), parent_buffer(0)
384 if (!cloned_buffer_) {
385 temppath = createBufferTmpDir();
386 lyxvc.setBuffer(owner_);
388 wa_ = new frontend::WorkAreaManager;
391 temppath = cloned_buffer_->d->temppath;
392 file_fully_loaded = true;
393 params = cloned_buffer_->d->params;
394 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
395 bibinfo_ = cloned_buffer_->d->bibinfo_;
396 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
397 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
398 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
399 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
400 unnamed = cloned_buffer_->d->unnamed;
401 internal_buffer = cloned_buffer_->d->internal_buffer;
405 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
406 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
408 LYXERR(Debug::INFO, "Buffer::Buffer()");
410 d->inset = new InsetText(*cloned_buffer->d->inset);
411 d->inset->setBuffer(*this);
412 // FIXME: optimize this loop somewhat, maybe by creating a new
413 // general recursive Inset::setId().
414 DocIterator it = doc_iterator_begin(this);
415 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
416 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
417 it.paragraph().setId(cloned_it.paragraph().id());
419 d->inset = new InsetText(this);
420 d->inset->setAutoBreakRows(true);
421 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
427 LYXERR(Debug::INFO, "Buffer::~Buffer()");
428 // here the buffer should take care that it is
429 // saved properly, before it goes into the void.
431 // GuiView already destroyed
435 // No need to do additional cleanups for internal buffer.
441 // this is in case of recursive includes: we won't try to delete
442 // ourselves as a child.
443 d->clone_list_->erase(this);
444 // loop over children
445 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
446 Impl::BufferPositionMap::iterator end = d->children_positions.end();
447 for (; it != end; ++it) {
448 Buffer * child = const_cast<Buffer *>(it->first);
449 if (d->clone_list_->erase(child))
452 // if we're the master buffer, then we should get rid of the list
455 // If this is not empty, we have leaked something. Worse, one of the
456 // children still has a reference to this list. But we will try to
457 // continue, rather than shut down.
458 LATTEST(d->clone_list_->empty());
459 list<CloneList *>::iterator it =
460 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
461 if (it == cloned_buffers.end()) {
462 // We will leak in this case, but it is safe to continue.
465 cloned_buffers.erase(it);
466 delete d->clone_list_;
468 // FIXME Do we really need to do this right before we delete d?
469 // clear references to children in macro tables
470 d->children_positions.clear();
471 d->position_to_children.clear();
473 // loop over children
474 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
475 Impl::BufferPositionMap::iterator end = d->children_positions.end();
476 for (; it != end; ++it) {
477 Buffer * child = const_cast<Buffer *>(it->first);
478 if (theBufferList().isLoaded(child))
479 theBufferList().releaseChild(this, child);
483 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
484 msg += emergencyWrite();
485 Alert::warning(_("Attempting to close changed document!"), msg);
488 // FIXME Do we really need to do this right before we delete d?
489 // clear references to children in macro tables
490 d->children_positions.clear();
491 d->position_to_children.clear();
493 if (!d->temppath.destroyDirectory()) {
494 Alert::warning(_("Could not remove temporary directory"),
495 bformat(_("Could not remove the temporary directory %1$s"),
496 from_utf8(d->temppath.absFileName())));
505 Buffer * Buffer::cloneFromMaster() const
508 cloned_buffers.push_back(new CloneList);
509 CloneList * clones = cloned_buffers.back();
511 masterBuffer()->cloneWithChildren(bufmap, clones);
513 // make sure we got cloned
514 BufferMap::const_iterator bit = bufmap.find(this);
515 LASSERT(bit != bufmap.end(), return 0);
516 Buffer * cloned_buffer = bit->second;
518 return cloned_buffer;
522 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
524 // have we already been cloned?
525 if (bufmap.find(this) != bufmap.end())
528 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
530 // The clone needs its own DocumentClass, since running updateBuffer() will
531 // modify it, and we would otherwise be sharing it with the original Buffer.
532 buffer_clone->params().makeDocumentClass(true);
534 cap::switchBetweenClasses(
535 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
536 static_cast<InsetText &>(buffer_clone->inset()), el);
538 bufmap[this] = buffer_clone;
539 clones->insert(buffer_clone);
540 buffer_clone->d->clone_list_ = clones;
541 buffer_clone->d->macro_lock = true;
542 buffer_clone->d->children_positions.clear();
544 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
545 // math macro caches need to be rethought and simplified.
546 // I am not sure wether we should handle Buffer cloning here or in BufferList.
547 // Right now BufferList knows nothing about buffer clones.
548 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
549 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
550 for (; it != end; ++it) {
551 DocIterator dit = it->first.clone(buffer_clone);
552 dit.setBuffer(buffer_clone);
553 Buffer * child = const_cast<Buffer *>(it->second.second);
555 child->cloneWithChildren(bufmap, clones);
556 BufferMap::iterator const bit = bufmap.find(child);
557 LASSERT(bit != bufmap.end(), continue);
558 Buffer * child_clone = bit->second;
560 Inset * inset = dit.nextInset();
561 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
562 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
563 inset_inc->setChildBuffer(child_clone);
564 child_clone->d->setParent(buffer_clone);
565 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
566 buffer_clone->setChild(dit, child_clone);
568 buffer_clone->d->macro_lock = false;
573 Buffer * Buffer::cloneBufferOnly() const {
574 cloned_buffers.push_back(new CloneList);
575 CloneList * clones = cloned_buffers.back();
576 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
578 // The clone needs its own DocumentClass, since running updateBuffer() will
579 // modify it, and we would otherwise be sharing it with the original Buffer.
580 buffer_clone->params().makeDocumentClass(true);
582 cap::switchBetweenClasses(
583 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
584 static_cast<InsetText &>(buffer_clone->inset()), el);
586 clones->insert(buffer_clone);
587 buffer_clone->d->clone_list_ = clones;
589 // we won't be cloning the children
590 buffer_clone->d->children_positions.clear();
595 bool Buffer::isClone() const
597 return d->cloned_buffer_;
601 void Buffer::changed(bool update_metrics) const
604 d->wa_->redrawAll(update_metrics);
608 frontend::WorkAreaManager & Buffer::workAreaManager() const
615 Text & Buffer::text() const
617 return d->inset->text();
621 Inset & Buffer::inset() const
627 BufferParams & Buffer::params()
633 BufferParams const & Buffer::params() const
639 BufferParams const & Buffer::masterParams() const
641 if (masterBuffer() == this)
644 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
645 // Copy child authors to the params. We need those pointers.
646 AuthorList const & child_authors = params().authors();
647 AuthorList::Authors::const_iterator it = child_authors.begin();
648 for (; it != child_authors.end(); it++)
649 mparams.authors().record(*it);
654 ParagraphList & Buffer::paragraphs()
656 return text().paragraphs();
660 ParagraphList const & Buffer::paragraphs() const
662 return text().paragraphs();
666 LyXVC & Buffer::lyxvc()
672 LyXVC const & Buffer::lyxvc() const
678 string const Buffer::temppath() const
680 return d->temppath.absFileName();
684 TexRow & Buffer::texrow()
690 TexRow const & Buffer::texrow() const
696 TocBackend & Buffer::tocBackend() const
698 return d->toc_backend;
702 Undo & Buffer::undo()
708 void Buffer::setChild(DocIterator const & dit, Buffer * child)
710 d->children_positions[child] = dit;
714 string Buffer::latexName(bool const no_path) const
716 FileName latex_name =
717 makeLatexName(d->exportFileName());
718 return no_path ? latex_name.onlyFileName()
719 : latex_name.absFileName();
723 FileName Buffer::Impl::exportFileName() const
725 docstring const branch_suffix =
726 params.branchlist().getFileNameSuffix();
727 if (branch_suffix.empty())
730 string const name = filename.onlyFileNameWithoutExt()
731 + to_utf8(branch_suffix);
732 FileName res(filename.onlyPath().absFileName() + "/" + name);
733 res.changeExtension(filename.extension());
739 string Buffer::logName(LogType * type) const
741 string const filename = latexName(false);
743 if (filename.empty()) {
749 string const path = temppath();
751 FileName const fname(addName(temppath(),
752 onlyFileName(changeExtension(filename,
755 // FIXME: how do we know this is the name of the build log?
756 FileName const bname(
757 addName(path, onlyFileName(
758 changeExtension(filename,
759 formats.extension(params().bufferFormat()) + ".out"))));
761 // Also consider the master buffer log file
762 FileName masterfname = fname;
764 if (masterBuffer() != this) {
765 string const mlogfile = masterBuffer()->logName(&mtype);
766 masterfname = FileName(mlogfile);
769 // If no Latex log or Build log is newer, show Build log
770 if (bname.exists() &&
771 ((!fname.exists() && !masterfname.exists())
772 || (fname.lastModified() < bname.lastModified()
773 && masterfname.lastModified() < bname.lastModified()))) {
774 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
777 return bname.absFileName();
778 // If we have a newer master file log or only a master log, show this
779 } else if (fname != masterfname
780 && (!fname.exists() && (masterfname.exists()
781 || fname.lastModified() < masterfname.lastModified()))) {
782 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
785 return masterfname.absFileName();
787 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
790 return fname.absFileName();
794 void Buffer::setReadonly(bool const flag)
796 if (d->read_only != flag) {
803 void Buffer::setFileName(FileName const & fname)
805 bool const changed = fname != d->filename;
808 lyxvc().file_found_hook(fname);
809 setReadonly(d->filename.isReadOnly());
815 int Buffer::readHeader(Lexer & lex)
817 int unknown_tokens = 0;
819 int begin_header_line = -1;
821 // Initialize parameters that may be/go lacking in header:
822 params().branchlist().clear();
823 params().preamble.erase();
824 params().options.erase();
825 params().master.erase();
826 params().float_placement.erase();
827 params().paperwidth.erase();
828 params().paperheight.erase();
829 params().leftmargin.erase();
830 params().rightmargin.erase();
831 params().topmargin.erase();
832 params().bottommargin.erase();
833 params().headheight.erase();
834 params().headsep.erase();
835 params().footskip.erase();
836 params().columnsep.erase();
837 params().fonts_cjk.erase();
838 params().listings_params.clear();
839 params().clearLayoutModules();
840 params().clearRemovedModules();
841 params().clearIncludedChildren();
842 params().pdfoptions().clear();
843 params().indiceslist().clear();
844 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
845 params().isbackgroundcolor = false;
846 params().fontcolor = RGBColor(0, 0, 0);
847 params().isfontcolor = false;
848 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
849 params().boxbgcolor = RGBColor(0xFF, 0, 0);
850 params().html_latex_start.clear();
851 params().html_latex_end.clear();
852 params().html_math_img_scale = 1.0;
853 params().output_sync_macro.erase();
854 params().setLocalLayout(string(), false);
855 params().setLocalLayout(string(), true);
857 for (int i = 0; i < 4; ++i) {
858 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
859 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
862 ErrorList & errorList = d->errorLists["Parse"];
871 if (token == "\\end_header")
875 if (token == "\\begin_header") {
876 begin_header_line = line;
880 LYXERR(Debug::PARSER, "Handling document header token: `"
883 string unknown = params().readToken(lex, token, d->filename.onlyPath());
884 if (!unknown.empty()) {
885 if (unknown[0] != '\\' && token == "\\textclass") {
886 Alert::warning(_("Unknown document class"),
887 bformat(_("Using the default document class, because the "
888 "class %1$s is unknown."), from_utf8(unknown)));
891 docstring const s = bformat(_("Unknown token: "
895 errorList.push_back(ErrorItem(_("Document header error"),
900 if (begin_header_line) {
901 docstring const s = _("\\begin_header is missing");
902 errorList.push_back(ErrorItem(_("Document header error"),
906 params().makeDocumentClass();
908 return unknown_tokens;
913 // changed to be public and have one parameter
914 // Returns true if "\end_document" is not read (Asger)
915 bool Buffer::readDocument(Lexer & lex)
917 ErrorList & errorList = d->errorLists["Parse"];
920 // remove dummy empty par
921 paragraphs().clear();
923 if (!lex.checkFor("\\begin_document")) {
924 docstring const s = _("\\begin_document is missing");
925 errorList.push_back(ErrorItem(_("Document header error"),
931 if (params().output_changes) {
932 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
933 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
934 LaTeXFeatures::isAvailable("xcolor");
936 if (!dvipost && !xcolorulem) {
937 Alert::warning(_("Changes not shown in LaTeX output"),
938 _("Changes will not be highlighted in LaTeX output, "
939 "because neither dvipost nor xcolor/ulem are installed.\n"
940 "Please install these packages or redefine "
941 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
942 } else if (!xcolorulem) {
943 Alert::warning(_("Changes not shown in LaTeX output"),
944 _("Changes will not be highlighted in LaTeX output "
945 "when using pdflatex, because xcolor and ulem are not installed.\n"
946 "Please install both packages or redefine "
947 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
951 if (!parent() && !params().master.empty()) {
952 FileName const master_file = makeAbsPath(params().master,
953 onlyPath(absFileName()));
954 if (isLyXFileName(master_file.absFileName())) {
956 checkAndLoadLyXFile(master_file, true);
958 // necessary e.g. after a reload
959 // to re-register the child (bug 5873)
960 // FIXME: clean up updateMacros (here, only
961 // child registering is needed).
962 master->updateMacros();
963 // set master as master buffer, but only
964 // if we are a real child
965 if (master->isChild(this))
967 // if the master is not fully loaded
968 // it is probably just loading this
969 // child. No warning needed then.
970 else if (master->isFullyLoaded())
971 LYXERR0("The master '"
973 << "' assigned to this document ("
975 << ") does not include "
976 "this document. Ignoring the master assignment.");
981 // assure we have a default index
982 params().indiceslist().addDefault(B_("Index"));
985 bool const res = text().read(lex, errorList, d->inset);
987 // inform parent buffer about local macros
989 Buffer const * pbuf = parent();
990 UserMacroSet::const_iterator cit = usermacros.begin();
991 UserMacroSet::const_iterator end = usermacros.end();
992 for (; cit != end; ++cit)
993 pbuf->usermacros.insert(*cit);
997 updateMacroInstances(InternalUpdate);
1002 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1004 Format const * fmt = formats.getFormat(format);
1007 // It is important to use the correct extension here, since some
1008 // converters create a wrong output file otherwise (e.g. html2latex)
1009 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1010 FileName const name(tempfile.name());
1011 ofdocstream os(name.toFilesystemEncoding().c_str());
1012 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1013 bool const success = !(os << contents).fail();
1016 bool converted = false;
1018 params().compressed = false;
1020 // remove dummy empty par
1021 paragraphs().clear();
1023 converted = importFile(format, name, errorList);
1032 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1034 if (!theConverters().isReachable(format, "lyx"))
1037 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1038 FileName const lyx(tempfile.name());
1039 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1040 return readFile(lyx) == ReadSuccess;
1046 bool Buffer::readString(string const & s)
1048 params().compressed = false;
1051 istringstream is(s);
1053 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1054 FileName const fn = tempfile.name();
1057 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1059 if (success && file_format != LYX_FORMAT) {
1060 // We need to call lyx2lyx, so write the input to a file
1061 ofstream os(fn.toFilesystemEncoding().c_str());
1064 // lyxvc in readFile
1065 if (readFile(fn) != ReadSuccess)
1069 if (readDocument(lex))
1075 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1079 if (!lex.setFile(fname)) {
1080 Alert::error(_("File Not Found"),
1081 bformat(_("Unable to open file `%1$s'."),
1082 from_utf8(fn.absFileName())));
1083 return ReadFileNotFound;
1087 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1088 if (ret_plf != ReadSuccess)
1091 if (file_format != LYX_FORMAT) {
1093 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1094 if (ret_clf != ReadSuccess)
1096 return readFile(tmpFile);
1099 // FIXME: InsetInfo needs to know whether the file is under VCS
1100 // during the parse process, so this has to be done before.
1101 lyxvc().file_found_hook(d->filename);
1103 if (readDocument(lex)) {
1104 Alert::error(_("Document format failure"),
1105 bformat(_("%1$s ended unexpectedly, which means"
1106 " that it is probably corrupted."),
1107 from_utf8(fn.absFileName())));
1108 return ReadDocumentFailure;
1111 d->file_fully_loaded = true;
1112 d->read_only = !d->filename.isWritable();
1113 params().compressed = formats.isZippedFile(d->filename);
1119 bool Buffer::isFullyLoaded() const
1121 return d->file_fully_loaded;
1125 void Buffer::setFullyLoaded(bool value)
1127 d->file_fully_loaded = value;
1131 PreviewLoader * Buffer::loader() const
1133 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1135 if (!d->preview_loader_)
1136 d->preview_loader_ = new PreviewLoader(*this);
1137 return d->preview_loader_;
1141 void Buffer::removePreviews() const
1143 delete d->preview_loader_;
1144 d->preview_loader_ = 0;
1148 void Buffer::updatePreviews() const
1150 PreviewLoader * ploader = loader();
1154 InsetIterator it = inset_iterator_begin(*d->inset);
1155 InsetIterator const end = inset_iterator_end(*d->inset);
1156 for (; it != end; ++it)
1157 it->addPreview(it, *ploader);
1159 ploader->startLoading();
1163 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1164 FileName const & fn, int & file_format) const
1166 if(!lex.checkFor("\\lyxformat")) {
1167 Alert::error(_("Document format failure"),
1168 bformat(_("%1$s is not a readable LyX document."),
1169 from_utf8(fn.absFileName())));
1170 return ReadNoLyXFormat;
1176 // LyX formats 217 and earlier were written as 2.17. This corresponds
1177 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1178 // these cases. See also: www.lyx.org/trac/changeset/1313.
1179 size_t dot = tmp_format.find_first_of(".,");
1180 if (dot != string::npos)
1181 tmp_format.erase(dot, 1);
1183 file_format = convert<int>(tmp_format);
1188 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1189 FileName & tmpfile, int from_format)
1191 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1192 tempfile.setAutoRemove(false);
1193 tmpfile = tempfile.name();
1194 if(tmpfile.empty()) {
1195 Alert::error(_("Conversion failed"),
1196 bformat(_("%1$s is from a different"
1197 " version of LyX, but a temporary"
1198 " file for converting it could"
1199 " not be created."),
1200 from_utf8(fn.absFileName())));
1201 return LyX2LyXNoTempFile;
1204 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1205 if (lyx2lyx.empty()) {
1206 Alert::error(_("Conversion script not found"),
1207 bformat(_("%1$s is from a different"
1208 " version of LyX, but the"
1209 " conversion script lyx2lyx"
1210 " could not be found."),
1211 from_utf8(fn.absFileName())));
1212 return LyX2LyXNotFound;
1216 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1217 ostringstream command;
1218 command << os::python()
1219 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1220 << " -t " << convert<string>(LYX_FORMAT)
1221 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1222 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1223 string const command_str = command.str();
1225 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1227 cmd_ret const ret = runCommand(command_str);
1228 if (ret.first != 0) {
1229 if (from_format < LYX_FORMAT) {
1230 Alert::error(_("Conversion script failed"),
1231 bformat(_("%1$s is from an older version"
1232 " of LyX and the lyx2lyx script"
1233 " failed to convert it."),
1234 from_utf8(fn.absFileName())));
1235 return LyX2LyXOlderFormat;
1237 Alert::error(_("Conversion script failed"),
1238 bformat(_("%1$s is from a newer version"
1239 " of LyX and the lyx2lyx script"
1240 " failed to convert it."),
1241 from_utf8(fn.absFileName())));
1242 return LyX2LyXNewerFormat;
1249 // Should probably be moved to somewhere else: BufferView? GuiView?
1250 bool Buffer::save() const
1252 docstring const file = makeDisplayPath(absFileName(), 20);
1253 d->filename.refresh();
1255 // check the read-only status before moving the file as a backup
1256 if (d->filename.exists()) {
1257 bool const read_only = !d->filename.isWritable();
1259 Alert::warning(_("File is read-only"),
1260 bformat(_("The file %1$s cannot be written because it "
1261 "is marked as read-only."), file));
1266 // ask if the disk file has been externally modified (use checksum method)
1267 if (fileName().exists() && isExternallyModified(checksum_method)) {
1269 bformat(_("Document %1$s has been externally modified. "
1270 "Are you sure you want to overwrite this file?"), file);
1271 int const ret = Alert::prompt(_("Overwrite modified file?"),
1272 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1277 // We don't need autosaves in the immediate future. (Asger)
1278 resetAutosaveTimers();
1280 // if the file does not yet exist, none of the backup activity
1281 // that follows is necessary
1282 if (!fileName().exists())
1283 return writeFile(fileName());
1285 // we first write the file to a new name, then move it to its
1286 // proper location once that has been done successfully. that
1287 // way we preserve the original file if something goes wrong.
1288 TempFile tempfile(fileName().onlyPath(), "tmpXXXXXX.lyx");
1289 FileName savefile(tempfile.name());
1291 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1292 if (!writeFile(savefile))
1295 // we will set this to false if we fail
1296 bool made_backup = true;
1297 bool const symlink = fileName().isSymLink();
1298 if (lyxrc.make_backup) {
1299 FileName backupName(absFileName() + '~');
1300 if (!lyxrc.backupdir_path.empty()) {
1301 string const mangledName =
1302 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1303 backupName = FileName(addName(lyxrc.backupdir_path,
1307 // Except file is symlink do not copy because of #6587.
1308 // Hard links have bad luck.
1309 made_backup = symlink ?
1310 fileName().copyTo(backupName):
1311 fileName().moveTo(backupName);
1314 Alert::error(_("Backup failure"),
1315 bformat(_("Cannot create backup file %1$s.\n"
1316 "Please check whether the directory exists and is writable."),
1317 from_utf8(backupName.absFileName())));
1318 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1322 // If we have no symlink, we can simply rename the temp file.
1323 // Otherwise, we need to copy it so the symlink stays intact.
1325 tempfile.setAutoRemove(false);
1327 (symlink ? savefile.copyTo(fileName(), true) : savefile.moveTo(fileName()))) {
1332 Alert::error(_("Write failure"),
1333 bformat(_("Cannot move saved file to:\n %1$s.\n"
1334 "But the file has successfully been saved as:\n %2$s."),
1335 from_utf8(fileName().absFileName()),
1336 from_utf8(savefile.absFileName())));
1341 bool Buffer::writeFile(FileName const & fname) const
1343 if (d->read_only && fname == d->filename)
1346 bool retval = false;
1348 docstring const str = bformat(_("Saving document %1$s..."),
1349 makeDisplayPath(fname.absFileName()));
1352 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1354 if (params().compressed) {
1355 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1356 retval = ofs && write(ofs);
1358 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1359 retval = ofs && write(ofs);
1363 message(str + _(" could not write file!"));
1368 // removeAutosaveFile();
1371 message(str + _(" done."));
1377 docstring Buffer::emergencyWrite()
1379 // No need to save if the buffer has not changed.
1383 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1385 docstring user_message = bformat(
1386 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1388 // We try to save three places:
1389 // 1) Same place as document. Unless it is an unnamed doc.
1391 string s = absFileName();
1394 if (writeFile(FileName(s))) {
1396 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1397 return user_message;
1399 user_message += " " + _("Save failed! Trying again...\n");
1403 // 2) In HOME directory.
1404 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1406 lyxerr << ' ' << s << endl;
1407 if (writeFile(FileName(s))) {
1409 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1410 return user_message;
1413 user_message += " " + _("Save failed! Trying yet again...\n");
1415 // 3) In "/tmp" directory.
1416 // MakeAbsPath to prepend the current
1417 // drive letter on OS/2
1418 s = addName(package().temp_dir().absFileName(), absFileName());
1420 lyxerr << ' ' << s << endl;
1421 if (writeFile(FileName(s))) {
1423 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1424 return user_message;
1427 user_message += " " + _("Save failed! Bummer. Document is lost.");
1430 return user_message;
1434 bool Buffer::write(ostream & ofs) const
1437 // Use the standard "C" locale for file output.
1438 ofs.imbue(locale::classic());
1441 // The top of the file should not be written by params().
1443 // write out a comment in the top of the file
1444 // Important: Keep the version formatting in sync with lyx2lyx and
1445 // tex2lyx (bug 7951)
1446 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1447 << " created this file. For more info see http://www.lyx.org/\n"
1448 << "\\lyxformat " << LYX_FORMAT << "\n"
1449 << "\\begin_document\n";
1451 /// For each author, set 'used' to true if there is a change
1452 /// by this author in the document; otherwise set it to 'false'.
1453 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1454 AuthorList::Authors::const_iterator a_end = params().authors().end();
1455 for (; a_it != a_end; ++a_it)
1456 a_it->setUsed(false);
1458 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1459 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1460 for ( ; it != end; ++it)
1461 it->checkAuthors(params().authors());
1463 // now write out the buffer parameters.
1464 ofs << "\\begin_header\n";
1465 params().writeFile(ofs);
1466 ofs << "\\end_header\n";
1469 ofs << "\n\\begin_body\n";
1471 ofs << "\n\\end_body\n";
1473 // Write marker that shows file is complete
1474 ofs << "\\end_document" << endl;
1476 // Shouldn't really be needed....
1479 // how to check if close went ok?
1480 // Following is an attempt... (BE 20001011)
1482 // good() returns false if any error occured, including some
1483 // formatting error.
1484 // bad() returns true if something bad happened in the buffer,
1485 // which should include file system full errors.
1490 lyxerr << "File was not closed properly." << endl;
1497 bool Buffer::makeLaTeXFile(FileName const & fname,
1498 string const & original_path,
1499 OutputParams const & runparams_in,
1500 OutputWhat output) const
1502 OutputParams runparams = runparams_in;
1504 // This is necessary for LuaTeX/XeTeX with tex fonts.
1505 // See FIXME in BufferParams::encoding()
1506 if (runparams.isFullUnicode())
1507 runparams.encoding = encodings.fromLyXName("utf8-plain");
1509 string const encoding = runparams.encoding->iconvName();
1510 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1513 try { ofs.reset(encoding); }
1514 catch (iconv_codecvt_facet_exception const & e) {
1515 lyxerr << "Caught iconv exception: " << e.what() << endl;
1516 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1517 "verify that the support software for your encoding (%1$s) is "
1518 "properly installed"), from_ascii(encoding)));
1521 if (!openFileWrite(ofs, fname))
1524 ErrorList & errorList = d->errorLists["Export"];
1526 bool failed_export = false;
1527 otexstream os(ofs, d->texrow);
1529 // make sure we are ready to export
1530 // this needs to be done before we validate
1531 // FIXME Do we need to do this all the time? I.e., in children
1532 // of a master we are exporting?
1534 updateMacroInstances(OutputUpdate);
1537 os.texrow().reset();
1538 writeLaTeXSource(os, original_path, runparams, output);
1540 catch (EncodingException const & e) {
1541 odocstringstream ods;
1542 ods.put(e.failed_char);
1544 oss << "0x" << hex << e.failed_char << dec;
1545 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1546 " (code point %2$s)"),
1547 ods.str(), from_utf8(oss.str()));
1548 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1549 "representable in the chosen encoding.\n"
1550 "Changing the document encoding to utf8 could help."),
1551 e.par_id, e.pos, e.pos + 1));
1552 failed_export = true;
1554 catch (iconv_codecvt_facet_exception const & e) {
1555 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1556 _(e.what()), -1, 0, 0));
1557 failed_export = true;
1559 catch (exception const & e) {
1560 errorList.push_back(ErrorItem(_("conversion failed"),
1561 _(e.what()), -1, 0, 0));
1562 failed_export = true;
1565 lyxerr << "Caught some really weird exception..." << endl;
1571 failed_export = true;
1572 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1575 if (runparams_in.silent)
1579 return !failed_export;
1583 void Buffer::writeLaTeXSource(otexstream & os,
1584 string const & original_path,
1585 OutputParams const & runparams_in,
1586 OutputWhat output) const
1588 // The child documents, if any, shall be already loaded at this point.
1590 OutputParams runparams = runparams_in;
1592 // If we are compiling a file standalone, even if this is the
1593 // child of some other buffer, let's cut the link here, so the
1594 // file is really independent and no concurring settings from
1595 // the master (e.g. branch state) interfere (see #8100).
1596 if (!runparams.is_child)
1597 d->ignore_parent = true;
1599 // Classify the unicode characters appearing in math insets
1600 BufferEncodings::initUnicodeMath(*this);
1602 // validate the buffer.
1603 LYXERR(Debug::LATEX, " Validating buffer...");
1604 LaTeXFeatures features(*this, params(), runparams);
1606 // This is only set once per document (in master)
1607 if (!runparams.is_child)
1608 runparams.use_polyglossia = features.usePolyglossia();
1609 LYXERR(Debug::LATEX, " Buffer validation done.");
1611 bool const output_preamble =
1612 output == FullSource || output == OnlyPreamble;
1613 bool const output_body =
1614 output == FullSource || output == OnlyBody;
1616 // The starting paragraph of the coming rows is the
1617 // first paragraph of the document. (Asger)
1618 if (output_preamble && runparams.nice) {
1619 os << "%% LyX " << lyx_version << " created this file. "
1620 "For more info, see http://www.lyx.org/.\n"
1621 "%% Do not edit unless you really know what "
1624 LYXERR(Debug::INFO, "lyx document header finished");
1626 // There are a few differences between nice LaTeX and usual files:
1627 // usual files have \batchmode and special input@path to allow
1628 // inclusion of figures specified by an explicitly relative path
1629 // (i.e., a path starting with './' or '../') with either \input or
1630 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1631 // input@path is set when the actual parameter original_path is set.
1632 // This is done for usual tex-file, but not for nice-latex-file.
1633 // (Matthias 250696)
1634 // Note that input@path is only needed for something the user does
1635 // in the preamble, included .tex files or ERT, files included by
1636 // LyX work without it.
1637 if (output_preamble) {
1638 if (!runparams.nice) {
1639 // code for usual, NOT nice-latex-file
1640 os << "\\batchmode\n"; // changed from \nonstopmode
1642 if (!original_path.empty()) {
1644 // We don't know the encoding of inputpath
1645 docstring const inputpath = from_utf8(original_path);
1646 docstring uncodable_glyphs;
1647 Encoding const * const enc = runparams.encoding;
1649 for (size_t n = 0; n < inputpath.size(); ++n) {
1650 if (!enc->encodable(inputpath[n])) {
1651 docstring const glyph(1, inputpath[n]);
1652 LYXERR0("Uncodable character '"
1654 << "' in input path!");
1655 uncodable_glyphs += glyph;
1660 // warn user if we found uncodable glyphs.
1661 if (!uncodable_glyphs.empty()) {
1662 frontend::Alert::warning(
1663 _("Uncodable character in file path"),
1665 _("The path of your document\n"
1667 "contains glyphs that are unknown "
1668 "in the current document encoding "
1669 "(namely %2$s). This may result in "
1670 "incomplete output, unless "
1671 "TEXINPUTS contains the document "
1672 "directory and you don't use "
1673 "explicitly relative paths (i.e., "
1674 "paths starting with './' or "
1675 "'../') in the preamble or in ERT."
1676 "\n\nIn case of problems, choose "
1677 "an appropriate document encoding\n"
1678 "(such as utf8) or change the "
1680 inputpath, uncodable_glyphs));
1683 support::latex_path(original_path);
1684 if (contains(docdir, '#')) {
1685 docdir = subst(docdir, "#", "\\#");
1686 os << "\\catcode`\\#=11"
1687 "\\def\\#{#}\\catcode`\\#=6\n";
1689 if (contains(docdir, '%')) {
1690 docdir = subst(docdir, "%", "\\%");
1691 os << "\\catcode`\\%=11"
1692 "\\def\\%{%}\\catcode`\\%=14\n";
1694 os << "\\makeatletter\n"
1695 << "\\def\\input@path{{"
1696 << docdir << "/}}\n"
1697 << "\\makeatother\n";
1701 // get parent macros (if this buffer has a parent) which will be
1702 // written at the document begin further down.
1703 MacroSet parentMacros;
1704 listParentMacros(parentMacros, features);
1706 // Write the preamble
1707 runparams.use_babel = params().writeLaTeX(os, features,
1708 d->filename.onlyPath());
1710 // Japanese might be required only in some children of a document,
1711 // but once required, we must keep use_japanese true.
1712 runparams.use_japanese |= features.isRequired("japanese");
1715 // Restore the parenthood if needed
1716 if (!runparams.is_child)
1717 d->ignore_parent = false;
1722 os << "\\begin{document}\n";
1724 // output the parent macros
1725 MacroSet::iterator it = parentMacros.begin();
1726 MacroSet::iterator end = parentMacros.end();
1727 for (; it != end; ++it) {
1728 int num_lines = (*it)->write(os.os(), true);
1729 os.texrow().newlines(num_lines);
1732 } // output_preamble
1734 os.texrow().start(paragraphs().begin()->id(), 0);
1736 LYXERR(Debug::INFO, "preamble finished, now the body.");
1739 latexParagraphs(*this, text(), os, runparams);
1741 // Restore the parenthood if needed
1742 if (!runparams.is_child)
1743 d->ignore_parent = false;
1745 // add this just in case after all the paragraphs
1748 if (output_preamble) {
1749 os << "\\end{document}\n";
1750 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1752 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1754 runparams_in.encoding = runparams.encoding;
1756 // Just to be sure. (Asger)
1757 os.texrow().newline();
1759 //for (int i = 0; i<d->texrow.rows(); i++) {
1761 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1762 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1765 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1766 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1770 void Buffer::makeDocBookFile(FileName const & fname,
1771 OutputParams const & runparams,
1772 OutputWhat output) const
1774 LYXERR(Debug::LATEX, "makeDocBookFile...");
1777 if (!openFileWrite(ofs, fname))
1780 // make sure we are ready to export
1781 // this needs to be done before we validate
1783 updateMacroInstances(OutputUpdate);
1785 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1789 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1793 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1794 OutputParams const & runparams,
1795 OutputWhat output) const
1797 LaTeXFeatures features(*this, params(), runparams);
1802 DocumentClass const & tclass = params().documentClass();
1803 string const top_element = tclass.latexname();
1805 bool const output_preamble =
1806 output == FullSource || output == OnlyPreamble;
1807 bool const output_body =
1808 output == FullSource || output == OnlyBody;
1810 if (output_preamble) {
1811 if (runparams.flavor == OutputParams::XML)
1812 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1815 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1818 if (! tclass.class_header().empty())
1819 os << from_ascii(tclass.class_header());
1820 else if (runparams.flavor == OutputParams::XML)
1821 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1822 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1824 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1826 docstring preamble = from_utf8(params().preamble);
1827 if (runparams.flavor != OutputParams::XML ) {
1828 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1829 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1830 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1831 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1834 string const name = runparams.nice
1835 ? changeExtension(absFileName(), ".sgml") : fname;
1836 preamble += features.getIncludedFiles(name);
1837 preamble += features.getLyXSGMLEntities();
1839 if (!preamble.empty()) {
1840 os << "\n [ " << preamble << " ]";
1846 string top = top_element;
1848 if (runparams.flavor == OutputParams::XML)
1849 top += params().language->code();
1851 top += params().language->code().substr(0, 2);
1854 if (!params().options.empty()) {
1856 top += params().options;
1859 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1860 << " file was created by LyX " << lyx_version
1861 << "\n See http://www.lyx.org/ for more information -->\n";
1863 params().documentClass().counters().reset();
1865 sgml::openTag(os, top);
1867 docbookParagraphs(text(), *this, os, runparams);
1868 sgml::closeTag(os, top_element);
1873 void Buffer::makeLyXHTMLFile(FileName const & fname,
1874 OutputParams const & runparams) const
1876 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1879 if (!openFileWrite(ofs, fname))
1882 // make sure we are ready to export
1883 // this has to be done before we validate
1884 updateBuffer(UpdateMaster, OutputUpdate);
1885 updateMacroInstances(OutputUpdate);
1887 writeLyXHTMLSource(ofs, runparams, FullSource);
1891 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1895 void Buffer::writeLyXHTMLSource(odocstream & os,
1896 OutputParams const & runparams,
1897 OutputWhat output) const
1899 LaTeXFeatures features(*this, params(), runparams);
1901 d->bibinfo_.makeCitationLabels(*this);
1903 bool const output_preamble =
1904 output == FullSource || output == OnlyPreamble;
1905 bool const output_body =
1906 output == FullSource || output == OnlyBody || output == IncludedFile;
1908 if (output_preamble) {
1909 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1910 << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd\">\n"
1911 // FIXME Language should be set properly.
1912 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1914 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1915 // FIXME Presumably need to set this right
1916 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1918 docstring const & doctitle = features.htmlTitle();
1920 << (doctitle.empty() ?
1921 from_ascii("LyX Document") :
1922 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1925 docstring styles = features.getTClassHTMLPreamble();
1926 if (!styles.empty())
1927 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1929 styles = from_utf8(features.getPreambleSnippets());
1930 if (!styles.empty())
1931 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1933 // we will collect CSS information in a stream, and then output it
1934 // either here, as part of the header, or else in a separate file.
1935 odocstringstream css;
1936 styles = from_utf8(features.getCSSSnippets());
1937 if (!styles.empty())
1938 css << "/* LyX Provided Styles */\n" << styles << '\n';
1940 styles = features.getTClassHTMLStyles();
1941 if (!styles.empty())
1942 css << "/* Layout-provided Styles */\n" << styles << '\n';
1944 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1945 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1946 if (needfg || needbg) {
1947 css << "\nbody {\n";
1950 << from_ascii(X11hexname(params().fontcolor))
1953 css << " background-color: "
1954 << from_ascii(X11hexname(params().backgroundcolor))
1959 docstring const dstyles = css.str();
1960 if (!dstyles.empty()) {
1961 bool written = false;
1962 if (params().html_css_as_file) {
1963 // open a file for CSS info
1965 string const fcssname = addName(temppath(), "docstyle.css");
1966 FileName const fcssfile = FileName(fcssname);
1967 if (openFileWrite(ocss, fcssfile)) {
1971 // write link to header
1972 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1974 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1977 // we are here if the CSS is supposed to be written to the header
1978 // or if we failed to write it to an external file.
1980 os << "<style type='text/css'>\n"
1989 bool const output_body_tag = (output != IncludedFile);
1990 if (output_body_tag)
1993 if (output != IncludedFile)
1994 // if we're an included file, the counters are in the master.
1995 params().documentClass().counters().reset();
1996 xhtmlParagraphs(text(), *this, xs, runparams);
1997 if (output_body_tag)
2001 if (output_preamble)
2006 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2007 // Other flags: -wall -v0 -x
2008 int Buffer::runChktex()
2012 // get LaTeX-Filename
2013 FileName const path(temppath());
2014 string const name = addName(path.absFileName(), latexName());
2015 string const org_path = filePath();
2017 PathChanger p(path); // path to LaTeX file
2018 message(_("Running chktex..."));
2020 // Generate the LaTeX file if neccessary
2021 OutputParams runparams(¶ms().encoding());
2022 runparams.flavor = OutputParams::LATEX;
2023 runparams.nice = false;
2024 runparams.linelen = lyxrc.plaintext_linelen;
2025 makeLaTeXFile(FileName(name), org_path, runparams);
2028 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2029 int const res = chktex.run(terr); // run chktex
2032 Alert::error(_("chktex failure"),
2033 _("Could not run chktex successfully."));
2035 ErrorList & errlist = d->errorLists["ChkTeX"];
2037 bufferErrors(terr, errlist);
2042 if (runparams.silent)
2043 d->errorLists["ChkTeX"].clear();
2051 void Buffer::validate(LaTeXFeatures & features) const
2053 // Validate the buffer params, but not for included
2054 // files, since they also use the parent buffer's
2056 if (!features.runparams().is_child)
2057 params().validate(features);
2059 for_each(paragraphs().begin(), paragraphs().end(),
2060 bind(&Paragraph::validate, _1, ref(features)));
2062 if (lyxerr.debugging(Debug::LATEX)) {
2063 features.showStruct();
2068 void Buffer::getLabelList(vector<docstring> & list) const
2070 // If this is a child document, use the master's list instead.
2072 masterBuffer()->getLabelList(list);
2077 Toc & toc = d->toc_backend.toc("label");
2078 TocIterator toc_it = toc.begin();
2079 TocIterator end = toc.end();
2080 for (; toc_it != end; ++toc_it) {
2081 if (toc_it->depth() == 0)
2082 list.push_back(toc_it->str());
2087 void Buffer::updateBibfilesCache(UpdateScope scope) const
2089 // FIXME This is probably unnecssary, given where we call this.
2090 // If this is a child document, use the parent's cache instead.
2091 if (parent() && scope != UpdateChildOnly) {
2092 masterBuffer()->updateBibfilesCache();
2096 d->bibfiles_cache_.clear();
2097 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2098 if (it->lyxCode() == BIBTEX_CODE) {
2099 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2100 support::FileNameList const bibfiles = inset.getBibFiles();
2101 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2104 } else if (it->lyxCode() == INCLUDE_CODE) {
2105 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2106 Buffer const * const incbuf = inset.getChildBuffer();
2109 support::FileNameList const & bibfiles =
2110 incbuf->getBibfilesCache(UpdateChildOnly);
2111 if (!bibfiles.empty()) {
2112 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2118 d->bibfile_cache_valid_ = true;
2119 d->bibinfo_cache_valid_ = false;
2120 d->cite_labels_valid_ = false;
2124 void Buffer::invalidateBibinfoCache() const
2126 d->bibinfo_cache_valid_ = false;
2127 d->cite_labels_valid_ = false;
2128 // also invalidate the cache for the parent buffer
2129 Buffer const * const pbuf = d->parent();
2131 pbuf->invalidateBibinfoCache();
2135 void Buffer::invalidateBibfileCache() const
2137 d->bibfile_cache_valid_ = false;
2138 d->bibinfo_cache_valid_ = false;
2139 d->cite_labels_valid_ = false;
2140 // also invalidate the cache for the parent buffer
2141 Buffer const * const pbuf = d->parent();
2143 pbuf->invalidateBibfileCache();
2147 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2149 // FIXME This is probably unnecessary, given where we call this.
2150 // If this is a child document, use the master's cache instead.
2151 Buffer const * const pbuf = masterBuffer();
2152 if (pbuf != this && scope != UpdateChildOnly)
2153 return pbuf->getBibfilesCache();
2155 if (!d->bibfile_cache_valid_)
2156 this->updateBibfilesCache(scope);
2158 return d->bibfiles_cache_;
2162 BiblioInfo const & Buffer::masterBibInfo() const
2164 Buffer const * const tmp = masterBuffer();
2166 return tmp->masterBibInfo();
2171 void Buffer::checkIfBibInfoCacheIsValid() const
2173 // use the master's cache
2174 Buffer const * const tmp = masterBuffer();
2176 tmp->checkIfBibInfoCacheIsValid();
2180 // compare the cached timestamps with the actual ones.
2181 FileNameList const & bibfiles_cache = getBibfilesCache();
2182 FileNameList::const_iterator ei = bibfiles_cache.begin();
2183 FileNameList::const_iterator en = bibfiles_cache.end();
2184 for (; ei != en; ++ ei) {
2185 time_t lastw = ei->lastModified();
2186 time_t prevw = d->bibfile_status_[*ei];
2187 if (lastw != prevw) {
2188 d->bibinfo_cache_valid_ = false;
2189 d->cite_labels_valid_ = false;
2190 d->bibfile_status_[*ei] = lastw;
2196 void Buffer::reloadBibInfoCache() const
2198 // use the master's cache
2199 Buffer const * const tmp = masterBuffer();
2201 tmp->reloadBibInfoCache();
2205 checkIfBibInfoCacheIsValid();
2206 if (d->bibinfo_cache_valid_)
2209 d->bibinfo_.clear();
2211 d->bibinfo_cache_valid_ = true;
2215 void Buffer::collectBibKeys() const
2217 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2218 it->collectBibKeys(it);
2222 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2224 Buffer const * tmp = masterBuffer();
2225 BiblioInfo & masterbi = (tmp == this) ?
2226 d->bibinfo_ : tmp->d->bibinfo_;
2227 masterbi.mergeBiblioInfo(bi);
2231 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2233 Buffer const * tmp = masterBuffer();
2234 BiblioInfo & masterbi = (tmp == this) ?
2235 d->bibinfo_ : tmp->d->bibinfo_;
2240 void Buffer::makeCitationLabels() const
2242 Buffer const * const master = masterBuffer();
2243 return d->bibinfo_.makeCitationLabels(*master);
2247 bool Buffer::citeLabelsValid() const
2249 return masterBuffer()->d->cite_labels_valid_;
2253 void Buffer::removeBiblioTempFiles() const
2255 // We remove files that contain LaTeX commands specific to the
2256 // particular bibliographic style being used, in order to avoid
2257 // LaTeX errors when we switch style.
2258 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2259 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2260 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2261 aux_file.removeFile();
2262 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2263 bbl_file.removeFile();
2264 // Also for the parent buffer
2265 Buffer const * const pbuf = parent();
2267 pbuf->removeBiblioTempFiles();
2271 bool Buffer::isDepClean(string const & name) const
2273 DepClean::const_iterator const it = d->dep_clean.find(name);
2274 if (it == d->dep_clean.end())
2280 void Buffer::markDepClean(string const & name)
2282 d->dep_clean[name] = true;
2286 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2289 // FIXME? if there is an Buffer LFUN that can be dispatched even
2290 // if internal, put a switch '(cmd.action)' here.
2296 switch (cmd.action()) {
2298 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2299 flag.setOnOff(isReadonly());
2302 // FIXME: There is need for a command-line import.
2303 //case LFUN_BUFFER_IMPORT:
2305 case LFUN_BUFFER_AUTO_SAVE:
2308 case LFUN_BUFFER_EXPORT_CUSTOM:
2309 // FIXME: Nothing to check here?
2312 case LFUN_BUFFER_EXPORT: {
2313 docstring const arg = cmd.argument();
2314 if (arg == "custom") {
2318 string format = to_utf8(arg);
2319 size_t pos = format.find(' ');
2320 if (pos != string::npos)
2321 format = format.substr(0, pos);
2322 enable = params().isExportable(format);
2324 flag.message(bformat(
2325 _("Don't know how to export to format: %1$s"), arg));
2329 case LFUN_BUFFER_CHKTEX:
2330 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2333 case LFUN_BUILD_PROGRAM:
2334 enable = params().isExportable("program");
2337 case LFUN_BRANCH_ACTIVATE:
2338 case LFUN_BRANCH_DEACTIVATE:
2339 case LFUN_BRANCH_MASTER_ACTIVATE:
2340 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2341 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2342 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2343 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2344 : params().branchlist();
2345 docstring const branchName = cmd.argument();
2346 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2350 case LFUN_BRANCH_ADD:
2351 case LFUN_BRANCHES_RENAME:
2352 case LFUN_BUFFER_PRINT:
2353 // if no Buffer is present, then of course we won't be called!
2356 case LFUN_BUFFER_LANGUAGE:
2357 enable = !isReadonly();
2363 flag.setEnabled(enable);
2368 void Buffer::dispatch(string const & command, DispatchResult & result)
2370 return dispatch(lyxaction.lookupFunc(command), result);
2374 // NOTE We can end up here even if we have no GUI, because we are called
2375 // by LyX::exec to handled command-line requests. So we may need to check
2376 // whether we have a GUI or not. The boolean use_gui holds this information.
2377 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2380 // FIXME? if there is an Buffer LFUN that can be dispatched even
2381 // if internal, put a switch '(cmd.action())' here.
2382 dr.dispatched(false);
2385 string const argument = to_utf8(func.argument());
2386 // We'll set this back to false if need be.
2387 bool dispatched = true;
2388 undo().beginUndoGroup();
2390 switch (func.action()) {
2391 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2392 if (lyxvc().inUse()) {
2393 string log = lyxvc().toggleReadOnly();
2398 setReadonly(!isReadonly());
2401 case LFUN_BUFFER_EXPORT: {
2402 ExportStatus const status = doExport(argument, false);
2403 dr.setError(status != ExportSuccess);
2404 if (status != ExportSuccess)
2405 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2410 case LFUN_BUILD_PROGRAM: {
2411 ExportStatus const status = doExport("program", true);
2412 dr.setError(status != ExportSuccess);
2413 if (status != ExportSuccess)
2414 dr.setMessage(_("Error generating literate programming code."));
2418 case LFUN_BUFFER_CHKTEX:
2422 case LFUN_BUFFER_EXPORT_CUSTOM: {
2424 string command = split(argument, format_name, ' ');
2425 Format const * format = formats.getFormat(format_name);
2427 lyxerr << "Format \"" << format_name
2428 << "\" not recognized!"
2433 // The name of the file created by the conversion process
2436 // Output to filename
2437 if (format->name() == "lyx") {
2438 string const latexname = latexName(false);
2439 filename = changeExtension(latexname,
2440 format->extension());
2441 filename = addName(temppath(), filename);
2443 if (!writeFile(FileName(filename)))
2447 doExport(format_name, true, filename);
2450 // Substitute $$FName for filename
2451 if (!contains(command, "$$FName"))
2452 command = "( " + command + " ) < $$FName";
2453 command = subst(command, "$$FName", filename);
2455 // Execute the command in the background
2457 call.startscript(Systemcall::DontWait, command, filePath());
2461 // FIXME: There is need for a command-line import.
2463 case LFUN_BUFFER_IMPORT:
2468 case LFUN_BUFFER_AUTO_SAVE:
2470 resetAutosaveTimers();
2473 case LFUN_BRANCH_ACTIVATE:
2474 case LFUN_BRANCH_DEACTIVATE:
2475 case LFUN_BRANCH_MASTER_ACTIVATE:
2476 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2477 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2478 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2479 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2482 docstring const branch_name = func.argument();
2483 // the case without a branch name is handled elsewhere
2484 if (branch_name.empty()) {
2488 Branch * branch = buf->params().branchlist().find(branch_name);
2490 LYXERR0("Branch " << branch_name << " does not exist.");
2492 docstring const msg =
2493 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2497 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2498 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2499 if (branch->isSelected() != activate) {
2500 buf->undo().recordUndoFullDocument(CursorData());
2501 branch->setSelected(activate);
2503 dr.screenUpdate(Update::Force);
2504 dr.forceBufferUpdate();
2509 case LFUN_BRANCH_ADD: {
2510 docstring branch_name = func.argument();
2511 if (branch_name.empty()) {
2515 BranchList & branch_list = params().branchlist();
2516 vector<docstring> const branches =
2517 getVectorFromString(branch_name, branch_list.separator());
2519 for (vector<docstring>::const_iterator it = branches.begin();
2520 it != branches.end(); ++it) {
2522 Branch * branch = branch_list.find(branch_name);
2524 LYXERR0("Branch " << branch_name << " already exists.");
2528 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2530 undo().recordUndoFullDocument(CursorData());
2531 branch_list.add(branch_name);
2532 branch = branch_list.find(branch_name);
2533 string const x11hexname = X11hexname(branch->color());
2534 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2535 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2537 dr.screenUpdate(Update::Force);
2545 case LFUN_BRANCHES_RENAME: {
2546 if (func.argument().empty())
2549 docstring const oldname = from_utf8(func.getArg(0));
2550 docstring const newname = from_utf8(func.getArg(1));
2551 InsetIterator it = inset_iterator_begin(inset());
2552 InsetIterator const end = inset_iterator_end(inset());
2553 bool success = false;
2554 for (; it != end; ++it) {
2555 if (it->lyxCode() == BRANCH_CODE) {
2556 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2557 if (ins.branch() == oldname) {
2558 undo().recordUndo(CursorData(it));
2559 ins.rename(newname);
2564 if (it->lyxCode() == INCLUDE_CODE) {
2565 // get buffer of external file
2566 InsetInclude const & ins =
2567 static_cast<InsetInclude const &>(*it);
2568 Buffer * child = ins.getChildBuffer();
2571 child->dispatch(func, dr);
2576 dr.screenUpdate(Update::Force);
2577 dr.forceBufferUpdate();
2582 case LFUN_BUFFER_PRINT: {
2583 // we'll assume there's a problem until we succeed
2585 string target = func.getArg(0);
2586 string target_name = func.getArg(1);
2587 string command = func.getArg(2);
2590 || target_name.empty()
2591 || command.empty()) {
2592 LYXERR0("Unable to parse " << func.argument());
2593 docstring const msg =
2594 bformat(_("Unable to parse \"%1$s\""), func.argument());
2598 if (target != "printer" && target != "file") {
2599 LYXERR0("Unrecognized target \"" << target << '"');
2600 docstring const msg =
2601 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2606 if (doExport("dvi", true) != ExportSuccess) {
2607 showPrintError(absFileName());
2608 dr.setMessage(_("Error exporting to DVI."));
2612 // Push directory path.
2613 string const path = temppath();
2614 // Prevent the compiler from optimizing away p
2618 // there are three cases here:
2619 // 1. we print to a file
2620 // 2. we print directly to a printer
2621 // 3. we print using a spool command (print to file first)
2624 string const dviname = changeExtension(latexName(true), "dvi");
2626 if (target == "printer") {
2627 if (!lyxrc.print_spool_command.empty()) {
2628 // case 3: print using a spool
2629 string const psname = changeExtension(dviname,".ps");
2630 command += ' ' + lyxrc.print_to_file
2633 + quoteName(dviname);
2635 string command2 = lyxrc.print_spool_command + ' ';
2636 if (target_name != "default") {
2637 command2 += lyxrc.print_spool_printerprefix
2641 command2 += quoteName(psname);
2643 // If successful, then spool command
2644 res = one.startscript(Systemcall::Wait, command,
2648 // If there's no GUI, we have to wait on this command. Otherwise,
2649 // LyX deletes the temporary directory, and with it the spooled
2650 // file, before it can be printed!!
2651 Systemcall::Starttype stype = use_gui ?
2652 Systemcall::DontWait : Systemcall::Wait;
2653 res = one.startscript(stype, command2,
2657 // case 2: print directly to a printer
2658 if (target_name != "default")
2659 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2661 Systemcall::Starttype stype = use_gui ?
2662 Systemcall::DontWait : Systemcall::Wait;
2663 res = one.startscript(stype, command +
2664 quoteName(dviname), filePath());
2668 // case 1: print to a file
2669 FileName const filename(makeAbsPath(target_name, filePath()));
2670 FileName const dvifile(makeAbsPath(dviname, path));
2671 if (filename.exists()) {
2672 docstring text = bformat(
2673 _("The file %1$s already exists.\n\n"
2674 "Do you want to overwrite that file?"),
2675 makeDisplayPath(filename.absFileName()));
2676 if (Alert::prompt(_("Overwrite file?"),
2677 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2680 command += ' ' + lyxrc.print_to_file
2681 + quoteName(filename.toFilesystemEncoding())
2683 + quoteName(dvifile.toFilesystemEncoding());
2685 Systemcall::Starttype stype = use_gui ?
2686 Systemcall::DontWait : Systemcall::Wait;
2687 res = one.startscript(stype, command, filePath());
2693 dr.setMessage(_("Error running external commands."));
2694 showPrintError(absFileName());
2703 dr.dispatched(dispatched);
2704 undo().endUndoGroup();
2708 void Buffer::changeLanguage(Language const * from, Language const * to)
2710 LASSERT(from, return);
2711 LASSERT(to, return);
2713 for_each(par_iterator_begin(),
2715 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2719 bool Buffer::isMultiLingual() const
2721 ParConstIterator end = par_iterator_end();
2722 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2723 if (it->isMultiLingual(params()))
2730 std::set<Language const *> Buffer::getLanguages() const
2732 std::set<Language const *> languages;
2733 getLanguages(languages);
2738 void Buffer::getLanguages(std::set<Language const *> & languages) const
2740 ParConstIterator end = par_iterator_end();
2741 // add the buffer language, even if it's not actively used
2742 languages.insert(language());
2743 // iterate over the paragraphs
2744 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2745 it->getLanguages(languages);
2747 ListOfBuffers clist = getDescendents();
2748 ListOfBuffers::const_iterator cit = clist.begin();
2749 ListOfBuffers::const_iterator const cen = clist.end();
2750 for (; cit != cen; ++cit)
2751 (*cit)->getLanguages(languages);
2755 DocIterator Buffer::getParFromID(int const id) const
2757 Buffer * buf = const_cast<Buffer *>(this);
2759 // John says this is called with id == -1 from undo
2760 lyxerr << "getParFromID(), id: " << id << endl;
2761 return doc_iterator_end(buf);
2764 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2765 if (it.paragraph().id() == id)
2768 return doc_iterator_end(buf);
2772 bool Buffer::hasParWithID(int const id) const
2774 return !getParFromID(id).atEnd();
2778 ParIterator Buffer::par_iterator_begin()
2780 return ParIterator(doc_iterator_begin(this));
2784 ParIterator Buffer::par_iterator_end()
2786 return ParIterator(doc_iterator_end(this));
2790 ParConstIterator Buffer::par_iterator_begin() const
2792 return ParConstIterator(doc_iterator_begin(this));
2796 ParConstIterator Buffer::par_iterator_end() const
2798 return ParConstIterator(doc_iterator_end(this));
2802 Language const * Buffer::language() const
2804 return params().language;
2808 docstring const Buffer::B_(string const & l10n) const
2810 return params().B_(l10n);
2814 bool Buffer::isClean() const
2816 return d->lyx_clean;
2820 bool Buffer::isExternallyModified(CheckMethod method) const
2822 LASSERT(d->filename.exists(), return false);
2823 // if method == timestamp, check timestamp before checksum
2824 return (method == checksum_method
2825 || d->timestamp_ != d->filename.lastModified())
2826 && d->checksum_ != d->filename.checksum();
2830 void Buffer::saveCheckSum() const
2832 FileName const & file = d->filename;
2835 if (file.exists()) {
2836 d->timestamp_ = file.lastModified();
2837 d->checksum_ = file.checksum();
2839 // in the case of save to a new file.
2846 void Buffer::markClean() const
2848 if (!d->lyx_clean) {
2849 d->lyx_clean = true;
2852 // if the .lyx file has been saved, we don't need an
2854 d->bak_clean = true;
2855 d->undo_.markDirty();
2859 void Buffer::setUnnamed(bool flag)
2865 bool Buffer::isUnnamed() const
2872 /// Don't check unnamed, here: isInternal() is used in
2873 /// newBuffer(), where the unnamed flag has not been set by anyone
2874 /// yet. Also, for an internal buffer, there should be no need for
2875 /// retrieving fileName() nor for checking if it is unnamed or not.
2876 bool Buffer::isInternal() const
2878 return d->internal_buffer;
2882 void Buffer::setInternal(bool flag)
2884 d->internal_buffer = flag;
2888 void Buffer::markDirty()
2891 d->lyx_clean = false;
2894 d->bak_clean = false;
2896 DepClean::iterator it = d->dep_clean.begin();
2897 DepClean::const_iterator const end = d->dep_clean.end();
2899 for (; it != end; ++it)
2904 FileName Buffer::fileName() const
2910 string Buffer::absFileName() const
2912 return d->filename.absFileName();
2916 string Buffer::filePath() const
2918 string const abs = d->filename.onlyPath().absFileName();
2921 int last = abs.length() - 1;
2923 return abs[last] == '/' ? abs : abs + '/';
2927 bool Buffer::isReadonly() const
2929 return d->read_only;
2933 void Buffer::setParent(Buffer const * buffer)
2935 // Avoids recursive include.
2936 d->setParent(buffer == this ? 0 : buffer);
2941 Buffer const * Buffer::parent() const
2947 ListOfBuffers Buffer::allRelatives() const
2949 ListOfBuffers lb = masterBuffer()->getDescendents();
2950 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2955 Buffer const * Buffer::masterBuffer() const
2957 // FIXME Should be make sure we are not in some kind
2958 // of recursive include? A -> B -> A will crash this.
2959 Buffer const * const pbuf = d->parent();
2963 return pbuf->masterBuffer();
2967 bool Buffer::isChild(Buffer * child) const
2969 return d->children_positions.find(child) != d->children_positions.end();
2973 DocIterator Buffer::firstChildPosition(Buffer const * child)
2975 Impl::BufferPositionMap::iterator it;
2976 it = d->children_positions.find(child);
2977 if (it == d->children_positions.end())
2978 return DocIterator(this);
2983 bool Buffer::hasChildren() const
2985 return !d->children_positions.empty();
2989 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2991 // loop over children
2992 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2993 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2994 for (; it != end; ++it) {
2995 Buffer * child = const_cast<Buffer *>(it->first);
2997 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2998 if (bit != clist.end())
3000 clist.push_back(child);
3002 // there might be grandchildren
3003 child->collectChildren(clist, true);
3008 ListOfBuffers Buffer::getChildren() const
3011 collectChildren(v, false);
3012 // Make sure we have not included ourselves.
3013 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3014 if (bit != v.end()) {
3015 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3022 ListOfBuffers Buffer::getDescendents() const
3025 collectChildren(v, true);
3026 // Make sure we have not included ourselves.
3027 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3028 if (bit != v.end()) {
3029 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3036 template<typename M>
3037 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3042 typename M::const_iterator it = m.lower_bound(x);
3043 if (it == m.begin())
3051 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3052 DocIterator const & pos) const
3054 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3056 // if paragraphs have no macro context set, pos will be empty
3060 // we haven't found anything yet
3061 DocIterator bestPos = owner_->par_iterator_begin();
3062 MacroData const * bestData = 0;
3064 // find macro definitions for name
3065 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3066 if (nameIt != macros.end()) {
3067 // find last definition in front of pos or at pos itself
3068 PositionScopeMacroMap::const_iterator it
3069 = greatest_below(nameIt->second, pos);
3070 if (it != nameIt->second.end()) {
3072 // scope ends behind pos?
3073 if (pos < it->second.first) {
3074 // Looks good, remember this. If there
3075 // is no external macro behind this,
3076 // we found the right one already.
3077 bestPos = it->first;
3078 bestData = &it->second.second;
3082 // try previous macro if there is one
3083 if (it == nameIt->second.begin())
3090 // find macros in included files
3091 PositionScopeBufferMap::const_iterator it
3092 = greatest_below(position_to_children, pos);
3093 if (it == position_to_children.end())
3094 // no children before
3098 // do we know something better (i.e. later) already?
3099 if (it->first < bestPos )
3102 // scope ends behind pos?
3103 if (pos < it->second.first
3104 && (cloned_buffer_ ||
3105 theBufferList().isLoaded(it->second.second))) {
3106 // look for macro in external file
3108 MacroData const * data
3109 = it->second.second->getMacro(name, false);
3112 bestPos = it->first;
3118 // try previous file if there is one
3119 if (it == position_to_children.begin())
3124 // return the best macro we have found
3129 MacroData const * Buffer::getMacro(docstring const & name,
3130 DocIterator const & pos, bool global) const
3135 // query buffer macros
3136 MacroData const * data = d->getBufferMacro(name, pos);
3140 // If there is a master buffer, query that
3141 Buffer const * const pbuf = d->parent();
3143 d->macro_lock = true;
3144 MacroData const * macro = pbuf->getMacro(
3145 name, *this, false);
3146 d->macro_lock = false;
3152 data = MacroTable::globalMacros().get(name);
3161 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3163 // set scope end behind the last paragraph
3164 DocIterator scope = par_iterator_begin();
3165 scope.pit() = scope.lastpit() + 1;
3167 return getMacro(name, scope, global);
3171 MacroData const * Buffer::getMacro(docstring const & name,
3172 Buffer const & child, bool global) const
3174 // look where the child buffer is included first
3175 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3176 if (it == d->children_positions.end())
3179 // check for macros at the inclusion position
3180 return getMacro(name, it->second, global);
3184 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3186 pit_type const lastpit = it.lastpit();
3188 // look for macros in each paragraph
3189 while (it.pit() <= lastpit) {
3190 Paragraph & par = it.paragraph();
3192 // iterate over the insets of the current paragraph
3193 InsetList const & insets = par.insetList();
3194 InsetList::const_iterator iit = insets.begin();
3195 InsetList::const_iterator end = insets.end();
3196 for (; iit != end; ++iit) {
3197 it.pos() = iit->pos;
3199 // is it a nested text inset?
3200 if (iit->inset->asInsetText()) {
3201 // Inset needs its own scope?
3202 InsetText const * itext = iit->inset->asInsetText();
3203 bool newScope = itext->isMacroScope();
3205 // scope which ends just behind the inset
3206 DocIterator insetScope = it;
3209 // collect macros in inset
3210 it.push_back(CursorSlice(*iit->inset));
3211 updateMacros(it, newScope ? insetScope : scope);
3216 if (iit->inset->asInsetTabular()) {
3217 CursorSlice slice(*iit->inset);
3218 size_t const numcells = slice.nargs();
3219 for (; slice.idx() < numcells; slice.forwardIdx()) {
3220 it.push_back(slice);
3221 updateMacros(it, scope);
3227 // is it an external file?
3228 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3229 // get buffer of external file
3230 InsetInclude const & inset =
3231 static_cast<InsetInclude const &>(*iit->inset);
3233 Buffer * child = inset.getChildBuffer();
3238 // register its position, but only when it is
3239 // included first in the buffer
3240 if (children_positions.find(child) ==
3241 children_positions.end())
3242 children_positions[child] = it;
3244 // register child with its scope
3245 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3249 InsetMath * im = iit->inset->asInsetMath();
3250 if (doing_export && im) {
3251 InsetMathHull * hull = im->asHullInset();
3253 hull->recordLocation(it);
3256 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3260 MathMacroTemplate & macroTemplate =
3261 *iit->inset->asInsetMath()->asMacroTemplate();
3262 MacroContext mc(owner_, it);
3263 macroTemplate.updateToContext(mc);
3266 bool valid = macroTemplate.validMacro();
3267 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3268 // then the BufferView's cursor will be invalid in
3269 // some cases which leads to crashes.
3274 // FIXME (Abdel), I don't understandt why we pass 'it' here
3275 // instead of 'macroTemplate' defined above... is this correct?
3276 macros[macroTemplate.name()][it] =
3277 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3287 void Buffer::updateMacros() const
3292 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3294 // start with empty table
3296 d->children_positions.clear();
3297 d->position_to_children.clear();
3299 // Iterate over buffer, starting with first paragraph
3300 // The scope must be bigger than any lookup DocIterator
3301 // later. For the global lookup, lastpit+1 is used, hence
3302 // we use lastpit+2 here.
3303 DocIterator it = par_iterator_begin();
3304 DocIterator outerScope = it;
3305 outerScope.pit() = outerScope.lastpit() + 2;
3306 d->updateMacros(it, outerScope);
3310 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3312 InsetIterator it = inset_iterator_begin(inset());
3313 InsetIterator const end = inset_iterator_end(inset());
3314 for (; it != end; ++it) {
3315 if (it->lyxCode() == BRANCH_CODE) {
3316 InsetBranch & br = static_cast<InsetBranch &>(*it);
3317 docstring const name = br.branch();
3318 if (!from_master && !params().branchlist().find(name))
3319 result.push_back(name);
3320 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3321 result.push_back(name);
3324 if (it->lyxCode() == INCLUDE_CODE) {
3325 // get buffer of external file
3326 InsetInclude const & ins =
3327 static_cast<InsetInclude const &>(*it);
3328 Buffer * child = ins.getChildBuffer();
3331 child->getUsedBranches(result, true);
3334 // remove duplicates
3339 void Buffer::updateMacroInstances(UpdateType utype) const
3341 LYXERR(Debug::MACROS, "updateMacroInstances for "
3342 << d->filename.onlyFileName());
3343 DocIterator it = doc_iterator_begin(this);
3345 DocIterator const end = doc_iterator_end(this);
3346 for (; it != end; it.forwardInset()) {
3347 // look for MathData cells in InsetMathNest insets
3348 InsetMath * minset = it.nextInset()->asInsetMath();
3352 // update macro in all cells of the InsetMathNest
3353 DocIterator::idx_type n = minset->nargs();
3354 MacroContext mc = MacroContext(this, it);
3355 for (DocIterator::idx_type i = 0; i < n; ++i) {
3356 MathData & data = minset->cell(i);
3357 data.updateMacros(0, mc, utype);
3363 void Buffer::listMacroNames(MacroNameSet & macros) const
3368 d->macro_lock = true;
3370 // loop over macro names
3371 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3372 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3373 for (; nameIt != nameEnd; ++nameIt)
3374 macros.insert(nameIt->first);
3376 // loop over children
3377 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3378 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3379 for (; it != end; ++it)
3380 it->first->listMacroNames(macros);
3383 Buffer const * const pbuf = d->parent();
3385 pbuf->listMacroNames(macros);
3387 d->macro_lock = false;
3391 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3393 Buffer const * const pbuf = d->parent();
3398 pbuf->listMacroNames(names);
3401 MacroNameSet::iterator it = names.begin();
3402 MacroNameSet::iterator end = names.end();
3403 for (; it != end; ++it) {
3405 MacroData const * data =
3406 pbuf->getMacro(*it, *this, false);
3408 macros.insert(data);
3410 // we cannot access the original MathMacroTemplate anymore
3411 // here to calls validate method. So we do its work here manually.
3412 // FIXME: somehow make the template accessible here.
3413 if (data->optionals() > 0)
3414 features.require("xargs");
3420 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3423 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3425 RefCache::iterator it = d->ref_cache_.find(label);
3426 if (it != d->ref_cache_.end())
3427 return it->second.second;
3429 static InsetLabel const * dummy_il = 0;
3430 static References const dummy_refs;
3431 it = d->ref_cache_.insert(
3432 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3433 return it->second.second;
3437 Buffer::References const & Buffer::references(docstring const & label) const
3439 return const_cast<Buffer *>(this)->getReferenceCache(label);
3443 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3445 References & refs = getReferenceCache(label);
3446 refs.push_back(make_pair(inset, it));
3450 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3452 masterBuffer()->d->ref_cache_[label].first = il;
3456 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3458 return masterBuffer()->d->ref_cache_[label].first;
3462 void Buffer::clearReferenceCache() const
3465 d->ref_cache_.clear();
3469 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3471 //FIXME: This does not work for child documents yet.
3472 reloadBibInfoCache();
3474 // Check if the label 'from' appears more than once
3475 BiblioInfo const & keys = masterBibInfo();
3476 BiblioInfo::const_iterator bit = keys.begin();
3477 BiblioInfo::const_iterator bend = keys.end();
3478 vector<docstring> labels;
3480 for (; bit != bend; ++bit)
3482 labels.push_back(bit->first);
3484 if (count(labels.begin(), labels.end(), from) > 1)
3487 string const paramName = "key";
3488 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3489 if (it->lyxCode() != CITE_CODE)
3491 InsetCommand * inset = it->asInsetCommand();
3492 docstring const oldValue = inset->getParam(paramName);
3493 if (oldValue == from)
3494 inset->setParam(paramName, to);
3499 void Buffer::getSourceCode(odocstream & os, string const format,
3500 pit_type par_begin, pit_type par_end,
3501 OutputWhat output, bool master) const
3503 OutputParams runparams(¶ms().encoding());
3504 runparams.nice = true;
3505 runparams.flavor = params().getOutputFlavor(format);
3506 runparams.linelen = lyxrc.plaintext_linelen;
3507 // No side effect of file copying and image conversion
3508 runparams.dryrun = true;
3510 if (output == CurrentParagraph) {
3511 runparams.par_begin = par_begin;
3512 runparams.par_end = par_end;
3513 if (par_begin + 1 == par_end) {
3515 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3519 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3520 convert<docstring>(par_begin),
3521 convert<docstring>(par_end - 1))
3524 // output paragraphs
3525 if (runparams.flavor == OutputParams::LYX) {
3526 Paragraph const & par = text().paragraphs()[par_begin];
3528 depth_type dt = par.getDepth();
3529 par.write(ods, params(), dt);
3530 os << from_utf8(ods.str());
3531 } else if (runparams.flavor == OutputParams::HTML) {
3533 setMathFlavor(runparams);
3534 xhtmlParagraphs(text(), *this, xs, runparams);
3535 } else if (runparams.flavor == OutputParams::TEXT) {
3537 // FIXME Handles only one paragraph, unlike the others.
3538 // Probably should have some routine with a signature like them.
3539 writePlaintextParagraph(*this,
3540 text().paragraphs()[par_begin], os, runparams, dummy);
3541 } else if (params().isDocBook()) {
3542 docbookParagraphs(text(), *this, os, runparams);
3544 // If we are previewing a paragraph, even if this is the
3545 // child of some other buffer, let's cut the link here,
3546 // so that no concurring settings from the master
3547 // (e.g. branch state) interfere (see #8101).
3549 d->ignore_parent = true;
3550 // We need to validate the Buffer params' features here
3551 // in order to know if we should output polyglossia
3552 // macros (instead of babel macros)
3553 LaTeXFeatures features(*this, params(), runparams);
3554 params().validate(features);
3555 runparams.use_polyglossia = features.usePolyglossia();
3560 // latex or literate
3561 otexstream ots(os, texrow);
3564 latexParagraphs(*this, text(), ots, runparams);
3566 // Restore the parenthood
3568 d->ignore_parent = false;
3572 if (output == FullSource)
3573 os << _("Preview source code");
3574 else if (output == OnlyPreamble)
3575 os << _("Preview preamble");
3576 else if (output == OnlyBody)
3577 os << _("Preview body");
3579 if (runparams.flavor == OutputParams::LYX) {
3581 if (output == FullSource)
3583 else if (output == OnlyPreamble)
3584 params().writeFile(ods);
3585 else if (output == OnlyBody)
3587 os << from_utf8(ods.str());
3588 } else if (runparams.flavor == OutputParams::HTML) {
3589 writeLyXHTMLSource(os, runparams, output);
3590 } else if (runparams.flavor == OutputParams::TEXT) {
3591 if (output == OnlyPreamble) {
3592 os << "% "<< _("Plain text does not have a preamble.");
3594 writePlaintextFile(*this, os, runparams);
3595 } else if (params().isDocBook()) {
3596 writeDocBookSource(os, absFileName(), runparams, output);
3598 // latex or literate
3600 d->texrow.newline();
3601 d->texrow.newline();
3602 otexstream ots(os, d->texrow);
3604 runparams.is_child = true;
3605 writeLaTeXSource(ots, string(), runparams, output);
3611 ErrorList & Buffer::errorList(string const & type) const
3613 return d->errorLists[type];
3617 void Buffer::updateTocItem(std::string const & type,
3618 DocIterator const & dit) const
3621 d->gui_->updateTocItem(type, dit);
3625 void Buffer::structureChanged() const
3628 d->gui_->structureChanged();
3632 void Buffer::errors(string const & err, bool from_master) const
3635 d->gui_->errors(err, from_master);
3639 void Buffer::message(docstring const & msg) const
3642 d->gui_->message(msg);
3646 void Buffer::setBusy(bool on) const
3649 d->gui_->setBusy(on);
3653 void Buffer::updateTitles() const
3656 d->wa_->updateTitles();
3660 void Buffer::resetAutosaveTimers() const
3663 d->gui_->resetAutosaveTimers();
3667 bool Buffer::hasGuiDelegate() const
3673 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3682 class AutoSaveBuffer : public ForkedProcess {
3685 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3686 : buffer_(buffer), fname_(fname) {}
3688 virtual shared_ptr<ForkedProcess> clone() const
3690 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3695 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3696 from_utf8(fname_.absFileName())));
3697 return run(DontWait);
3701 virtual int generateChild();
3703 Buffer const & buffer_;
3708 int AutoSaveBuffer::generateChild()
3710 #if defined(__APPLE__)
3711 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3712 * We should use something else like threads.
3714 * Since I do not know how to determine at run time what is the OS X
3715 * version, I just disable forking altogether for now (JMarc)
3717 pid_t const pid = -1;
3719 // tmp_ret will be located (usually) in /tmp
3720 // will that be a problem?
3721 // Note that this calls ForkedCalls::fork(), so it's
3722 // ok cross-platform.
3723 pid_t const pid = fork();
3724 // If you want to debug the autosave
3725 // you should set pid to -1, and comment out the fork.
3726 if (pid != 0 && pid != -1)
3730 // pid = -1 signifies that lyx was unable
3731 // to fork. But we will do the save
3733 bool failed = false;
3734 TempFile tempfile("lyxautoXXXXXX.lyx");
3735 tempfile.setAutoRemove(false);
3736 FileName const tmp_ret = tempfile.name();
3737 if (!tmp_ret.empty()) {
3738 buffer_.writeFile(tmp_ret);
3739 // assume successful write of tmp_ret
3740 if (!tmp_ret.moveTo(fname_))
3746 // failed to write/rename tmp_ret so try writing direct
3747 if (!buffer_.writeFile(fname_)) {
3748 // It is dangerous to do this in the child,
3749 // but safe in the parent, so...
3750 if (pid == -1) // emit message signal.
3751 buffer_.message(_("Autosave failed!"));
3755 if (pid == 0) // we are the child so...
3764 FileName Buffer::getEmergencyFileName() const
3766 return FileName(d->filename.absFileName() + ".emergency");
3770 FileName Buffer::getAutosaveFileName() const
3772 // if the document is unnamed try to save in the backup dir, else
3773 // in the default document path, and as a last try in the filePath,
3774 // which will most often be the temporary directory
3777 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3778 : lyxrc.backupdir_path;
3779 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3782 string const fname = "#" + d->filename.onlyFileName() + "#";
3784 return makeAbsPath(fname, fpath);
3788 void Buffer::removeAutosaveFile() const
3790 FileName const f = getAutosaveFileName();
3796 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3798 FileName const newauto = getAutosaveFileName();
3800 if (newauto != oldauto && oldauto.exists())
3801 if (!oldauto.moveTo(newauto))
3802 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3806 bool Buffer::autoSave() const
3808 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3809 if (buf->d->bak_clean || isReadonly())
3812 message(_("Autosaving current document..."));
3813 buf->d->bak_clean = true;
3815 FileName const fname = getAutosaveFileName();
3816 LASSERT(d->cloned_buffer_, return false);
3818 // If this buffer is cloned, we assume that
3819 // we are running in a separate thread already.
3820 TempFile tempfile("lyxautoXXXXXX.lyx");
3821 tempfile.setAutoRemove(false);
3822 FileName const tmp_ret = tempfile.name();
3823 if (!tmp_ret.empty()) {
3825 // assume successful write of tmp_ret
3826 if (tmp_ret.moveTo(fname))
3829 // failed to write/rename tmp_ret so try writing direct
3830 return writeFile(fname);
3834 void Buffer::setExportStatus(bool e) const
3836 d->doing_export = e;
3837 ListOfBuffers clist = getDescendents();
3838 ListOfBuffers::const_iterator cit = clist.begin();
3839 ListOfBuffers::const_iterator const cen = clist.end();
3840 for (; cit != cen; ++cit)
3841 (*cit)->d->doing_export = e;
3845 bool Buffer::isExporting() const
3847 return d->doing_export;
3851 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3855 return doExport(target, put_in_tempdir, result_file);
3858 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3859 string & result_file) const
3861 bool const update_unincluded =
3862 params().maintain_unincluded_children
3863 && !params().getIncludedChildren().empty();
3865 // (1) export with all included children (omit \includeonly)
3866 if (update_unincluded) {
3867 ExportStatus const status =
3868 doExport(target, put_in_tempdir, true, result_file);
3869 if (status != ExportSuccess)
3872 // (2) export with included children only
3873 return doExport(target, put_in_tempdir, false, result_file);
3877 void Buffer::setMathFlavor(OutputParams & op) const
3879 switch (params().html_math_output) {
3880 case BufferParams::MathML:
3881 op.math_flavor = OutputParams::MathAsMathML;
3883 case BufferParams::HTML:
3884 op.math_flavor = OutputParams::MathAsHTML;
3886 case BufferParams::Images:
3887 op.math_flavor = OutputParams::MathAsImages;
3889 case BufferParams::LaTeX:
3890 op.math_flavor = OutputParams::MathAsLaTeX;
3896 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3897 bool includeall, string & result_file) const
3899 LYXERR(Debug::FILES, "target=" << target);
3900 OutputParams runparams(¶ms().encoding());
3901 string format = target;
3902 string dest_filename;
3903 size_t pos = target.find(' ');
3904 if (pos != string::npos) {
3905 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3906 format = target.substr(0, pos);
3907 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3908 FileName(dest_filename).onlyPath().createPath();
3909 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3911 MarkAsExporting exporting(this);
3912 string backend_format;
3913 runparams.flavor = OutputParams::LATEX;
3914 runparams.linelen = lyxrc.plaintext_linelen;
3915 runparams.includeall = includeall;
3916 vector<string> backs = params().backends();
3917 Converters converters = theConverters();
3918 bool need_nice_file = false;
3919 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3920 // Get shortest path to format
3921 converters.buildGraph();
3922 Graph::EdgePath path;
3923 for (vector<string>::const_iterator it = backs.begin();
3924 it != backs.end(); ++it) {
3925 Graph::EdgePath p = converters.getPath(*it, format);
3926 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3927 backend_format = *it;
3932 if (!put_in_tempdir) {
3933 // Only show this alert if this is an export to a non-temporary
3934 // file (not for previewing).
3935 Alert::error(_("Couldn't export file"), bformat(
3936 _("No information for exporting the format %1$s."),
3937 formats.prettyName(format)));
3939 return ExportNoPathToFormat;
3941 runparams.flavor = converters.getFlavor(path, this);
3942 Graph::EdgePath::const_iterator it = path.begin();
3943 Graph::EdgePath::const_iterator en = path.end();
3944 for (; it != en; ++it)
3945 if (theConverters().get(*it).nice) {
3946 need_nice_file = true;
3951 backend_format = format;
3952 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3953 // FIXME: Don't hardcode format names here, but use a flag
3954 if (backend_format == "pdflatex")
3955 runparams.flavor = OutputParams::PDFLATEX;
3956 else if (backend_format == "luatex")
3957 runparams.flavor = OutputParams::LUATEX;
3958 else if (backend_format == "dviluatex")
3959 runparams.flavor = OutputParams::DVILUATEX;
3960 else if (backend_format == "xetex")
3961 runparams.flavor = OutputParams::XETEX;
3964 string filename = latexName(false);
3965 filename = addName(temppath(), filename);
3966 filename = changeExtension(filename,
3967 formats.extension(backend_format));
3968 LYXERR(Debug::FILES, "filename=" << filename);
3970 // Plain text backend
3971 if (backend_format == "text") {
3972 runparams.flavor = OutputParams::TEXT;
3973 writePlaintextFile(*this, FileName(filename), runparams);
3976 else if (backend_format == "xhtml") {
3977 runparams.flavor = OutputParams::HTML;
3978 setMathFlavor(runparams);
3979 makeLyXHTMLFile(FileName(filename), runparams);
3980 } else if (backend_format == "lyx")
3981 writeFile(FileName(filename));
3983 else if (params().isDocBook()) {
3984 runparams.nice = !put_in_tempdir;
3985 makeDocBookFile(FileName(filename), runparams);
3988 else if (backend_format == format || need_nice_file) {
3989 runparams.nice = true;
3990 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3991 if (d->cloned_buffer_)
3992 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3995 } else if (!lyxrc.tex_allows_spaces
3996 && contains(filePath(), ' ')) {
3997 Alert::error(_("File name error"),
3998 _("The directory path to the document cannot contain spaces."));
3999 return ExportTexPathHasSpaces;
4001 runparams.nice = false;
4002 bool const success = makeLaTeXFile(
4003 FileName(filename), filePath(), runparams);
4004 if (d->cloned_buffer_)
4005 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4010 string const error_type = (format == "program")
4011 ? "Build" : params().bufferFormat();
4012 ErrorList & error_list = d->errorLists[error_type];
4013 string const ext = formats.extension(format);
4014 FileName const tmp_result_file(changeExtension(filename, ext));
4015 bool const success = converters.convert(this, FileName(filename),
4016 tmp_result_file, FileName(absFileName()), backend_format, format,
4019 // Emit the signal to show the error list or copy it back to the
4020 // cloned Buffer so that it can be emitted afterwards.
4021 if (format != backend_format) {
4022 if (runparams.silent)
4024 else if (d->cloned_buffer_)
4025 d->cloned_buffer_->d->errorLists[error_type] =
4026 d->errorLists[error_type];
4029 // also to the children, in case of master-buffer-view
4030 ListOfBuffers clist = getDescendents();
4031 ListOfBuffers::const_iterator cit = clist.begin();
4032 ListOfBuffers::const_iterator const cen = clist.end();
4033 for (; cit != cen; ++cit) {
4034 if (runparams.silent)
4035 (*cit)->d->errorLists[error_type].clear();
4036 else if (d->cloned_buffer_) {
4037 // Enable reverse search by copying back the
4038 // texrow object to the cloned buffer.
4039 // FIXME: this is not thread safe.
4040 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4041 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4042 (*cit)->d->errorLists[error_type];
4044 (*cit)->errors(error_type, true);
4048 if (d->cloned_buffer_) {
4049 // Enable reverse dvi or pdf to work by copying back the texrow
4050 // object to the cloned buffer.
4051 // FIXME: There is a possibility of concurrent access to texrow
4052 // here from the main GUI thread that should be securized.
4053 d->cloned_buffer_->d->texrow = d->texrow;
4054 string const error_type = params().bufferFormat();
4055 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4059 return ExportConverterError;
4061 if (put_in_tempdir) {
4062 result_file = tmp_result_file.absFileName();
4063 return ExportSuccess;
4066 if (dest_filename.empty())
4067 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4069 result_file = dest_filename;
4070 // We need to copy referenced files (e. g. included graphics
4071 // if format == "dvi") to the result dir.
4072 vector<ExportedFile> const files =
4073 runparams.exportdata->externalFiles(format);
4074 string const dest = runparams.export_folder.empty() ?
4075 onlyPath(result_file) : runparams.export_folder;
4076 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4077 : force_overwrite == ALL_FILES;
4078 CopyStatus status = use_force ? FORCE : SUCCESS;
4080 vector<ExportedFile>::const_iterator it = files.begin();
4081 vector<ExportedFile>::const_iterator const en = files.end();
4082 for (; it != en && status != CANCEL; ++it) {
4083 string const fmt = formats.getFormatFromFile(it->sourceName);
4084 string fixedName = it->exportName;
4085 if (!runparams.export_folder.empty()) {
4086 // Relative pathnames starting with ../ will be sanitized
4087 // if exporting to a different folder
4088 while (fixedName.substr(0, 3) == "../")
4089 fixedName = fixedName.substr(3, fixedName.length() - 3);
4091 FileName fixedFileName = makeAbsPath(fixedName, dest);
4092 fixedFileName.onlyPath().createPath();
4093 status = copyFile(fmt, it->sourceName,
4095 it->exportName, status == FORCE,
4096 runparams.export_folder.empty());
4099 if (status == CANCEL) {
4100 message(_("Document export cancelled."));
4101 return ExportCancel;
4104 if (tmp_result_file.exists()) {
4105 // Finally copy the main file
4106 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4107 : force_overwrite != NO_FILES;
4108 if (status == SUCCESS && use_force)
4110 status = copyFile(format, tmp_result_file,
4111 FileName(result_file), result_file,
4113 if (status == CANCEL) {
4114 message(_("Document export cancelled."));
4115 return ExportCancel;
4117 message(bformat(_("Document exported as %1$s "
4119 formats.prettyName(format),
4120 makeDisplayPath(result_file)));
4123 // This must be a dummy converter like fax (bug 1888)
4124 message(bformat(_("Document exported as %1$s"),
4125 formats.prettyName(format)));
4128 return ExportSuccess;
4132 Buffer::ExportStatus Buffer::preview(string const & format) const
4134 bool const update_unincluded =
4135 params().maintain_unincluded_children
4136 && !params().getIncludedChildren().empty();
4137 return preview(format, update_unincluded);
4140 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4142 MarkAsExporting exporting(this);
4144 // (1) export with all included children (omit \includeonly)
4146 ExportStatus const status = doExport(format, true, true, result_file);
4147 if (status != ExportSuccess)
4150 // (2) export with included children only
4151 ExportStatus const status = doExport(format, true, false, result_file);
4152 if (status != ExportSuccess)
4154 if (!formats.view(*this, FileName(result_file), format))
4155 return PreviewError;
4156 return PreviewSuccess;
4160 Buffer::ReadStatus Buffer::extractFromVC()
4162 bool const found = LyXVC::file_not_found_hook(d->filename);
4164 return ReadFileNotFound;
4165 if (!d->filename.isReadableFile())
4171 Buffer::ReadStatus Buffer::loadEmergency()
4173 FileName const emergencyFile = getEmergencyFileName();
4174 if (!emergencyFile.exists()
4175 || emergencyFile.lastModified() <= d->filename.lastModified())
4176 return ReadFileNotFound;
4178 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4179 docstring const text = bformat(_("An emergency save of the document "
4180 "%1$s exists.\n\nRecover emergency save?"), file);
4182 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4183 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4189 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4190 bool const success = (ret_llf == ReadSuccess);
4193 Alert::warning(_("File is read-only"),
4194 bformat(_("An emergency file is successfully loaded, "
4195 "but the original file %1$s is marked read-only. "
4196 "Please make sure to save the document as a different "
4197 "file."), from_utf8(d->filename.absFileName())));
4200 lyxvc().file_found_hook(d->filename);
4201 str = _("Document was successfully recovered.");
4203 str = _("Document was NOT successfully recovered.");
4204 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4205 makeDisplayPath(emergencyFile.absFileName()));
4207 int const del_emerg =
4208 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4209 _("&Remove"), _("&Keep"));
4210 if (del_emerg == 0) {
4211 emergencyFile.removeFile();
4213 Alert::warning(_("Emergency file deleted"),
4214 _("Do not forget to save your file now!"), true);
4216 return success ? ReadSuccess : ReadEmergencyFailure;
4219 int const del_emerg =
4220 Alert::prompt(_("Delete emergency file?"),
4221 _("Remove emergency file now?"), 1, 1,
4222 _("&Remove"), _("&Keep"));
4224 emergencyFile.removeFile();
4225 return ReadOriginal;
4235 Buffer::ReadStatus Buffer::loadAutosave()
4237 // Now check if autosave file is newer.
4238 FileName const autosaveFile = getAutosaveFileName();
4239 if (!autosaveFile.exists()
4240 || autosaveFile.lastModified() <= d->filename.lastModified())
4241 return ReadFileNotFound;
4243 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4244 docstring const text = bformat(_("The backup of the document %1$s "
4245 "is newer.\n\nLoad the backup instead?"), file);
4246 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4247 _("&Load backup"), _("Load &original"), _("&Cancel"));
4252 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4253 // the file is not saved if we load the autosave file.
4254 if (ret_llf == ReadSuccess) {
4256 Alert::warning(_("File is read-only"),
4257 bformat(_("A backup file is successfully loaded, "
4258 "but the original file %1$s is marked read-only. "
4259 "Please make sure to save the document as a "
4261 from_utf8(d->filename.absFileName())));
4264 lyxvc().file_found_hook(d->filename);
4267 return ReadAutosaveFailure;
4270 // Here we delete the autosave
4271 autosaveFile.removeFile();
4272 return ReadOriginal;
4280 Buffer::ReadStatus Buffer::loadLyXFile()
4282 if (!d->filename.isReadableFile()) {
4283 ReadStatus const ret_rvc = extractFromVC();
4284 if (ret_rvc != ReadSuccess)
4288 ReadStatus const ret_re = loadEmergency();
4289 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4292 ReadStatus const ret_ra = loadAutosave();
4293 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4296 return loadThisLyXFile(d->filename);
4300 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4302 return readFile(fn);
4306 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4308 TeXErrors::Errors::const_iterator it = terr.begin();
4309 TeXErrors::Errors::const_iterator end = terr.end();
4310 ListOfBuffers clist = getDescendents();
4311 ListOfBuffers::const_iterator cen = clist.end();
4313 for (; it != end; ++it) {
4316 int errorRow = it->error_in_line;
4317 Buffer const * buf = 0;
4319 if (it->child_name.empty())
4320 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4322 // The error occurred in a child
4323 ListOfBuffers::const_iterator cit = clist.begin();
4324 for (; cit != cen; ++cit) {
4325 string const child_name =
4326 DocFileName(changeExtension(
4327 (*cit)->absFileName(), "tex")).
4329 if (it->child_name != child_name)
4331 (*cit)->d->texrow.getIdFromRow(errorRow,
4332 id_start, pos_start);
4333 if (id_start != -1) {
4334 buf = d->cloned_buffer_
4335 ? (*cit)->d->cloned_buffer_->d->owner_
4336 : (*cit)->d->owner_;
4347 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4348 } while (found && id_start == id_end && pos_start == pos_end);
4350 if (id_start != id_end) {
4351 // Next registered position is outside the inset where
4352 // the error occurred, so signal end-of-paragraph
4356 errorList.push_back(ErrorItem(it->error_desc,
4357 it->error_text, id_start, pos_start, pos_end, buf));
4362 void Buffer::setBuffersForInsets() const
4364 inset().setBuffer(const_cast<Buffer &>(*this));
4368 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4370 LBUFERR(!text().paragraphs().empty());
4372 // Use the master text class also for child documents
4373 Buffer const * const master = masterBuffer();
4374 DocumentClass const & textclass = master->params().documentClass();
4376 // do this only if we are the top-level Buffer
4377 if (master == this) {
4378 textclass.counters().reset(from_ascii("bibitem"));
4379 reloadBibInfoCache();
4382 // keep the buffers to be children in this set. If the call from the
4383 // master comes back we can see which of them were actually seen (i.e.
4384 // via an InsetInclude). The remaining ones in the set need still be updated.
4385 static std::set<Buffer const *> bufToUpdate;
4386 if (scope == UpdateMaster) {
4387 // If this is a child document start with the master
4388 if (master != this) {
4389 bufToUpdate.insert(this);
4390 master->updateBuffer(UpdateMaster, utype);
4391 // If the master buffer has no gui associated with it, then the TocModel is
4392 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4393 // (bug 5699). The same happens if the master buffer is open in a different
4394 // window. This test catches both possibilities.
4395 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4396 // There remains a problem here: If there is another child open in yet a third
4397 // window, that TOC is not updated. So some more general solution is needed at
4399 if (master->d->gui_ != d->gui_)
4402 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4403 if (bufToUpdate.find(this) == bufToUpdate.end())
4407 // start over the counters in the master
4408 textclass.counters().reset();
4411 // update will be done below for this buffer
4412 bufToUpdate.erase(this);
4414 // update all caches
4415 clearReferenceCache();
4418 Buffer & cbuf = const_cast<Buffer &>(*this);
4421 ParIterator parit = cbuf.par_iterator_begin();
4422 updateBuffer(parit, utype);
4425 // TocBackend update will be done later.
4428 d->bibinfo_cache_valid_ = true;
4429 d->cite_labels_valid_ = true;
4430 cbuf.tocBackend().update(utype == OutputUpdate);
4431 if (scope == UpdateMaster)
4432 cbuf.structureChanged();
4436 static depth_type getDepth(DocIterator const & it)
4438 depth_type depth = 0;
4439 for (size_t i = 0 ; i < it.depth() ; ++i)
4440 if (!it[i].inset().inMathed())
4441 depth += it[i].paragraph().getDepth() + 1;
4442 // remove 1 since the outer inset does not count
4446 static depth_type getItemDepth(ParIterator const & it)
4448 Paragraph const & par = *it;
4449 LabelType const labeltype = par.layout().labeltype;
4451 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4454 // this will hold the lowest depth encountered up to now.
4455 depth_type min_depth = getDepth(it);
4456 ParIterator prev_it = it;
4459 --prev_it.top().pit();
4461 // start of nested inset: go to outer par
4463 if (prev_it.empty()) {
4464 // start of document: nothing to do
4469 // We search for the first paragraph with same label
4470 // that is not more deeply nested.
4471 Paragraph & prev_par = *prev_it;
4472 depth_type const prev_depth = getDepth(prev_it);
4473 if (labeltype == prev_par.layout().labeltype) {
4474 if (prev_depth < min_depth)
4475 return prev_par.itemdepth + 1;
4476 if (prev_depth == min_depth)
4477 return prev_par.itemdepth;
4479 min_depth = min(min_depth, prev_depth);
4480 // small optimization: if we are at depth 0, we won't
4481 // find anything else
4482 if (prev_depth == 0)
4488 static bool needEnumCounterReset(ParIterator const & it)
4490 Paragraph const & par = *it;
4491 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4492 depth_type const cur_depth = par.getDepth();
4493 ParIterator prev_it = it;
4494 while (prev_it.pit()) {
4495 --prev_it.top().pit();
4496 Paragraph const & prev_par = *prev_it;
4497 if (prev_par.getDepth() <= cur_depth)
4498 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4500 // start of nested inset: reset
4505 // set the label of a paragraph. This includes the counters.
4506 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4508 BufferParams const & bp = owner_->masterBuffer()->params();
4509 DocumentClass const & textclass = bp.documentClass();
4510 Paragraph & par = it.paragraph();
4511 Layout const & layout = par.layout();
4512 Counters & counters = textclass.counters();
4514 if (par.params().startOfAppendix()) {
4515 // We want to reset the counter corresponding to toplevel sectioning
4516 Layout const & lay = textclass.getTOCLayout();
4517 docstring const cnt = lay.counter;
4519 counters.reset(cnt);
4520 counters.appendix(true);
4522 par.params().appendix(counters.appendix());
4524 // Compute the item depth of the paragraph
4525 par.itemdepth = getItemDepth(it);
4527 if (layout.margintype == MARGIN_MANUAL) {
4528 if (par.params().labelWidthString().empty())
4529 par.params().labelWidthString(par.expandLabel(layout, bp));
4530 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4531 // we do not need to do anything here, since the empty case is
4532 // handled during export.
4534 par.params().labelWidthString(docstring());
4537 switch(layout.labeltype) {
4538 case LABEL_ITEMIZE: {
4539 // At some point of time we should do something more
4540 // clever here, like:
4541 // par.params().labelString(
4542 // bp.user_defined_bullet(par.itemdepth).getText());
4543 // for now, use a simple hardcoded label
4544 docstring itemlabel;
4545 switch (par.itemdepth) {
4547 itemlabel = char_type(0x2022);
4550 itemlabel = char_type(0x2013);
4553 itemlabel = char_type(0x2217);
4556 itemlabel = char_type(0x2219); // or 0x00b7
4559 par.params().labelString(itemlabel);
4563 case LABEL_ENUMERATE: {
4564 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4566 switch (par.itemdepth) {
4575 enumcounter += "iv";
4578 // not a valid enumdepth...
4582 // Maybe we have to reset the enumeration counter.
4583 if (needEnumCounterReset(it))
4584 counters.reset(enumcounter);
4585 counters.step(enumcounter, utype);
4587 string const & lang = par.getParLanguage(bp)->code();
4588 par.params().labelString(counters.theCounter(enumcounter, lang));
4593 case LABEL_SENSITIVE: {
4594 string const & type = counters.current_float();
4595 docstring full_label;
4597 full_label = owner_->B_("Senseless!!! ");
4599 docstring name = owner_->B_(textclass.floats().getType(type).name());
4600 if (counters.hasCounter(from_utf8(type))) {
4601 string const & lang = par.getParLanguage(bp)->code();
4602 counters.step(from_utf8(type), utype);
4603 full_label = bformat(from_ascii("%1$s %2$s:"),
4605 counters.theCounter(from_utf8(type), lang));
4607 full_label = bformat(from_ascii("%1$s #:"), name);
4609 par.params().labelString(full_label);
4613 case LABEL_NO_LABEL:
4614 par.params().labelString(docstring());
4618 case LABEL_CENTERED:
4619 case LABEL_STATIC: {
4620 docstring const & lcounter = layout.counter;
4621 if (!lcounter.empty()) {
4622 if (layout.toclevel <= bp.secnumdepth
4623 && (layout.latextype != LATEX_ENVIRONMENT
4624 || it.text()->isFirstInSequence(it.pit()))) {
4625 if (counters.hasCounter(lcounter))
4626 counters.step(lcounter, utype);
4627 par.params().labelString(par.expandLabel(layout, bp));
4629 par.params().labelString(docstring());
4631 par.params().labelString(par.expandLabel(layout, bp));
4637 par.params().labelString(par.expandLabel(layout, bp));
4642 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4644 // LASSERT: Is it safe to continue here, or should we just return?
4645 LASSERT(parit.pit() == 0, /**/);
4647 // Set the position of the text in the buffer to be able
4648 // to resolve macros in it.
4649 parit.text()->setMacrocontextPosition(parit);
4651 depth_type maxdepth = 0;
4652 pit_type const lastpit = parit.lastpit();
4653 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4654 // reduce depth if necessary
4655 if (parit->params().depth() > maxdepth) {
4656 /** FIXME: this function is const, but
4657 * nevertheless it modifies the buffer. To be
4658 * cleaner, one should modify the buffer in
4659 * another function, which is actually
4660 * non-const. This would however be costly in
4661 * terms of code duplication.
4663 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4664 parit->params().depth(maxdepth);
4666 maxdepth = parit->getMaxDepthAfter();
4668 if (utype == OutputUpdate) {
4669 // track the active counters
4670 // we have to do this for the master buffer, since the local
4671 // buffer isn't tracking anything.
4672 masterBuffer()->params().documentClass().counters().
4673 setActiveLayout(parit->layout());
4676 // set the counter for this paragraph
4677 d->setLabel(parit, utype);
4680 InsetList::const_iterator iit = parit->insetList().begin();
4681 InsetList::const_iterator end = parit->insetList().end();
4682 for (; iit != end; ++iit) {
4683 parit.pos() = iit->pos;
4684 iit->inset->updateBuffer(parit, utype);
4690 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4691 WordLangTuple & word_lang, docstring_list & suggestions) const
4695 suggestions.clear();
4696 word_lang = WordLangTuple();
4697 bool const to_end = to.empty();
4698 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4699 // OK, we start from here.
4700 for (; from != end; from.forwardPos()) {
4701 // We are only interested in text so remove the math CursorSlice.
4702 while (from.inMathed()) {
4706 // If from is at the end of the document (which is possible
4707 // when leaving the mathed) LyX will crash later otherwise.
4708 if (from.atEnd() || (!to_end && from >= end))
4711 from.paragraph().spellCheck();
4712 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4713 if (SpellChecker::misspelled(res)) {
4718 // Do not increase progress when from == to, otherwise the word
4719 // count will be wrong.
4729 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4731 bool inword = false;
4736 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4737 if (!dit.inTexted()) {
4742 Paragraph const & par = dit.paragraph();
4743 pos_type const pos = dit.pos();
4745 // Copied and adapted from isWordSeparator() in Paragraph
4746 if (pos == dit.lastpos()) {
4749 Inset const * ins = par.getInset(pos);
4750 if (ins && skipNoOutput && !ins->producesOutput()) {
4753 // stop if end of range was skipped
4754 if (!to.atEnd() && dit >= to)
4757 } else if (!par.isDeleted(pos)) {
4758 if (par.isWordSeparator(pos))
4764 if (ins && ins->isLetter())
4766 else if (ins && ins->isSpace())
4769 char_type const c = par.getChar(pos);
4770 if (isPrintableNonspace(c))
4772 else if (isSpace(c))
4782 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4784 d->updateStatistics(from, to, skipNoOutput);
4788 int Buffer::wordCount() const
4790 return d->wordCount();
4794 int Buffer::charCount(bool with_blanks) const
4796 return d->charCount(with_blanks);
4800 Buffer::ReadStatus Buffer::reload()
4803 // c.f. bug http://www.lyx.org/trac/ticket/6587
4804 removeAutosaveFile();
4805 // e.g., read-only status could have changed due to version control
4806 d->filename.refresh();
4807 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4809 // clear parent. this will get reset if need be.
4811 ReadStatus const status = loadLyXFile();
4812 if (status == ReadSuccess) {
4817 message(bformat(_("Document %1$s reloaded."), disp_fn));
4820 message(bformat(_("Could not reload document %1$s."), disp_fn));
4830 bool Buffer::saveAs(FileName const & fn)
4832 FileName const old_name = fileName();
4833 FileName const old_auto = getAutosaveFileName();
4834 bool const old_unnamed = isUnnamed();
4841 // bring the autosave file with us, just in case.
4842 moveAutosaveFile(old_auto);
4843 // validate version control data and
4844 // correct buffer title
4845 lyxvc().file_found_hook(fileName());
4847 // the file has now been saved to the new location.
4848 // we need to check that the locations of child buffers
4850 checkChildBuffers();
4851 checkMasterBuffer();
4855 // reset the old filename and unnamed state
4856 setFileName(old_name);
4857 setUnnamed(old_unnamed);
4863 // FIXME We could do better here, but it is complicated. What would be
4864 // nice is to offer either (a) to save the child buffer to an appropriate
4865 // location, so that it would "move with the master", or else (b) to update
4866 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4867 // complicated, because the code for this lives in GuiView.
4868 void Buffer::checkChildBuffers()
4870 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4871 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4872 for (; it != en; ++it) {
4873 DocIterator dit = it->second;
4874 Buffer * cbuf = const_cast<Buffer *>(it->first);
4875 if (!cbuf || !theBufferList().isLoaded(cbuf))
4877 Inset * inset = dit.nextInset();
4878 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4879 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4880 docstring const & incfile = inset_inc->getParam("filename");
4881 string oldloc = cbuf->absFileName();
4882 string newloc = makeAbsPath(to_utf8(incfile),
4883 onlyPath(absFileName())).absFileName();
4884 if (oldloc == newloc)
4886 // the location of the child file is incorrect.
4887 Alert::warning(_("Included File Invalid"),
4888 bformat(_("Saving this document to a new location has made the file:\n"
4890 "inaccessible. You will need to update the included filename."),
4891 from_utf8(oldloc)));
4893 inset_inc->setChildBuffer(0);
4895 // invalidate cache of children
4896 d->children_positions.clear();
4897 d->position_to_children.clear();
4901 // If a child has been saved under a different name/path, it might have been
4902 // orphaned. Therefore the master needs to be reset (bug 8161).
4903 void Buffer::checkMasterBuffer()
4905 Buffer const * const master = masterBuffer();
4909 // necessary to re-register the child (bug 5873)
4910 // FIXME: clean up updateMacros (here, only
4911 // child registering is needed).
4912 master->updateMacros();
4913 // (re)set master as master buffer, but only
4914 // if we are a real child
4915 if (master->isChild(this))