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 FileName const fn = FileName::tempName("Buffer_readString");
1056 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1058 if (success && file_format != LYX_FORMAT) {
1059 // We need to call lyx2lyx, so write the input to a file
1060 ofstream os(fn.toFilesystemEncoding().c_str());
1063 // lyxvc in readFile
1064 if (readFile(fn) != ReadSuccess)
1068 if (readDocument(lex))
1076 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1080 if (!lex.setFile(fname)) {
1081 Alert::error(_("File Not Found"),
1082 bformat(_("Unable to open file `%1$s'."),
1083 from_utf8(fn.absFileName())));
1084 return ReadFileNotFound;
1088 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1089 if (ret_plf != ReadSuccess)
1092 if (file_format != LYX_FORMAT) {
1094 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1095 if (ret_clf != ReadSuccess)
1097 return readFile(tmpFile);
1100 // FIXME: InsetInfo needs to know whether the file is under VCS
1101 // during the parse process, so this has to be done before.
1102 lyxvc().file_found_hook(d->filename);
1104 if (readDocument(lex)) {
1105 Alert::error(_("Document format failure"),
1106 bformat(_("%1$s ended unexpectedly, which means"
1107 " that it is probably corrupted."),
1108 from_utf8(fn.absFileName())));
1109 return ReadDocumentFailure;
1112 d->file_fully_loaded = true;
1113 d->read_only = !d->filename.isWritable();
1114 params().compressed = formats.isZippedFile(d->filename);
1120 bool Buffer::isFullyLoaded() const
1122 return d->file_fully_loaded;
1126 void Buffer::setFullyLoaded(bool value)
1128 d->file_fully_loaded = value;
1132 PreviewLoader * Buffer::loader() const
1134 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1136 if (!d->preview_loader_)
1137 d->preview_loader_ = new PreviewLoader(*this);
1138 return d->preview_loader_;
1142 void Buffer::removePreviews() const
1144 delete d->preview_loader_;
1145 d->preview_loader_ = 0;
1149 void Buffer::updatePreviews() const
1151 PreviewLoader * ploader = loader();
1155 InsetIterator it = inset_iterator_begin(*d->inset);
1156 InsetIterator const end = inset_iterator_end(*d->inset);
1157 for (; it != end; ++it)
1158 it->addPreview(it, *ploader);
1160 ploader->startLoading();
1164 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1165 FileName const & fn, int & file_format) const
1167 if(!lex.checkFor("\\lyxformat")) {
1168 Alert::error(_("Document format failure"),
1169 bformat(_("%1$s is not a readable LyX document."),
1170 from_utf8(fn.absFileName())));
1171 return ReadNoLyXFormat;
1177 // LyX formats 217 and earlier were written as 2.17. This corresponds
1178 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1179 // these cases. See also: www.lyx.org/trac/changeset/1313.
1180 size_t dot = tmp_format.find_first_of(".,");
1181 if (dot != string::npos)
1182 tmp_format.erase(dot, 1);
1184 file_format = convert<int>(tmp_format);
1189 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1190 FileName & tmpfile, int from_format)
1192 tmpfile = FileName::tempName("Buffer_convertLyXFormatXXXXXX.lyx");
1193 if(tmpfile.empty()) {
1194 Alert::error(_("Conversion failed"),
1195 bformat(_("%1$s is from a different"
1196 " version of LyX, but a temporary"
1197 " file for converting it could"
1198 " not be created."),
1199 from_utf8(fn.absFileName())));
1200 return LyX2LyXNoTempFile;
1203 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1204 if (lyx2lyx.empty()) {
1205 Alert::error(_("Conversion script not found"),
1206 bformat(_("%1$s is from a different"
1207 " version of LyX, but the"
1208 " conversion script lyx2lyx"
1209 " could not be found."),
1210 from_utf8(fn.absFileName())));
1211 return LyX2LyXNotFound;
1215 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1216 ostringstream command;
1217 command << os::python()
1218 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1219 << " -t " << convert<string>(LYX_FORMAT)
1220 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1221 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1222 string const command_str = command.str();
1224 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1226 cmd_ret const ret = runCommand(command_str);
1227 if (ret.first != 0) {
1228 if (from_format < LYX_FORMAT) {
1229 Alert::error(_("Conversion script failed"),
1230 bformat(_("%1$s is from an older version"
1231 " of LyX and the lyx2lyx script"
1232 " failed to convert it."),
1233 from_utf8(fn.absFileName())));
1234 return LyX2LyXOlderFormat;
1236 Alert::error(_("Conversion script failed"),
1237 bformat(_("%1$s is from a newer version"
1238 " of LyX and the lyx2lyx script"
1239 " failed to convert it."),
1240 from_utf8(fn.absFileName())));
1241 return LyX2LyXNewerFormat;
1248 // Should probably be moved to somewhere else: BufferView? GuiView?
1249 bool Buffer::save() const
1251 docstring const file = makeDisplayPath(absFileName(), 20);
1252 d->filename.refresh();
1254 // check the read-only status before moving the file as a backup
1255 if (d->filename.exists()) {
1256 bool const read_only = !d->filename.isWritable();
1258 Alert::warning(_("File is read-only"),
1259 bformat(_("The file %1$s cannot be written because it "
1260 "is marked as read-only."), file));
1265 // ask if the disk file has been externally modified (use checksum method)
1266 if (fileName().exists() && isExternallyModified(checksum_method)) {
1268 bformat(_("Document %1$s has been externally modified. "
1269 "Are you sure you want to overwrite this file?"), file);
1270 int const ret = Alert::prompt(_("Overwrite modified file?"),
1271 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1276 // We don't need autosaves in the immediate future. (Asger)
1277 resetAutosaveTimers();
1279 FileName backupName;
1280 bool madeBackup = false;
1282 // make a backup if the file already exists
1283 if (lyxrc.make_backup && fileName().exists()) {
1284 backupName = FileName(absFileName() + '~');
1285 if (!lyxrc.backupdir_path.empty()) {
1286 string const mangledName =
1287 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1288 backupName = FileName(addName(lyxrc.backupdir_path,
1292 // Except file is symlink do not copy because of #6587.
1293 // Hard links have bad luck.
1294 if (fileName().isSymLink())
1295 madeBackup = fileName().copyTo(backupName);
1297 madeBackup = fileName().moveTo(backupName);
1300 Alert::error(_("Backup failure"),
1301 bformat(_("Cannot create backup file %1$s.\n"
1302 "Please check whether the directory exists and is writable."),
1303 from_utf8(backupName.absFileName())));
1304 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1308 if (writeFile(d->filename)) {
1312 // Saving failed, so backup is not backup
1314 backupName.moveTo(d->filename);
1320 bool Buffer::writeFile(FileName const & fname) const
1322 if (d->read_only && fname == d->filename)
1325 bool retval = false;
1327 docstring const str = bformat(_("Saving document %1$s..."),
1328 makeDisplayPath(fname.absFileName()));
1331 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1333 if (params().compressed) {
1334 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1335 retval = ofs && write(ofs);
1337 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1338 retval = ofs && write(ofs);
1342 message(str + _(" could not write file!"));
1347 // removeAutosaveFile();
1350 message(str + _(" done."));
1356 docstring Buffer::emergencyWrite()
1358 // No need to save if the buffer has not changed.
1362 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1364 docstring user_message = bformat(
1365 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1367 // We try to save three places:
1368 // 1) Same place as document. Unless it is an unnamed doc.
1370 string s = absFileName();
1373 if (writeFile(FileName(s))) {
1375 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1376 return user_message;
1378 user_message += " " + _("Save failed! Trying again...\n");
1382 // 2) In HOME directory.
1383 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1385 lyxerr << ' ' << s << endl;
1386 if (writeFile(FileName(s))) {
1388 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1389 return user_message;
1392 user_message += " " + _("Save failed! Trying yet again...\n");
1394 // 3) In "/tmp" directory.
1395 // MakeAbsPath to prepend the current
1396 // drive letter on OS/2
1397 s = addName(package().temp_dir().absFileName(), absFileName());
1399 lyxerr << ' ' << s << endl;
1400 if (writeFile(FileName(s))) {
1402 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1403 return user_message;
1406 user_message += " " + _("Save failed! Bummer. Document is lost.");
1409 return user_message;
1413 bool Buffer::write(ostream & ofs) const
1416 // Use the standard "C" locale for file output.
1417 ofs.imbue(locale::classic());
1420 // The top of the file should not be written by params().
1422 // write out a comment in the top of the file
1423 // Important: Keep the version formatting in sync with lyx2lyx and
1424 // tex2lyx (bug 7951)
1425 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1426 << " created this file. For more info see http://www.lyx.org/\n"
1427 << "\\lyxformat " << LYX_FORMAT << "\n"
1428 << "\\begin_document\n";
1430 /// For each author, set 'used' to true if there is a change
1431 /// by this author in the document; otherwise set it to 'false'.
1432 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1433 AuthorList::Authors::const_iterator a_end = params().authors().end();
1434 for (; a_it != a_end; ++a_it)
1435 a_it->setUsed(false);
1437 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1438 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1439 for ( ; it != end; ++it)
1440 it->checkAuthors(params().authors());
1442 // now write out the buffer parameters.
1443 ofs << "\\begin_header\n";
1444 params().writeFile(ofs);
1445 ofs << "\\end_header\n";
1448 ofs << "\n\\begin_body\n";
1450 ofs << "\n\\end_body\n";
1452 // Write marker that shows file is complete
1453 ofs << "\\end_document" << endl;
1455 // Shouldn't really be needed....
1458 // how to check if close went ok?
1459 // Following is an attempt... (BE 20001011)
1461 // good() returns false if any error occured, including some
1462 // formatting error.
1463 // bad() returns true if something bad happened in the buffer,
1464 // which should include file system full errors.
1469 lyxerr << "File was not closed properly." << endl;
1476 bool Buffer::makeLaTeXFile(FileName const & fname,
1477 string const & original_path,
1478 OutputParams const & runparams_in,
1479 OutputWhat output) const
1481 OutputParams runparams = runparams_in;
1483 // This is necessary for LuaTeX/XeTeX with tex fonts.
1484 // See FIXME in BufferParams::encoding()
1485 if (runparams.isFullUnicode())
1486 runparams.encoding = encodings.fromLyXName("utf8-plain");
1488 string const encoding = runparams.encoding->iconvName();
1489 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1492 try { ofs.reset(encoding); }
1493 catch (iconv_codecvt_facet_exception const & e) {
1494 lyxerr << "Caught iconv exception: " << e.what() << endl;
1495 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1496 "verify that the support software for your encoding (%1$s) is "
1497 "properly installed"), from_ascii(encoding)));
1500 if (!openFileWrite(ofs, fname))
1503 ErrorList & errorList = d->errorLists["Export"];
1505 bool failed_export = false;
1506 otexstream os(ofs, d->texrow);
1508 // make sure we are ready to export
1509 // this needs to be done before we validate
1510 // FIXME Do we need to do this all the time? I.e., in children
1511 // of a master we are exporting?
1513 updateMacroInstances(OutputUpdate);
1516 os.texrow().reset();
1517 writeLaTeXSource(os, original_path, runparams, output);
1519 catch (EncodingException const & e) {
1520 odocstringstream ods;
1521 ods.put(e.failed_char);
1523 oss << "0x" << hex << e.failed_char << dec;
1524 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1525 " (code point %2$s)"),
1526 ods.str(), from_utf8(oss.str()));
1527 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1528 "representable in the chosen encoding.\n"
1529 "Changing the document encoding to utf8 could help."),
1530 e.par_id, e.pos, e.pos + 1));
1531 failed_export = true;
1533 catch (iconv_codecvt_facet_exception const & e) {
1534 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1535 _(e.what()), -1, 0, 0));
1536 failed_export = true;
1538 catch (exception const & e) {
1539 errorList.push_back(ErrorItem(_("conversion failed"),
1540 _(e.what()), -1, 0, 0));
1541 failed_export = true;
1544 lyxerr << "Caught some really weird exception..." << endl;
1550 failed_export = true;
1551 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1554 if (runparams_in.silent)
1558 return !failed_export;
1562 void Buffer::writeLaTeXSource(otexstream & os,
1563 string const & original_path,
1564 OutputParams const & runparams_in,
1565 OutputWhat output) const
1567 // The child documents, if any, shall be already loaded at this point.
1569 OutputParams runparams = runparams_in;
1571 // If we are compiling a file standalone, even if this is the
1572 // child of some other buffer, let's cut the link here, so the
1573 // file is really independent and no concurring settings from
1574 // the master (e.g. branch state) interfere (see #8100).
1575 if (!runparams.is_child)
1576 d->ignore_parent = true;
1578 // Classify the unicode characters appearing in math insets
1579 BufferEncodings::initUnicodeMath(*this);
1581 // validate the buffer.
1582 LYXERR(Debug::LATEX, " Validating buffer...");
1583 LaTeXFeatures features(*this, params(), runparams);
1585 // This is only set once per document (in master)
1586 if (!runparams.is_child)
1587 runparams.use_polyglossia = features.usePolyglossia();
1588 LYXERR(Debug::LATEX, " Buffer validation done.");
1590 bool const output_preamble =
1591 output == FullSource || output == OnlyPreamble;
1592 bool const output_body =
1593 output == FullSource || output == OnlyBody;
1595 // The starting paragraph of the coming rows is the
1596 // first paragraph of the document. (Asger)
1597 if (output_preamble && runparams.nice) {
1598 os << "%% LyX " << lyx_version << " created this file. "
1599 "For more info, see http://www.lyx.org/.\n"
1600 "%% Do not edit unless you really know what "
1603 LYXERR(Debug::INFO, "lyx document header finished");
1605 // There are a few differences between nice LaTeX and usual files:
1606 // usual files have \batchmode and special input@path to allow
1607 // inclusion of figures specified by an explicitly relative path
1608 // (i.e., a path starting with './' or '../') with either \input or
1609 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1610 // input@path is set when the actual parameter original_path is set.
1611 // This is done for usual tex-file, but not for nice-latex-file.
1612 // (Matthias 250696)
1613 // Note that input@path is only needed for something the user does
1614 // in the preamble, included .tex files or ERT, files included by
1615 // LyX work without it.
1616 if (output_preamble) {
1617 if (!runparams.nice) {
1618 // code for usual, NOT nice-latex-file
1619 os << "\\batchmode\n"; // changed from \nonstopmode
1621 if (!original_path.empty()) {
1623 // We don't know the encoding of inputpath
1624 docstring const inputpath = from_utf8(original_path);
1625 docstring uncodable_glyphs;
1626 Encoding const * const enc = runparams.encoding;
1628 for (size_t n = 0; n < inputpath.size(); ++n) {
1629 if (!enc->encodable(inputpath[n])) {
1630 docstring const glyph(1, inputpath[n]);
1631 LYXERR0("Uncodable character '"
1633 << "' in input path!");
1634 uncodable_glyphs += glyph;
1639 // warn user if we found uncodable glyphs.
1640 if (!uncodable_glyphs.empty()) {
1641 frontend::Alert::warning(
1642 _("Uncodable character in file path"),
1644 _("The path of your document\n"
1646 "contains glyphs that are unknown "
1647 "in the current document encoding "
1648 "(namely %2$s). This may result in "
1649 "incomplete output, unless "
1650 "TEXINPUTS contains the document "
1651 "directory and you don't use "
1652 "explicitly relative paths (i.e., "
1653 "paths starting with './' or "
1654 "'../') in the preamble or in ERT."
1655 "\n\nIn case of problems, choose "
1656 "an appropriate document encoding\n"
1657 "(such as utf8) or change the "
1659 inputpath, uncodable_glyphs));
1662 support::latex_path(original_path);
1663 if (contains(docdir, '#')) {
1664 docdir = subst(docdir, "#", "\\#");
1665 os << "\\catcode`\\#=11"
1666 "\\def\\#{#}\\catcode`\\#=6\n";
1668 if (contains(docdir, '%')) {
1669 docdir = subst(docdir, "%", "\\%");
1670 os << "\\catcode`\\%=11"
1671 "\\def\\%{%}\\catcode`\\%=14\n";
1673 os << "\\makeatletter\n"
1674 << "\\def\\input@path{{"
1675 << docdir << "/}}\n"
1676 << "\\makeatother\n";
1680 // get parent macros (if this buffer has a parent) which will be
1681 // written at the document begin further down.
1682 MacroSet parentMacros;
1683 listParentMacros(parentMacros, features);
1685 // Write the preamble
1686 runparams.use_babel = params().writeLaTeX(os, features,
1687 d->filename.onlyPath());
1689 // Japanese might be required only in some children of a document,
1690 // but once required, we must keep use_japanese true.
1691 runparams.use_japanese |= features.isRequired("japanese");
1694 // Restore the parenthood if needed
1695 if (!runparams.is_child)
1696 d->ignore_parent = false;
1701 os << "\\begin{document}\n";
1703 // output the parent macros
1704 MacroSet::iterator it = parentMacros.begin();
1705 MacroSet::iterator end = parentMacros.end();
1706 for (; it != end; ++it) {
1707 int num_lines = (*it)->write(os.os(), true);
1708 os.texrow().newlines(num_lines);
1711 } // output_preamble
1713 os.texrow().start(paragraphs().begin()->id(), 0);
1715 LYXERR(Debug::INFO, "preamble finished, now the body.");
1718 latexParagraphs(*this, text(), os, runparams);
1720 // Restore the parenthood if needed
1721 if (!runparams.is_child)
1722 d->ignore_parent = false;
1724 // add this just in case after all the paragraphs
1727 if (output_preamble) {
1728 os << "\\end{document}\n";
1729 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1731 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1733 runparams_in.encoding = runparams.encoding;
1735 // Just to be sure. (Asger)
1736 os.texrow().newline();
1738 //for (int i = 0; i<d->texrow.rows(); i++) {
1740 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1741 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1744 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1745 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1749 void Buffer::makeDocBookFile(FileName const & fname,
1750 OutputParams const & runparams,
1751 OutputWhat output) const
1753 LYXERR(Debug::LATEX, "makeDocBookFile...");
1756 if (!openFileWrite(ofs, fname))
1759 // make sure we are ready to export
1760 // this needs to be done before we validate
1762 updateMacroInstances(OutputUpdate);
1764 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1768 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1772 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1773 OutputParams const & runparams,
1774 OutputWhat output) const
1776 LaTeXFeatures features(*this, params(), runparams);
1781 DocumentClass const & tclass = params().documentClass();
1782 string const top_element = tclass.latexname();
1784 bool const output_preamble =
1785 output == FullSource || output == OnlyPreamble;
1786 bool const output_body =
1787 output == FullSource || output == OnlyBody;
1789 if (output_preamble) {
1790 if (runparams.flavor == OutputParams::XML)
1791 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1794 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1797 if (! tclass.class_header().empty())
1798 os << from_ascii(tclass.class_header());
1799 else if (runparams.flavor == OutputParams::XML)
1800 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1801 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1803 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1805 docstring preamble = from_utf8(params().preamble);
1806 if (runparams.flavor != OutputParams::XML ) {
1807 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1808 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1809 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1810 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1813 string const name = runparams.nice
1814 ? changeExtension(absFileName(), ".sgml") : fname;
1815 preamble += features.getIncludedFiles(name);
1816 preamble += features.getLyXSGMLEntities();
1818 if (!preamble.empty()) {
1819 os << "\n [ " << preamble << " ]";
1825 string top = top_element;
1827 if (runparams.flavor == OutputParams::XML)
1828 top += params().language->code();
1830 top += params().language->code().substr(0, 2);
1833 if (!params().options.empty()) {
1835 top += params().options;
1838 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1839 << " file was created by LyX " << lyx_version
1840 << "\n See http://www.lyx.org/ for more information -->\n";
1842 params().documentClass().counters().reset();
1844 sgml::openTag(os, top);
1846 docbookParagraphs(text(), *this, os, runparams);
1847 sgml::closeTag(os, top_element);
1852 void Buffer::makeLyXHTMLFile(FileName const & fname,
1853 OutputParams const & runparams) const
1855 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1858 if (!openFileWrite(ofs, fname))
1861 // make sure we are ready to export
1862 // this has to be done before we validate
1863 updateBuffer(UpdateMaster, OutputUpdate);
1864 updateMacroInstances(OutputUpdate);
1866 writeLyXHTMLSource(ofs, runparams, FullSource);
1870 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1874 void Buffer::writeLyXHTMLSource(odocstream & os,
1875 OutputParams const & runparams,
1876 OutputWhat output) const
1878 LaTeXFeatures features(*this, params(), runparams);
1880 d->bibinfo_.makeCitationLabels(*this);
1882 bool const output_preamble =
1883 output == FullSource || output == OnlyPreamble;
1884 bool const output_body =
1885 output == FullSource || output == OnlyBody || output == IncludedFile;
1887 if (output_preamble) {
1888 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1889 << "<!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"
1890 // FIXME Language should be set properly.
1891 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1893 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1894 // FIXME Presumably need to set this right
1895 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1897 docstring const & doctitle = features.htmlTitle();
1899 << (doctitle.empty() ?
1900 from_ascii("LyX Document") :
1901 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1904 docstring styles = features.getTClassHTMLPreamble();
1905 if (!styles.empty())
1906 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1908 styles = from_utf8(features.getPreambleSnippets());
1909 if (!styles.empty())
1910 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1912 // we will collect CSS information in a stream, and then output it
1913 // either here, as part of the header, or else in a separate file.
1914 odocstringstream css;
1915 styles = from_utf8(features.getCSSSnippets());
1916 if (!styles.empty())
1917 css << "/* LyX Provided Styles */\n" << styles << '\n';
1919 styles = features.getTClassHTMLStyles();
1920 if (!styles.empty())
1921 css << "/* Layout-provided Styles */\n" << styles << '\n';
1923 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1924 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1925 if (needfg || needbg) {
1926 css << "\nbody {\n";
1929 << from_ascii(X11hexname(params().fontcolor))
1932 css << " background-color: "
1933 << from_ascii(X11hexname(params().backgroundcolor))
1938 docstring const dstyles = css.str();
1939 if (!dstyles.empty()) {
1940 bool written = false;
1941 if (params().html_css_as_file) {
1942 // open a file for CSS info
1944 string const fcssname = addName(temppath(), "docstyle.css");
1945 FileName const fcssfile = FileName(fcssname);
1946 if (openFileWrite(ocss, fcssfile)) {
1950 // write link to header
1951 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1953 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1956 // we are here if the CSS is supposed to be written to the header
1957 // or if we failed to write it to an external file.
1959 os << "<style type='text/css'>\n"
1968 bool const output_body_tag = (output != IncludedFile);
1969 if (output_body_tag)
1972 if (output != IncludedFile)
1973 // if we're an included file, the counters are in the master.
1974 params().documentClass().counters().reset();
1975 xhtmlParagraphs(text(), *this, xs, runparams);
1976 if (output_body_tag)
1980 if (output_preamble)
1985 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1986 // Other flags: -wall -v0 -x
1987 int Buffer::runChktex()
1991 // get LaTeX-Filename
1992 FileName const path(temppath());
1993 string const name = addName(path.absFileName(), latexName());
1994 string const org_path = filePath();
1996 PathChanger p(path); // path to LaTeX file
1997 message(_("Running chktex..."));
1999 // Generate the LaTeX file if neccessary
2000 OutputParams runparams(¶ms().encoding());
2001 runparams.flavor = OutputParams::LATEX;
2002 runparams.nice = false;
2003 runparams.linelen = lyxrc.plaintext_linelen;
2004 makeLaTeXFile(FileName(name), org_path, runparams);
2007 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2008 int const res = chktex.run(terr); // run chktex
2011 Alert::error(_("chktex failure"),
2012 _("Could not run chktex successfully."));
2014 ErrorList & errlist = d->errorLists["ChkTeX"];
2016 bufferErrors(terr, errlist);
2021 if (runparams.silent)
2022 d->errorLists["ChkTeX"].clear();
2030 void Buffer::validate(LaTeXFeatures & features) const
2032 // Validate the buffer params, but not for included
2033 // files, since they also use the parent buffer's
2035 if (!features.runparams().is_child)
2036 params().validate(features);
2038 for_each(paragraphs().begin(), paragraphs().end(),
2039 bind(&Paragraph::validate, _1, ref(features)));
2041 if (lyxerr.debugging(Debug::LATEX)) {
2042 features.showStruct();
2047 void Buffer::getLabelList(vector<docstring> & list) const
2049 // If this is a child document, use the master's list instead.
2051 masterBuffer()->getLabelList(list);
2056 Toc & toc = d->toc_backend.toc("label");
2057 TocIterator toc_it = toc.begin();
2058 TocIterator end = toc.end();
2059 for (; toc_it != end; ++toc_it) {
2060 if (toc_it->depth() == 0)
2061 list.push_back(toc_it->str());
2066 void Buffer::updateBibfilesCache(UpdateScope scope) const
2068 // FIXME This is probably unnecssary, given where we call this.
2069 // If this is a child document, use the parent's cache instead.
2070 if (parent() && scope != UpdateChildOnly) {
2071 masterBuffer()->updateBibfilesCache();
2075 d->bibfiles_cache_.clear();
2076 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2077 if (it->lyxCode() == BIBTEX_CODE) {
2078 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2079 support::FileNameList const bibfiles = inset.getBibFiles();
2080 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2083 } else if (it->lyxCode() == INCLUDE_CODE) {
2084 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2085 Buffer const * const incbuf = inset.getChildBuffer();
2088 support::FileNameList const & bibfiles =
2089 incbuf->getBibfilesCache(UpdateChildOnly);
2090 if (!bibfiles.empty()) {
2091 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2097 d->bibfile_cache_valid_ = true;
2098 d->bibinfo_cache_valid_ = false;
2099 d->cite_labels_valid_ = false;
2103 void Buffer::invalidateBibinfoCache() const
2105 d->bibinfo_cache_valid_ = false;
2106 d->cite_labels_valid_ = false;
2107 // also invalidate the cache for the parent buffer
2108 Buffer const * const pbuf = d->parent();
2110 pbuf->invalidateBibinfoCache();
2114 void Buffer::invalidateBibfileCache() const
2116 d->bibfile_cache_valid_ = false;
2117 d->bibinfo_cache_valid_ = false;
2118 d->cite_labels_valid_ = false;
2119 // also invalidate the cache for the parent buffer
2120 Buffer const * const pbuf = d->parent();
2122 pbuf->invalidateBibfileCache();
2126 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2128 // FIXME This is probably unnecessary, given where we call this.
2129 // If this is a child document, use the master's cache instead.
2130 Buffer const * const pbuf = masterBuffer();
2131 if (pbuf != this && scope != UpdateChildOnly)
2132 return pbuf->getBibfilesCache();
2134 if (!d->bibfile_cache_valid_)
2135 this->updateBibfilesCache(scope);
2137 return d->bibfiles_cache_;
2141 BiblioInfo const & Buffer::masterBibInfo() const
2143 Buffer const * const tmp = masterBuffer();
2145 return tmp->masterBibInfo();
2150 void Buffer::checkIfBibInfoCacheIsValid() const
2152 // use the master's cache
2153 Buffer const * const tmp = masterBuffer();
2155 tmp->checkIfBibInfoCacheIsValid();
2159 // compare the cached timestamps with the actual ones.
2160 FileNameList const & bibfiles_cache = getBibfilesCache();
2161 FileNameList::const_iterator ei = bibfiles_cache.begin();
2162 FileNameList::const_iterator en = bibfiles_cache.end();
2163 for (; ei != en; ++ ei) {
2164 time_t lastw = ei->lastModified();
2165 time_t prevw = d->bibfile_status_[*ei];
2166 if (lastw != prevw) {
2167 d->bibinfo_cache_valid_ = false;
2168 d->cite_labels_valid_ = false;
2169 d->bibfile_status_[*ei] = lastw;
2175 void Buffer::reloadBibInfoCache() const
2177 // use the master's cache
2178 Buffer const * const tmp = masterBuffer();
2180 tmp->reloadBibInfoCache();
2184 checkIfBibInfoCacheIsValid();
2185 if (d->bibinfo_cache_valid_)
2188 d->bibinfo_.clear();
2190 d->bibinfo_cache_valid_ = true;
2194 void Buffer::collectBibKeys() const
2196 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2197 it->collectBibKeys(it);
2201 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2203 Buffer const * tmp = masterBuffer();
2204 BiblioInfo & masterbi = (tmp == this) ?
2205 d->bibinfo_ : tmp->d->bibinfo_;
2206 masterbi.mergeBiblioInfo(bi);
2210 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2212 Buffer const * tmp = masterBuffer();
2213 BiblioInfo & masterbi = (tmp == this) ?
2214 d->bibinfo_ : tmp->d->bibinfo_;
2219 void Buffer::makeCitationLabels() const
2221 Buffer const * const master = masterBuffer();
2222 return d->bibinfo_.makeCitationLabels(*master);
2226 bool Buffer::citeLabelsValid() const
2228 return masterBuffer()->d->cite_labels_valid_;
2232 void Buffer::removeBiblioTempFiles() const
2234 // We remove files that contain LaTeX commands specific to the
2235 // particular bibliographic style being used, in order to avoid
2236 // LaTeX errors when we switch style.
2237 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2238 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2239 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2240 aux_file.removeFile();
2241 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2242 bbl_file.removeFile();
2243 // Also for the parent buffer
2244 Buffer const * const pbuf = parent();
2246 pbuf->removeBiblioTempFiles();
2250 bool Buffer::isDepClean(string const & name) const
2252 DepClean::const_iterator const it = d->dep_clean.find(name);
2253 if (it == d->dep_clean.end())
2259 void Buffer::markDepClean(string const & name)
2261 d->dep_clean[name] = true;
2265 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2268 // FIXME? if there is an Buffer LFUN that can be dispatched even
2269 // if internal, put a switch '(cmd.action)' here.
2275 switch (cmd.action()) {
2277 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2278 flag.setOnOff(isReadonly());
2281 // FIXME: There is need for a command-line import.
2282 //case LFUN_BUFFER_IMPORT:
2284 case LFUN_BUFFER_AUTO_SAVE:
2287 case LFUN_BUFFER_EXPORT_CUSTOM:
2288 // FIXME: Nothing to check here?
2291 case LFUN_BUFFER_EXPORT: {
2292 docstring const arg = cmd.argument();
2293 if (arg == "custom") {
2297 string format = to_utf8(arg);
2298 size_t pos = format.find(' ');
2299 if (pos != string::npos)
2300 format = format.substr(0, pos);
2301 enable = params().isExportable(format);
2303 flag.message(bformat(
2304 _("Don't know how to export to format: %1$s"), arg));
2308 case LFUN_BUFFER_CHKTEX:
2309 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2312 case LFUN_BUILD_PROGRAM:
2313 enable = params().isExportable("program");
2316 case LFUN_BRANCH_ACTIVATE:
2317 case LFUN_BRANCH_DEACTIVATE:
2318 case LFUN_BRANCH_MASTER_ACTIVATE:
2319 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2320 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2321 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2322 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2323 : params().branchlist();
2324 docstring const branchName = cmd.argument();
2325 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2329 case LFUN_BRANCH_ADD:
2330 case LFUN_BRANCHES_RENAME:
2331 case LFUN_BUFFER_PRINT:
2332 // if no Buffer is present, then of course we won't be called!
2335 case LFUN_BUFFER_LANGUAGE:
2336 enable = !isReadonly();
2342 flag.setEnabled(enable);
2347 void Buffer::dispatch(string const & command, DispatchResult & result)
2349 return dispatch(lyxaction.lookupFunc(command), result);
2353 // NOTE We can end up here even if we have no GUI, because we are called
2354 // by LyX::exec to handled command-line requests. So we may need to check
2355 // whether we have a GUI or not. The boolean use_gui holds this information.
2356 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2359 // FIXME? if there is an Buffer LFUN that can be dispatched even
2360 // if internal, put a switch '(cmd.action())' here.
2361 dr.dispatched(false);
2364 string const argument = to_utf8(func.argument());
2365 // We'll set this back to false if need be.
2366 bool dispatched = true;
2367 undo().beginUndoGroup();
2369 switch (func.action()) {
2370 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2371 if (lyxvc().inUse()) {
2372 string log = lyxvc().toggleReadOnly();
2377 setReadonly(!isReadonly());
2380 case LFUN_BUFFER_EXPORT: {
2381 ExportStatus const status = doExport(argument, false);
2382 dr.setError(status != ExportSuccess);
2383 if (status != ExportSuccess)
2384 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2389 case LFUN_BUILD_PROGRAM: {
2390 ExportStatus const status = doExport("program", true);
2391 dr.setError(status != ExportSuccess);
2392 if (status != ExportSuccess)
2393 dr.setMessage(_("Error generating literate programming code."));
2397 case LFUN_BUFFER_CHKTEX:
2401 case LFUN_BUFFER_EXPORT_CUSTOM: {
2403 string command = split(argument, format_name, ' ');
2404 Format const * format = formats.getFormat(format_name);
2406 lyxerr << "Format \"" << format_name
2407 << "\" not recognized!"
2412 // The name of the file created by the conversion process
2415 // Output to filename
2416 if (format->name() == "lyx") {
2417 string const latexname = latexName(false);
2418 filename = changeExtension(latexname,
2419 format->extension());
2420 filename = addName(temppath(), filename);
2422 if (!writeFile(FileName(filename)))
2426 doExport(format_name, true, filename);
2429 // Substitute $$FName for filename
2430 if (!contains(command, "$$FName"))
2431 command = "( " + command + " ) < $$FName";
2432 command = subst(command, "$$FName", filename);
2434 // Execute the command in the background
2436 call.startscript(Systemcall::DontWait, command, filePath());
2440 // FIXME: There is need for a command-line import.
2442 case LFUN_BUFFER_IMPORT:
2447 case LFUN_BUFFER_AUTO_SAVE:
2449 resetAutosaveTimers();
2452 case LFUN_BRANCH_ACTIVATE:
2453 case LFUN_BRANCH_DEACTIVATE:
2454 case LFUN_BRANCH_MASTER_ACTIVATE:
2455 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2456 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2457 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2458 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2461 docstring const branch_name = func.argument();
2462 // the case without a branch name is handled elsewhere
2463 if (branch_name.empty()) {
2467 Branch * branch = buf->params().branchlist().find(branch_name);
2469 LYXERR0("Branch " << branch_name << " does not exist.");
2471 docstring const msg =
2472 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2476 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2477 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2478 if (branch->isSelected() != activate) {
2479 buf->undo().recordUndoFullDocument(CursorData());
2480 branch->setSelected(activate);
2482 dr.screenUpdate(Update::Force);
2483 dr.forceBufferUpdate();
2488 case LFUN_BRANCH_ADD: {
2489 docstring branch_name = func.argument();
2490 if (branch_name.empty()) {
2494 BranchList & branch_list = params().branchlist();
2495 vector<docstring> const branches =
2496 getVectorFromString(branch_name, branch_list.separator());
2498 for (vector<docstring>::const_iterator it = branches.begin();
2499 it != branches.end(); ++it) {
2501 Branch * branch = branch_list.find(branch_name);
2503 LYXERR0("Branch " << branch_name << " already exists.");
2507 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2509 undo().recordUndoFullDocument(CursorData());
2510 branch_list.add(branch_name);
2511 branch = branch_list.find(branch_name);
2512 string const x11hexname = X11hexname(branch->color());
2513 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2514 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2516 dr.screenUpdate(Update::Force);
2524 case LFUN_BRANCHES_RENAME: {
2525 if (func.argument().empty())
2528 docstring const oldname = from_utf8(func.getArg(0));
2529 docstring const newname = from_utf8(func.getArg(1));
2530 InsetIterator it = inset_iterator_begin(inset());
2531 InsetIterator const end = inset_iterator_end(inset());
2532 bool success = false;
2533 for (; it != end; ++it) {
2534 if (it->lyxCode() == BRANCH_CODE) {
2535 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2536 if (ins.branch() == oldname) {
2537 undo().recordUndo(CursorData(it));
2538 ins.rename(newname);
2543 if (it->lyxCode() == INCLUDE_CODE) {
2544 // get buffer of external file
2545 InsetInclude const & ins =
2546 static_cast<InsetInclude const &>(*it);
2547 Buffer * child = ins.getChildBuffer();
2550 child->dispatch(func, dr);
2555 dr.screenUpdate(Update::Force);
2556 dr.forceBufferUpdate();
2561 case LFUN_BUFFER_PRINT: {
2562 // we'll assume there's a problem until we succeed
2564 string target = func.getArg(0);
2565 string target_name = func.getArg(1);
2566 string command = func.getArg(2);
2569 || target_name.empty()
2570 || command.empty()) {
2571 LYXERR0("Unable to parse " << func.argument());
2572 docstring const msg =
2573 bformat(_("Unable to parse \"%1$s\""), func.argument());
2577 if (target != "printer" && target != "file") {
2578 LYXERR0("Unrecognized target \"" << target << '"');
2579 docstring const msg =
2580 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2585 if (doExport("dvi", true) != ExportSuccess) {
2586 showPrintError(absFileName());
2587 dr.setMessage(_("Error exporting to DVI."));
2591 // Push directory path.
2592 string const path = temppath();
2593 // Prevent the compiler from optimizing away p
2597 // there are three cases here:
2598 // 1. we print to a file
2599 // 2. we print directly to a printer
2600 // 3. we print using a spool command (print to file first)
2603 string const dviname = changeExtension(latexName(true), "dvi");
2605 if (target == "printer") {
2606 if (!lyxrc.print_spool_command.empty()) {
2607 // case 3: print using a spool
2608 string const psname = changeExtension(dviname,".ps");
2609 command += ' ' + lyxrc.print_to_file
2612 + quoteName(dviname);
2614 string command2 = lyxrc.print_spool_command + ' ';
2615 if (target_name != "default") {
2616 command2 += lyxrc.print_spool_printerprefix
2620 command2 += quoteName(psname);
2622 // If successful, then spool command
2623 res = one.startscript(Systemcall::Wait, command,
2627 // If there's no GUI, we have to wait on this command. Otherwise,
2628 // LyX deletes the temporary directory, and with it the spooled
2629 // file, before it can be printed!!
2630 Systemcall::Starttype stype = use_gui ?
2631 Systemcall::DontWait : Systemcall::Wait;
2632 res = one.startscript(stype, command2,
2636 // case 2: print directly to a printer
2637 if (target_name != "default")
2638 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2640 Systemcall::Starttype stype = use_gui ?
2641 Systemcall::DontWait : Systemcall::Wait;
2642 res = one.startscript(stype, command +
2643 quoteName(dviname), filePath());
2647 // case 1: print to a file
2648 FileName const filename(makeAbsPath(target_name, filePath()));
2649 FileName const dvifile(makeAbsPath(dviname, path));
2650 if (filename.exists()) {
2651 docstring text = bformat(
2652 _("The file %1$s already exists.\n\n"
2653 "Do you want to overwrite that file?"),
2654 makeDisplayPath(filename.absFileName()));
2655 if (Alert::prompt(_("Overwrite file?"),
2656 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2659 command += ' ' + lyxrc.print_to_file
2660 + quoteName(filename.toFilesystemEncoding())
2662 + quoteName(dvifile.toFilesystemEncoding());
2664 Systemcall::Starttype stype = use_gui ?
2665 Systemcall::DontWait : Systemcall::Wait;
2666 res = one.startscript(stype, command, filePath());
2672 dr.setMessage(_("Error running external commands."));
2673 showPrintError(absFileName());
2682 dr.dispatched(dispatched);
2683 undo().endUndoGroup();
2687 void Buffer::changeLanguage(Language const * from, Language const * to)
2689 LASSERT(from, return);
2690 LASSERT(to, return);
2692 for_each(par_iterator_begin(),
2694 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2698 bool Buffer::isMultiLingual() const
2700 ParConstIterator end = par_iterator_end();
2701 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2702 if (it->isMultiLingual(params()))
2709 std::set<Language const *> Buffer::getLanguages() const
2711 std::set<Language const *> languages;
2712 getLanguages(languages);
2717 void Buffer::getLanguages(std::set<Language const *> & languages) const
2719 ParConstIterator end = par_iterator_end();
2720 // add the buffer language, even if it's not actively used
2721 languages.insert(language());
2722 // iterate over the paragraphs
2723 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2724 it->getLanguages(languages);
2726 ListOfBuffers clist = getDescendents();
2727 ListOfBuffers::const_iterator cit = clist.begin();
2728 ListOfBuffers::const_iterator const cen = clist.end();
2729 for (; cit != cen; ++cit)
2730 (*cit)->getLanguages(languages);
2734 DocIterator Buffer::getParFromID(int const id) const
2736 Buffer * buf = const_cast<Buffer *>(this);
2738 // John says this is called with id == -1 from undo
2739 lyxerr << "getParFromID(), id: " << id << endl;
2740 return doc_iterator_end(buf);
2743 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2744 if (it.paragraph().id() == id)
2747 return doc_iterator_end(buf);
2751 bool Buffer::hasParWithID(int const id) const
2753 return !getParFromID(id).atEnd();
2757 ParIterator Buffer::par_iterator_begin()
2759 return ParIterator(doc_iterator_begin(this));
2763 ParIterator Buffer::par_iterator_end()
2765 return ParIterator(doc_iterator_end(this));
2769 ParConstIterator Buffer::par_iterator_begin() const
2771 return ParConstIterator(doc_iterator_begin(this));
2775 ParConstIterator Buffer::par_iterator_end() const
2777 return ParConstIterator(doc_iterator_end(this));
2781 Language const * Buffer::language() const
2783 return params().language;
2787 docstring const Buffer::B_(string const & l10n) const
2789 return params().B_(l10n);
2793 bool Buffer::isClean() const
2795 return d->lyx_clean;
2799 bool Buffer::isExternallyModified(CheckMethod method) const
2801 LASSERT(d->filename.exists(), return false);
2802 // if method == timestamp, check timestamp before checksum
2803 return (method == checksum_method
2804 || d->timestamp_ != d->filename.lastModified())
2805 && d->checksum_ != d->filename.checksum();
2809 void Buffer::saveCheckSum() const
2811 FileName const & file = d->filename;
2814 if (file.exists()) {
2815 d->timestamp_ = file.lastModified();
2816 d->checksum_ = file.checksum();
2818 // in the case of save to a new file.
2825 void Buffer::markClean() const
2827 if (!d->lyx_clean) {
2828 d->lyx_clean = true;
2831 // if the .lyx file has been saved, we don't need an
2833 d->bak_clean = true;
2834 d->undo_.markDirty();
2838 void Buffer::setUnnamed(bool flag)
2844 bool Buffer::isUnnamed() const
2851 /// Don't check unnamed, here: isInternal() is used in
2852 /// newBuffer(), where the unnamed flag has not been set by anyone
2853 /// yet. Also, for an internal buffer, there should be no need for
2854 /// retrieving fileName() nor for checking if it is unnamed or not.
2855 bool Buffer::isInternal() const
2857 return d->internal_buffer;
2861 void Buffer::setInternal(bool flag)
2863 d->internal_buffer = flag;
2867 void Buffer::markDirty()
2870 d->lyx_clean = false;
2873 d->bak_clean = false;
2875 DepClean::iterator it = d->dep_clean.begin();
2876 DepClean::const_iterator const end = d->dep_clean.end();
2878 for (; it != end; ++it)
2883 FileName Buffer::fileName() const
2889 string Buffer::absFileName() const
2891 return d->filename.absFileName();
2895 string Buffer::filePath() const
2897 string const abs = d->filename.onlyPath().absFileName();
2900 int last = abs.length() - 1;
2902 return abs[last] == '/' ? abs : abs + '/';
2906 bool Buffer::isReadonly() const
2908 return d->read_only;
2912 void Buffer::setParent(Buffer const * buffer)
2914 // Avoids recursive include.
2915 d->setParent(buffer == this ? 0 : buffer);
2920 Buffer const * Buffer::parent() const
2926 ListOfBuffers Buffer::allRelatives() const
2928 ListOfBuffers lb = masterBuffer()->getDescendents();
2929 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2934 Buffer const * Buffer::masterBuffer() const
2936 // FIXME Should be make sure we are not in some kind
2937 // of recursive include? A -> B -> A will crash this.
2938 Buffer const * const pbuf = d->parent();
2942 return pbuf->masterBuffer();
2946 bool Buffer::isChild(Buffer * child) const
2948 return d->children_positions.find(child) != d->children_positions.end();
2952 DocIterator Buffer::firstChildPosition(Buffer const * child)
2954 Impl::BufferPositionMap::iterator it;
2955 it = d->children_positions.find(child);
2956 if (it == d->children_positions.end())
2957 return DocIterator(this);
2962 bool Buffer::hasChildren() const
2964 return !d->children_positions.empty();
2968 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2970 // loop over children
2971 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2972 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2973 for (; it != end; ++it) {
2974 Buffer * child = const_cast<Buffer *>(it->first);
2976 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2977 if (bit != clist.end())
2979 clist.push_back(child);
2981 // there might be grandchildren
2982 child->collectChildren(clist, true);
2987 ListOfBuffers Buffer::getChildren() const
2990 collectChildren(v, false);
2991 // Make sure we have not included ourselves.
2992 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2993 if (bit != v.end()) {
2994 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3001 ListOfBuffers Buffer::getDescendents() const
3004 collectChildren(v, true);
3005 // Make sure we have not included ourselves.
3006 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3007 if (bit != v.end()) {
3008 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3015 template<typename M>
3016 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3021 typename M::const_iterator it = m.lower_bound(x);
3022 if (it == m.begin())
3030 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3031 DocIterator const & pos) const
3033 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3035 // if paragraphs have no macro context set, pos will be empty
3039 // we haven't found anything yet
3040 DocIterator bestPos = owner_->par_iterator_begin();
3041 MacroData const * bestData = 0;
3043 // find macro definitions for name
3044 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3045 if (nameIt != macros.end()) {
3046 // find last definition in front of pos or at pos itself
3047 PositionScopeMacroMap::const_iterator it
3048 = greatest_below(nameIt->second, pos);
3049 if (it != nameIt->second.end()) {
3051 // scope ends behind pos?
3052 if (pos < it->second.first) {
3053 // Looks good, remember this. If there
3054 // is no external macro behind this,
3055 // we found the right one already.
3056 bestPos = it->first;
3057 bestData = &it->second.second;
3061 // try previous macro if there is one
3062 if (it == nameIt->second.begin())
3069 // find macros in included files
3070 PositionScopeBufferMap::const_iterator it
3071 = greatest_below(position_to_children, pos);
3072 if (it == position_to_children.end())
3073 // no children before
3077 // do we know something better (i.e. later) already?
3078 if (it->first < bestPos )
3081 // scope ends behind pos?
3082 if (pos < it->second.first
3083 && (cloned_buffer_ ||
3084 theBufferList().isLoaded(it->second.second))) {
3085 // look for macro in external file
3087 MacroData const * data
3088 = it->second.second->getMacro(name, false);
3091 bestPos = it->first;
3097 // try previous file if there is one
3098 if (it == position_to_children.begin())
3103 // return the best macro we have found
3108 MacroData const * Buffer::getMacro(docstring const & name,
3109 DocIterator const & pos, bool global) const
3114 // query buffer macros
3115 MacroData const * data = d->getBufferMacro(name, pos);
3119 // If there is a master buffer, query that
3120 Buffer const * const pbuf = d->parent();
3122 d->macro_lock = true;
3123 MacroData const * macro = pbuf->getMacro(
3124 name, *this, false);
3125 d->macro_lock = false;
3131 data = MacroTable::globalMacros().get(name);
3140 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3142 // set scope end behind the last paragraph
3143 DocIterator scope = par_iterator_begin();
3144 scope.pit() = scope.lastpit() + 1;
3146 return getMacro(name, scope, global);
3150 MacroData const * Buffer::getMacro(docstring const & name,
3151 Buffer const & child, bool global) const
3153 // look where the child buffer is included first
3154 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3155 if (it == d->children_positions.end())
3158 // check for macros at the inclusion position
3159 return getMacro(name, it->second, global);
3163 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3165 pit_type const lastpit = it.lastpit();
3167 // look for macros in each paragraph
3168 while (it.pit() <= lastpit) {
3169 Paragraph & par = it.paragraph();
3171 // iterate over the insets of the current paragraph
3172 InsetList const & insets = par.insetList();
3173 InsetList::const_iterator iit = insets.begin();
3174 InsetList::const_iterator end = insets.end();
3175 for (; iit != end; ++iit) {
3176 it.pos() = iit->pos;
3178 // is it a nested text inset?
3179 if (iit->inset->asInsetText()) {
3180 // Inset needs its own scope?
3181 InsetText const * itext = iit->inset->asInsetText();
3182 bool newScope = itext->isMacroScope();
3184 // scope which ends just behind the inset
3185 DocIterator insetScope = it;
3188 // collect macros in inset
3189 it.push_back(CursorSlice(*iit->inset));
3190 updateMacros(it, newScope ? insetScope : scope);
3195 if (iit->inset->asInsetTabular()) {
3196 CursorSlice slice(*iit->inset);
3197 size_t const numcells = slice.nargs();
3198 for (; slice.idx() < numcells; slice.forwardIdx()) {
3199 it.push_back(slice);
3200 updateMacros(it, scope);
3206 // is it an external file?
3207 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3208 // get buffer of external file
3209 InsetInclude const & inset =
3210 static_cast<InsetInclude const &>(*iit->inset);
3212 Buffer * child = inset.getChildBuffer();
3217 // register its position, but only when it is
3218 // included first in the buffer
3219 if (children_positions.find(child) ==
3220 children_positions.end())
3221 children_positions[child] = it;
3223 // register child with its scope
3224 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3228 InsetMath * im = iit->inset->asInsetMath();
3229 if (doing_export && im) {
3230 InsetMathHull * hull = im->asHullInset();
3232 hull->recordLocation(it);
3235 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3239 MathMacroTemplate & macroTemplate =
3240 *iit->inset->asInsetMath()->asMacroTemplate();
3241 MacroContext mc(owner_, it);
3242 macroTemplate.updateToContext(mc);
3245 bool valid = macroTemplate.validMacro();
3246 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3247 // then the BufferView's cursor will be invalid in
3248 // some cases which leads to crashes.
3253 // FIXME (Abdel), I don't understandt why we pass 'it' here
3254 // instead of 'macroTemplate' defined above... is this correct?
3255 macros[macroTemplate.name()][it] =
3256 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3266 void Buffer::updateMacros() const
3271 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3273 // start with empty table
3275 d->children_positions.clear();
3276 d->position_to_children.clear();
3278 // Iterate over buffer, starting with first paragraph
3279 // The scope must be bigger than any lookup DocIterator
3280 // later. For the global lookup, lastpit+1 is used, hence
3281 // we use lastpit+2 here.
3282 DocIterator it = par_iterator_begin();
3283 DocIterator outerScope = it;
3284 outerScope.pit() = outerScope.lastpit() + 2;
3285 d->updateMacros(it, outerScope);
3289 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3291 InsetIterator it = inset_iterator_begin(inset());
3292 InsetIterator const end = inset_iterator_end(inset());
3293 for (; it != end; ++it) {
3294 if (it->lyxCode() == BRANCH_CODE) {
3295 InsetBranch & br = static_cast<InsetBranch &>(*it);
3296 docstring const name = br.branch();
3297 if (!from_master && !params().branchlist().find(name))
3298 result.push_back(name);
3299 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3300 result.push_back(name);
3303 if (it->lyxCode() == INCLUDE_CODE) {
3304 // get buffer of external file
3305 InsetInclude const & ins =
3306 static_cast<InsetInclude const &>(*it);
3307 Buffer * child = ins.getChildBuffer();
3310 child->getUsedBranches(result, true);
3313 // remove duplicates
3318 void Buffer::updateMacroInstances(UpdateType utype) const
3320 LYXERR(Debug::MACROS, "updateMacroInstances for "
3321 << d->filename.onlyFileName());
3322 DocIterator it = doc_iterator_begin(this);
3324 DocIterator const end = doc_iterator_end(this);
3325 for (; it != end; it.forwardInset()) {
3326 // look for MathData cells in InsetMathNest insets
3327 InsetMath * minset = it.nextInset()->asInsetMath();
3331 // update macro in all cells of the InsetMathNest
3332 DocIterator::idx_type n = minset->nargs();
3333 MacroContext mc = MacroContext(this, it);
3334 for (DocIterator::idx_type i = 0; i < n; ++i) {
3335 MathData & data = minset->cell(i);
3336 data.updateMacros(0, mc, utype);
3342 void Buffer::listMacroNames(MacroNameSet & macros) const
3347 d->macro_lock = true;
3349 // loop over macro names
3350 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3351 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3352 for (; nameIt != nameEnd; ++nameIt)
3353 macros.insert(nameIt->first);
3355 // loop over children
3356 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3357 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3358 for (; it != end; ++it)
3359 it->first->listMacroNames(macros);
3362 Buffer const * const pbuf = d->parent();
3364 pbuf->listMacroNames(macros);
3366 d->macro_lock = false;
3370 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3372 Buffer const * const pbuf = d->parent();
3377 pbuf->listMacroNames(names);
3380 MacroNameSet::iterator it = names.begin();
3381 MacroNameSet::iterator end = names.end();
3382 for (; it != end; ++it) {
3384 MacroData const * data =
3385 pbuf->getMacro(*it, *this, false);
3387 macros.insert(data);
3389 // we cannot access the original MathMacroTemplate anymore
3390 // here to calls validate method. So we do its work here manually.
3391 // FIXME: somehow make the template accessible here.
3392 if (data->optionals() > 0)
3393 features.require("xargs");
3399 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3402 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3404 RefCache::iterator it = d->ref_cache_.find(label);
3405 if (it != d->ref_cache_.end())
3406 return it->second.second;
3408 static InsetLabel const * dummy_il = 0;
3409 static References const dummy_refs;
3410 it = d->ref_cache_.insert(
3411 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3412 return it->second.second;
3416 Buffer::References const & Buffer::references(docstring const & label) const
3418 return const_cast<Buffer *>(this)->getReferenceCache(label);
3422 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3424 References & refs = getReferenceCache(label);
3425 refs.push_back(make_pair(inset, it));
3429 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3431 masterBuffer()->d->ref_cache_[label].first = il;
3435 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3437 return masterBuffer()->d->ref_cache_[label].first;
3441 void Buffer::clearReferenceCache() const
3444 d->ref_cache_.clear();
3448 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3450 //FIXME: This does not work for child documents yet.
3451 reloadBibInfoCache();
3453 // Check if the label 'from' appears more than once
3454 BiblioInfo const & keys = masterBibInfo();
3455 BiblioInfo::const_iterator bit = keys.begin();
3456 BiblioInfo::const_iterator bend = keys.end();
3457 vector<docstring> labels;
3459 for (; bit != bend; ++bit)
3461 labels.push_back(bit->first);
3463 if (count(labels.begin(), labels.end(), from) > 1)
3466 string const paramName = "key";
3467 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3468 if (it->lyxCode() != CITE_CODE)
3470 InsetCommand * inset = it->asInsetCommand();
3471 docstring const oldValue = inset->getParam(paramName);
3472 if (oldValue == from)
3473 inset->setParam(paramName, to);
3478 void Buffer::getSourceCode(odocstream & os, string const format,
3479 pit_type par_begin, pit_type par_end,
3480 OutputWhat output, bool master) const
3482 OutputParams runparams(¶ms().encoding());
3483 runparams.nice = true;
3484 runparams.flavor = params().getOutputFlavor(format);
3485 runparams.linelen = lyxrc.plaintext_linelen;
3486 // No side effect of file copying and image conversion
3487 runparams.dryrun = true;
3489 if (output == CurrentParagraph) {
3490 runparams.par_begin = par_begin;
3491 runparams.par_end = par_end;
3492 if (par_begin + 1 == par_end) {
3494 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3498 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3499 convert<docstring>(par_begin),
3500 convert<docstring>(par_end - 1))
3503 // output paragraphs
3504 if (runparams.flavor == OutputParams::LYX) {
3505 Paragraph const & par = text().paragraphs()[par_begin];
3507 depth_type dt = par.getDepth();
3508 par.write(ods, params(), dt);
3509 os << from_utf8(ods.str());
3510 } else if (runparams.flavor == OutputParams::HTML) {
3512 setMathFlavor(runparams);
3513 xhtmlParagraphs(text(), *this, xs, runparams);
3514 } else if (runparams.flavor == OutputParams::TEXT) {
3516 // FIXME Handles only one paragraph, unlike the others.
3517 // Probably should have some routine with a signature like them.
3518 writePlaintextParagraph(*this,
3519 text().paragraphs()[par_begin], os, runparams, dummy);
3520 } else if (params().isDocBook()) {
3521 docbookParagraphs(text(), *this, os, runparams);
3523 // If we are previewing a paragraph, even if this is the
3524 // child of some other buffer, let's cut the link here,
3525 // so that no concurring settings from the master
3526 // (e.g. branch state) interfere (see #8101).
3528 d->ignore_parent = true;
3529 // We need to validate the Buffer params' features here
3530 // in order to know if we should output polyglossia
3531 // macros (instead of babel macros)
3532 LaTeXFeatures features(*this, params(), runparams);
3533 params().validate(features);
3534 runparams.use_polyglossia = features.usePolyglossia();
3539 // latex or literate
3540 otexstream ots(os, texrow);
3543 latexParagraphs(*this, text(), ots, runparams);
3545 // Restore the parenthood
3547 d->ignore_parent = false;
3551 if (output == FullSource)
3552 os << _("Preview source code");
3553 else if (output == OnlyPreamble)
3554 os << _("Preview preamble");
3555 else if (output == OnlyBody)
3556 os << _("Preview body");
3558 if (runparams.flavor == OutputParams::LYX) {
3560 if (output == FullSource)
3562 else if (output == OnlyPreamble)
3563 params().writeFile(ods);
3564 else if (output == OnlyBody)
3566 os << from_utf8(ods.str());
3567 } else if (runparams.flavor == OutputParams::HTML) {
3568 writeLyXHTMLSource(os, runparams, output);
3569 } else if (runparams.flavor == OutputParams::TEXT) {
3570 if (output == OnlyPreamble) {
3571 os << "% "<< _("Plain text does not have a preamble.");
3573 writePlaintextFile(*this, os, runparams);
3574 } else if (params().isDocBook()) {
3575 writeDocBookSource(os, absFileName(), runparams, output);
3577 // latex or literate
3579 d->texrow.newline();
3580 d->texrow.newline();
3581 otexstream ots(os, d->texrow);
3583 runparams.is_child = true;
3584 writeLaTeXSource(ots, string(), runparams, output);
3590 ErrorList & Buffer::errorList(string const & type) const
3592 return d->errorLists[type];
3596 void Buffer::updateTocItem(std::string const & type,
3597 DocIterator const & dit) const
3600 d->gui_->updateTocItem(type, dit);
3604 void Buffer::structureChanged() const
3607 d->gui_->structureChanged();
3611 void Buffer::errors(string const & err, bool from_master) const
3614 d->gui_->errors(err, from_master);
3618 void Buffer::message(docstring const & msg) const
3621 d->gui_->message(msg);
3625 void Buffer::setBusy(bool on) const
3628 d->gui_->setBusy(on);
3632 void Buffer::updateTitles() const
3635 d->wa_->updateTitles();
3639 void Buffer::resetAutosaveTimers() const
3642 d->gui_->resetAutosaveTimers();
3646 bool Buffer::hasGuiDelegate() const
3652 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3661 class AutoSaveBuffer : public ForkedProcess {
3664 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3665 : buffer_(buffer), fname_(fname) {}
3667 virtual shared_ptr<ForkedProcess> clone() const
3669 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3674 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3675 from_utf8(fname_.absFileName())));
3676 return run(DontWait);
3680 virtual int generateChild();
3682 Buffer const & buffer_;
3687 int AutoSaveBuffer::generateChild()
3689 #if defined(__APPLE__)
3690 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3691 * We should use something else like threads.
3693 * Since I do not know how to determine at run time what is the OS X
3694 * version, I just disable forking altogether for now (JMarc)
3696 pid_t const pid = -1;
3698 // tmp_ret will be located (usually) in /tmp
3699 // will that be a problem?
3700 // Note that this calls ForkedCalls::fork(), so it's
3701 // ok cross-platform.
3702 pid_t const pid = fork();
3703 // If you want to debug the autosave
3704 // you should set pid to -1, and comment out the fork.
3705 if (pid != 0 && pid != -1)
3709 // pid = -1 signifies that lyx was unable
3710 // to fork. But we will do the save
3712 bool failed = false;
3713 FileName const tmp_ret = FileName::tempName("lyxauto");
3714 if (!tmp_ret.empty()) {
3715 buffer_.writeFile(tmp_ret);
3716 // assume successful write of tmp_ret
3717 if (!tmp_ret.moveTo(fname_))
3723 // failed to write/rename tmp_ret so try writing direct
3724 if (!buffer_.writeFile(fname_)) {
3725 // It is dangerous to do this in the child,
3726 // but safe in the parent, so...
3727 if (pid == -1) // emit message signal.
3728 buffer_.message(_("Autosave failed!"));
3732 if (pid == 0) // we are the child so...
3741 FileName Buffer::getEmergencyFileName() const
3743 return FileName(d->filename.absFileName() + ".emergency");
3747 FileName Buffer::getAutosaveFileName() const
3749 // if the document is unnamed try to save in the backup dir, else
3750 // in the default document path, and as a last try in the filePath,
3751 // which will most often be the temporary directory
3754 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3755 : lyxrc.backupdir_path;
3756 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3759 string const fname = "#" + d->filename.onlyFileName() + "#";
3761 return makeAbsPath(fname, fpath);
3765 void Buffer::removeAutosaveFile() const
3767 FileName const f = getAutosaveFileName();
3773 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3775 FileName const newauto = getAutosaveFileName();
3777 if (newauto != oldauto && oldauto.exists())
3778 if (!oldauto.moveTo(newauto))
3779 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3783 bool Buffer::autoSave() const
3785 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3786 if (buf->d->bak_clean || isReadonly())
3789 message(_("Autosaving current document..."));
3790 buf->d->bak_clean = true;
3792 FileName const fname = getAutosaveFileName();
3793 LASSERT(d->cloned_buffer_, return false);
3795 // If this buffer is cloned, we assume that
3796 // we are running in a separate thread already.
3797 FileName const tmp_ret = FileName::tempName("lyxauto");
3798 if (!tmp_ret.empty()) {
3800 // assume successful write of tmp_ret
3801 if (tmp_ret.moveTo(fname))
3804 // failed to write/rename tmp_ret so try writing direct
3805 return writeFile(fname);
3809 void Buffer::setExportStatus(bool e) const
3811 d->doing_export = e;
3812 ListOfBuffers clist = getDescendents();
3813 ListOfBuffers::const_iterator cit = clist.begin();
3814 ListOfBuffers::const_iterator const cen = clist.end();
3815 for (; cit != cen; ++cit)
3816 (*cit)->d->doing_export = e;
3820 bool Buffer::isExporting() const
3822 return d->doing_export;
3826 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3830 return doExport(target, put_in_tempdir, result_file);
3833 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3834 string & result_file) const
3836 bool const update_unincluded =
3837 params().maintain_unincluded_children
3838 && !params().getIncludedChildren().empty();
3840 // (1) export with all included children (omit \includeonly)
3841 if (update_unincluded) {
3842 ExportStatus const status =
3843 doExport(target, put_in_tempdir, true, result_file);
3844 if (status != ExportSuccess)
3847 // (2) export with included children only
3848 return doExport(target, put_in_tempdir, false, result_file);
3852 void Buffer::setMathFlavor(OutputParams & op) const
3854 switch (params().html_math_output) {
3855 case BufferParams::MathML:
3856 op.math_flavor = OutputParams::MathAsMathML;
3858 case BufferParams::HTML:
3859 op.math_flavor = OutputParams::MathAsHTML;
3861 case BufferParams::Images:
3862 op.math_flavor = OutputParams::MathAsImages;
3864 case BufferParams::LaTeX:
3865 op.math_flavor = OutputParams::MathAsLaTeX;
3871 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3872 bool includeall, string & result_file) const
3874 LYXERR(Debug::FILES, "target=" << target);
3875 OutputParams runparams(¶ms().encoding());
3876 string format = target;
3877 string dest_filename;
3878 size_t pos = target.find(' ');
3879 if (pos != string::npos) {
3880 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3881 format = target.substr(0, pos);
3882 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3883 FileName(dest_filename).onlyPath().createPath();
3884 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3886 MarkAsExporting exporting(this);
3887 string backend_format;
3888 runparams.flavor = OutputParams::LATEX;
3889 runparams.linelen = lyxrc.plaintext_linelen;
3890 runparams.includeall = includeall;
3891 vector<string> backs = params().backends();
3892 Converters converters = theConverters();
3893 bool need_nice_file = false;
3894 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3895 // Get shortest path to format
3896 converters.buildGraph();
3897 Graph::EdgePath path;
3898 for (vector<string>::const_iterator it = backs.begin();
3899 it != backs.end(); ++it) {
3900 Graph::EdgePath p = converters.getPath(*it, format);
3901 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3902 backend_format = *it;
3907 if (!put_in_tempdir) {
3908 // Only show this alert if this is an export to a non-temporary
3909 // file (not for previewing).
3910 Alert::error(_("Couldn't export file"), bformat(
3911 _("No information for exporting the format %1$s."),
3912 formats.prettyName(format)));
3914 return ExportNoPathToFormat;
3916 runparams.flavor = converters.getFlavor(path, this);
3917 Graph::EdgePath::const_iterator it = path.begin();
3918 Graph::EdgePath::const_iterator en = path.end();
3919 for (; it != en; ++it)
3920 if (theConverters().get(*it).nice) {
3921 need_nice_file = true;
3926 backend_format = format;
3927 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3928 // FIXME: Don't hardcode format names here, but use a flag
3929 if (backend_format == "pdflatex")
3930 runparams.flavor = OutputParams::PDFLATEX;
3931 else if (backend_format == "luatex")
3932 runparams.flavor = OutputParams::LUATEX;
3933 else if (backend_format == "dviluatex")
3934 runparams.flavor = OutputParams::DVILUATEX;
3935 else if (backend_format == "xetex")
3936 runparams.flavor = OutputParams::XETEX;
3939 string filename = latexName(false);
3940 filename = addName(temppath(), filename);
3941 filename = changeExtension(filename,
3942 formats.extension(backend_format));
3943 LYXERR(Debug::FILES, "filename=" << filename);
3945 // Plain text backend
3946 if (backend_format == "text") {
3947 runparams.flavor = OutputParams::TEXT;
3948 writePlaintextFile(*this, FileName(filename), runparams);
3951 else if (backend_format == "xhtml") {
3952 runparams.flavor = OutputParams::HTML;
3953 setMathFlavor(runparams);
3954 makeLyXHTMLFile(FileName(filename), runparams);
3955 } else if (backend_format == "lyx")
3956 writeFile(FileName(filename));
3958 else if (params().isDocBook()) {
3959 runparams.nice = !put_in_tempdir;
3960 makeDocBookFile(FileName(filename), runparams);
3963 else if (backend_format == format || need_nice_file) {
3964 runparams.nice = true;
3965 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3966 if (d->cloned_buffer_)
3967 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3970 } else if (!lyxrc.tex_allows_spaces
3971 && contains(filePath(), ' ')) {
3972 Alert::error(_("File name error"),
3973 _("The directory path to the document cannot contain spaces."));
3974 return ExportTexPathHasSpaces;
3976 runparams.nice = false;
3977 bool const success = makeLaTeXFile(
3978 FileName(filename), filePath(), runparams);
3979 if (d->cloned_buffer_)
3980 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3985 string const error_type = (format == "program")
3986 ? "Build" : params().bufferFormat();
3987 ErrorList & error_list = d->errorLists[error_type];
3988 string const ext = formats.extension(format);
3989 FileName const tmp_result_file(changeExtension(filename, ext));
3990 bool const success = converters.convert(this, FileName(filename),
3991 tmp_result_file, FileName(absFileName()), backend_format, format,
3994 // Emit the signal to show the error list or copy it back to the
3995 // cloned Buffer so that it can be emitted afterwards.
3996 if (format != backend_format) {
3997 if (runparams.silent)
3999 else if (d->cloned_buffer_)
4000 d->cloned_buffer_->d->errorLists[error_type] =
4001 d->errorLists[error_type];
4004 // also to the children, in case of master-buffer-view
4005 ListOfBuffers clist = getDescendents();
4006 ListOfBuffers::const_iterator cit = clist.begin();
4007 ListOfBuffers::const_iterator const cen = clist.end();
4008 for (; cit != cen; ++cit) {
4009 if (runparams.silent)
4010 (*cit)->d->errorLists[error_type].clear();
4011 else if (d->cloned_buffer_) {
4012 // Enable reverse search by copying back the
4013 // texrow object to the cloned buffer.
4014 // FIXME: this is not thread safe.
4015 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4016 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4017 (*cit)->d->errorLists[error_type];
4019 (*cit)->errors(error_type, true);
4023 if (d->cloned_buffer_) {
4024 // Enable reverse dvi or pdf to work by copying back the texrow
4025 // object to the cloned buffer.
4026 // FIXME: There is a possibility of concurrent access to texrow
4027 // here from the main GUI thread that should be securized.
4028 d->cloned_buffer_->d->texrow = d->texrow;
4029 string const error_type = params().bufferFormat();
4030 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4034 return ExportConverterError;
4036 if (put_in_tempdir) {
4037 result_file = tmp_result_file.absFileName();
4038 return ExportSuccess;
4041 if (dest_filename.empty())
4042 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4044 result_file = dest_filename;
4045 // We need to copy referenced files (e. g. included graphics
4046 // if format == "dvi") to the result dir.
4047 vector<ExportedFile> const files =
4048 runparams.exportdata->externalFiles(format);
4049 string const dest = runparams.export_folder.empty() ?
4050 onlyPath(result_file) : runparams.export_folder;
4051 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4052 : force_overwrite == ALL_FILES;
4053 CopyStatus status = use_force ? FORCE : SUCCESS;
4055 vector<ExportedFile>::const_iterator it = files.begin();
4056 vector<ExportedFile>::const_iterator const en = files.end();
4057 for (; it != en && status != CANCEL; ++it) {
4058 string const fmt = formats.getFormatFromFile(it->sourceName);
4059 string fixedName = it->exportName;
4060 if (!runparams.export_folder.empty()) {
4061 // Relative pathnames starting with ../ will be sanitized
4062 // if exporting to a different folder
4063 while (fixedName.substr(0, 3) == "../")
4064 fixedName = fixedName.substr(3, fixedName.length() - 3);
4066 FileName fixedFileName = makeAbsPath(fixedName, dest);
4067 fixedFileName.onlyPath().createPath();
4068 status = copyFile(fmt, it->sourceName,
4070 it->exportName, status == FORCE,
4071 runparams.export_folder.empty());
4074 if (status == CANCEL) {
4075 message(_("Document export cancelled."));
4076 return ExportCancel;
4079 if (tmp_result_file.exists()) {
4080 // Finally copy the main file
4081 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4082 : force_overwrite != NO_FILES;
4083 if (status == SUCCESS && use_force)
4085 status = copyFile(format, tmp_result_file,
4086 FileName(result_file), result_file,
4088 if (status == CANCEL) {
4089 message(_("Document export cancelled."));
4090 return ExportCancel;
4092 message(bformat(_("Document exported as %1$s "
4094 formats.prettyName(format),
4095 makeDisplayPath(result_file)));
4098 // This must be a dummy converter like fax (bug 1888)
4099 message(bformat(_("Document exported as %1$s"),
4100 formats.prettyName(format)));
4103 return ExportSuccess;
4107 Buffer::ExportStatus Buffer::preview(string const & format) const
4109 bool const update_unincluded =
4110 params().maintain_unincluded_children
4111 && !params().getIncludedChildren().empty();
4112 return preview(format, update_unincluded);
4115 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4117 MarkAsExporting exporting(this);
4119 // (1) export with all included children (omit \includeonly)
4121 ExportStatus const status = doExport(format, true, true, result_file);
4122 if (status != ExportSuccess)
4125 // (2) export with included children only
4126 ExportStatus const status = doExport(format, true, false, result_file);
4127 if (status != ExportSuccess)
4129 if (!formats.view(*this, FileName(result_file), format))
4130 return PreviewError;
4131 return PreviewSuccess;
4135 Buffer::ReadStatus Buffer::extractFromVC()
4137 bool const found = LyXVC::file_not_found_hook(d->filename);
4139 return ReadFileNotFound;
4140 if (!d->filename.isReadableFile())
4146 Buffer::ReadStatus Buffer::loadEmergency()
4148 FileName const emergencyFile = getEmergencyFileName();
4149 if (!emergencyFile.exists()
4150 || emergencyFile.lastModified() <= d->filename.lastModified())
4151 return ReadFileNotFound;
4153 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4154 docstring const text = bformat(_("An emergency save of the document "
4155 "%1$s exists.\n\nRecover emergency save?"), file);
4157 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4158 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4164 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4165 bool const success = (ret_llf == ReadSuccess);
4168 Alert::warning(_("File is read-only"),
4169 bformat(_("An emergency file is successfully loaded, "
4170 "but the original file %1$s is marked read-only. "
4171 "Please make sure to save the document as a different "
4172 "file."), from_utf8(d->filename.absFileName())));
4175 lyxvc().file_found_hook(d->filename);
4176 str = _("Document was successfully recovered.");
4178 str = _("Document was NOT successfully recovered.");
4179 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4180 makeDisplayPath(emergencyFile.absFileName()));
4182 int const del_emerg =
4183 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4184 _("&Remove"), _("&Keep"));
4185 if (del_emerg == 0) {
4186 emergencyFile.removeFile();
4188 Alert::warning(_("Emergency file deleted"),
4189 _("Do not forget to save your file now!"), true);
4191 return success ? ReadSuccess : ReadEmergencyFailure;
4194 int const del_emerg =
4195 Alert::prompt(_("Delete emergency file?"),
4196 _("Remove emergency file now?"), 1, 1,
4197 _("&Remove"), _("&Keep"));
4199 emergencyFile.removeFile();
4200 return ReadOriginal;
4210 Buffer::ReadStatus Buffer::loadAutosave()
4212 // Now check if autosave file is newer.
4213 FileName const autosaveFile = getAutosaveFileName();
4214 if (!autosaveFile.exists()
4215 || autosaveFile.lastModified() <= d->filename.lastModified())
4216 return ReadFileNotFound;
4218 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4219 docstring const text = bformat(_("The backup of the document %1$s "
4220 "is newer.\n\nLoad the backup instead?"), file);
4221 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4222 _("&Load backup"), _("Load &original"), _("&Cancel"));
4227 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4228 // the file is not saved if we load the autosave file.
4229 if (ret_llf == ReadSuccess) {
4231 Alert::warning(_("File is read-only"),
4232 bformat(_("A backup file is successfully loaded, "
4233 "but the original file %1$s is marked read-only. "
4234 "Please make sure to save the document as a "
4236 from_utf8(d->filename.absFileName())));
4239 lyxvc().file_found_hook(d->filename);
4242 return ReadAutosaveFailure;
4245 // Here we delete the autosave
4246 autosaveFile.removeFile();
4247 return ReadOriginal;
4255 Buffer::ReadStatus Buffer::loadLyXFile()
4257 if (!d->filename.isReadableFile()) {
4258 ReadStatus const ret_rvc = extractFromVC();
4259 if (ret_rvc != ReadSuccess)
4263 ReadStatus const ret_re = loadEmergency();
4264 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4267 ReadStatus const ret_ra = loadAutosave();
4268 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4271 return loadThisLyXFile(d->filename);
4275 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4277 return readFile(fn);
4281 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4283 TeXErrors::Errors::const_iterator it = terr.begin();
4284 TeXErrors::Errors::const_iterator end = terr.end();
4285 ListOfBuffers clist = getDescendents();
4286 ListOfBuffers::const_iterator cen = clist.end();
4288 for (; it != end; ++it) {
4291 int errorRow = it->error_in_line;
4292 Buffer const * buf = 0;
4294 if (it->child_name.empty())
4295 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4297 // The error occurred in a child
4298 ListOfBuffers::const_iterator cit = clist.begin();
4299 for (; cit != cen; ++cit) {
4300 string const child_name =
4301 DocFileName(changeExtension(
4302 (*cit)->absFileName(), "tex")).
4304 if (it->child_name != child_name)
4306 (*cit)->d->texrow.getIdFromRow(errorRow,
4307 id_start, pos_start);
4308 if (id_start != -1) {
4309 buf = d->cloned_buffer_
4310 ? (*cit)->d->cloned_buffer_->d->owner_
4311 : (*cit)->d->owner_;
4322 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4323 } while (found && id_start == id_end && pos_start == pos_end);
4325 if (id_start != id_end) {
4326 // Next registered position is outside the inset where
4327 // the error occurred, so signal end-of-paragraph
4331 errorList.push_back(ErrorItem(it->error_desc,
4332 it->error_text, id_start, pos_start, pos_end, buf));
4337 void Buffer::setBuffersForInsets() const
4339 inset().setBuffer(const_cast<Buffer &>(*this));
4343 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4345 LBUFERR(!text().paragraphs().empty());
4347 // Use the master text class also for child documents
4348 Buffer const * const master = masterBuffer();
4349 DocumentClass const & textclass = master->params().documentClass();
4351 // do this only if we are the top-level Buffer
4352 if (master == this) {
4353 textclass.counters().reset(from_ascii("bibitem"));
4354 reloadBibInfoCache();
4357 // keep the buffers to be children in this set. If the call from the
4358 // master comes back we can see which of them were actually seen (i.e.
4359 // via an InsetInclude). The remaining ones in the set need still be updated.
4360 static std::set<Buffer const *> bufToUpdate;
4361 if (scope == UpdateMaster) {
4362 // If this is a child document start with the master
4363 if (master != this) {
4364 bufToUpdate.insert(this);
4365 master->updateBuffer(UpdateMaster, utype);
4366 // If the master buffer has no gui associated with it, then the TocModel is
4367 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4368 // (bug 5699). The same happens if the master buffer is open in a different
4369 // window. This test catches both possibilities.
4370 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4371 // There remains a problem here: If there is another child open in yet a third
4372 // window, that TOC is not updated. So some more general solution is needed at
4374 if (master->d->gui_ != d->gui_)
4377 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4378 if (bufToUpdate.find(this) == bufToUpdate.end())
4382 // start over the counters in the master
4383 textclass.counters().reset();
4386 // update will be done below for this buffer
4387 bufToUpdate.erase(this);
4389 // update all caches
4390 clearReferenceCache();
4393 Buffer & cbuf = const_cast<Buffer &>(*this);
4396 ParIterator parit = cbuf.par_iterator_begin();
4397 updateBuffer(parit, utype);
4400 // TocBackend update will be done later.
4403 d->bibinfo_cache_valid_ = true;
4404 d->cite_labels_valid_ = true;
4405 cbuf.tocBackend().update(utype == OutputUpdate);
4406 if (scope == UpdateMaster)
4407 cbuf.structureChanged();
4411 static depth_type getDepth(DocIterator const & it)
4413 depth_type depth = 0;
4414 for (size_t i = 0 ; i < it.depth() ; ++i)
4415 if (!it[i].inset().inMathed())
4416 depth += it[i].paragraph().getDepth() + 1;
4417 // remove 1 since the outer inset does not count
4421 static depth_type getItemDepth(ParIterator const & it)
4423 Paragraph const & par = *it;
4424 LabelType const labeltype = par.layout().labeltype;
4426 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4429 // this will hold the lowest depth encountered up to now.
4430 depth_type min_depth = getDepth(it);
4431 ParIterator prev_it = it;
4434 --prev_it.top().pit();
4436 // start of nested inset: go to outer par
4438 if (prev_it.empty()) {
4439 // start of document: nothing to do
4444 // We search for the first paragraph with same label
4445 // that is not more deeply nested.
4446 Paragraph & prev_par = *prev_it;
4447 depth_type const prev_depth = getDepth(prev_it);
4448 if (labeltype == prev_par.layout().labeltype) {
4449 if (prev_depth < min_depth)
4450 return prev_par.itemdepth + 1;
4451 if (prev_depth == min_depth)
4452 return prev_par.itemdepth;
4454 min_depth = min(min_depth, prev_depth);
4455 // small optimization: if we are at depth 0, we won't
4456 // find anything else
4457 if (prev_depth == 0)
4463 static bool needEnumCounterReset(ParIterator const & it)
4465 Paragraph const & par = *it;
4466 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4467 depth_type const cur_depth = par.getDepth();
4468 ParIterator prev_it = it;
4469 while (prev_it.pit()) {
4470 --prev_it.top().pit();
4471 Paragraph const & prev_par = *prev_it;
4472 if (prev_par.getDepth() <= cur_depth)
4473 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4475 // start of nested inset: reset
4480 // set the label of a paragraph. This includes the counters.
4481 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4483 BufferParams const & bp = owner_->masterBuffer()->params();
4484 DocumentClass const & textclass = bp.documentClass();
4485 Paragraph & par = it.paragraph();
4486 Layout const & layout = par.layout();
4487 Counters & counters = textclass.counters();
4489 if (par.params().startOfAppendix()) {
4490 // We want to reset the counter corresponding to toplevel sectioning
4491 Layout const & lay = textclass.getTOCLayout();
4492 docstring const cnt = lay.counter;
4494 counters.reset(cnt);
4495 counters.appendix(true);
4497 par.params().appendix(counters.appendix());
4499 // Compute the item depth of the paragraph
4500 par.itemdepth = getItemDepth(it);
4502 if (layout.margintype == MARGIN_MANUAL) {
4503 if (par.params().labelWidthString().empty())
4504 par.params().labelWidthString(par.expandLabel(layout, bp));
4505 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4506 // we do not need to do anything here, since the empty case is
4507 // handled during export.
4509 par.params().labelWidthString(docstring());
4512 switch(layout.labeltype) {
4513 case LABEL_ITEMIZE: {
4514 // At some point of time we should do something more
4515 // clever here, like:
4516 // par.params().labelString(
4517 // bp.user_defined_bullet(par.itemdepth).getText());
4518 // for now, use a simple hardcoded label
4519 docstring itemlabel;
4520 switch (par.itemdepth) {
4522 itemlabel = char_type(0x2022);
4525 itemlabel = char_type(0x2013);
4528 itemlabel = char_type(0x2217);
4531 itemlabel = char_type(0x2219); // or 0x00b7
4534 par.params().labelString(itemlabel);
4538 case LABEL_ENUMERATE: {
4539 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4541 switch (par.itemdepth) {
4550 enumcounter += "iv";
4553 // not a valid enumdepth...
4557 // Maybe we have to reset the enumeration counter.
4558 if (needEnumCounterReset(it))
4559 counters.reset(enumcounter);
4560 counters.step(enumcounter, utype);
4562 string const & lang = par.getParLanguage(bp)->code();
4563 par.params().labelString(counters.theCounter(enumcounter, lang));
4568 case LABEL_SENSITIVE: {
4569 string const & type = counters.current_float();
4570 docstring full_label;
4572 full_label = owner_->B_("Senseless!!! ");
4574 docstring name = owner_->B_(textclass.floats().getType(type).name());
4575 if (counters.hasCounter(from_utf8(type))) {
4576 string const & lang = par.getParLanguage(bp)->code();
4577 counters.step(from_utf8(type), utype);
4578 full_label = bformat(from_ascii("%1$s %2$s:"),
4580 counters.theCounter(from_utf8(type), lang));
4582 full_label = bformat(from_ascii("%1$s #:"), name);
4584 par.params().labelString(full_label);
4588 case LABEL_NO_LABEL:
4589 par.params().labelString(docstring());
4593 case LABEL_CENTERED:
4594 case LABEL_STATIC: {
4595 docstring const & lcounter = layout.counter;
4596 if (!lcounter.empty()) {
4597 if (layout.toclevel <= bp.secnumdepth
4598 && (layout.latextype != LATEX_ENVIRONMENT
4599 || it.text()->isFirstInSequence(it.pit()))) {
4600 if (counters.hasCounter(lcounter))
4601 counters.step(lcounter, utype);
4602 par.params().labelString(par.expandLabel(layout, bp));
4604 par.params().labelString(docstring());
4606 par.params().labelString(par.expandLabel(layout, bp));
4612 par.params().labelString(par.expandLabel(layout, bp));
4617 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4619 // LASSERT: Is it safe to continue here, or should we just return?
4620 LASSERT(parit.pit() == 0, /**/);
4622 // Set the position of the text in the buffer to be able
4623 // to resolve macros in it.
4624 parit.text()->setMacrocontextPosition(parit);
4626 depth_type maxdepth = 0;
4627 pit_type const lastpit = parit.lastpit();
4628 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4629 // reduce depth if necessary
4630 if (parit->params().depth() > maxdepth) {
4631 /** FIXME: this function is const, but
4632 * nevertheless it modifies the buffer. To be
4633 * cleaner, one should modify the buffer in
4634 * another function, which is actually
4635 * non-const. This would however be costly in
4636 * terms of code duplication.
4638 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4639 parit->params().depth(maxdepth);
4641 maxdepth = parit->getMaxDepthAfter();
4643 if (utype == OutputUpdate) {
4644 // track the active counters
4645 // we have to do this for the master buffer, since the local
4646 // buffer isn't tracking anything.
4647 masterBuffer()->params().documentClass().counters().
4648 setActiveLayout(parit->layout());
4651 // set the counter for this paragraph
4652 d->setLabel(parit, utype);
4655 InsetList::const_iterator iit = parit->insetList().begin();
4656 InsetList::const_iterator end = parit->insetList().end();
4657 for (; iit != end; ++iit) {
4658 parit.pos() = iit->pos;
4659 iit->inset->updateBuffer(parit, utype);
4665 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4666 WordLangTuple & word_lang, docstring_list & suggestions) const
4670 suggestions.clear();
4671 word_lang = WordLangTuple();
4672 bool const to_end = to.empty();
4673 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4674 // OK, we start from here.
4675 for (; from != end; from.forwardPos()) {
4676 // We are only interested in text so remove the math CursorSlice.
4677 while (from.inMathed()) {
4681 // If from is at the end of the document (which is possible
4682 // when leaving the mathed) LyX will crash later otherwise.
4683 if (from.atEnd() || (!to_end && from >= end))
4686 from.paragraph().spellCheck();
4687 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4688 if (SpellChecker::misspelled(res)) {
4693 // Do not increase progress when from == to, otherwise the word
4694 // count will be wrong.
4704 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4706 bool inword = false;
4711 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4712 if (!dit.inTexted()) {
4717 Paragraph const & par = dit.paragraph();
4718 pos_type const pos = dit.pos();
4720 // Copied and adapted from isWordSeparator() in Paragraph
4721 if (pos == dit.lastpos()) {
4724 Inset const * ins = par.getInset(pos);
4725 if (ins && skipNoOutput && !ins->producesOutput()) {
4728 // stop if end of range was skipped
4729 if (!to.atEnd() && dit >= to)
4732 } else if (!par.isDeleted(pos)) {
4733 if (par.isWordSeparator(pos))
4739 if (ins && ins->isLetter())
4741 else if (ins && ins->isSpace())
4744 char_type const c = par.getChar(pos);
4745 if (isPrintableNonspace(c))
4747 else if (isSpace(c))
4757 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4759 d->updateStatistics(from, to, skipNoOutput);
4763 int Buffer::wordCount() const
4765 return d->wordCount();
4769 int Buffer::charCount(bool with_blanks) const
4771 return d->charCount(with_blanks);
4775 Buffer::ReadStatus Buffer::reload()
4778 // c.f. bug http://www.lyx.org/trac/ticket/6587
4779 removeAutosaveFile();
4780 // e.g., read-only status could have changed due to version control
4781 d->filename.refresh();
4782 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4784 // clear parent. this will get reset if need be.
4786 ReadStatus const status = loadLyXFile();
4787 if (status == ReadSuccess) {
4792 message(bformat(_("Document %1$s reloaded."), disp_fn));
4795 message(bformat(_("Could not reload document %1$s."), disp_fn));
4805 bool Buffer::saveAs(FileName const & fn)
4807 FileName const old_name = fileName();
4808 FileName const old_auto = getAutosaveFileName();
4809 bool const old_unnamed = isUnnamed();
4816 // bring the autosave file with us, just in case.
4817 moveAutosaveFile(old_auto);
4818 // validate version control data and
4819 // correct buffer title
4820 lyxvc().file_found_hook(fileName());
4822 // the file has now been saved to the new location.
4823 // we need to check that the locations of child buffers
4825 checkChildBuffers();
4826 checkMasterBuffer();
4830 // reset the old filename and unnamed state
4831 setFileName(old_name);
4832 setUnnamed(old_unnamed);
4838 // FIXME We could do better here, but it is complicated. What would be
4839 // nice is to offer either (a) to save the child buffer to an appropriate
4840 // location, so that it would "move with the master", or else (b) to update
4841 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4842 // complicated, because the code for this lives in GuiView.
4843 void Buffer::checkChildBuffers()
4845 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4846 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4847 for (; it != en; ++it) {
4848 DocIterator dit = it->second;
4849 Buffer * cbuf = const_cast<Buffer *>(it->first);
4850 if (!cbuf || !theBufferList().isLoaded(cbuf))
4852 Inset * inset = dit.nextInset();
4853 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4854 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4855 docstring const & incfile = inset_inc->getParam("filename");
4856 string oldloc = cbuf->absFileName();
4857 string newloc = makeAbsPath(to_utf8(incfile),
4858 onlyPath(absFileName())).absFileName();
4859 if (oldloc == newloc)
4861 // the location of the child file is incorrect.
4862 Alert::warning(_("Included File Invalid"),
4863 bformat(_("Saving this document to a new location has made the file:\n"
4865 "inaccessible. You will need to update the included filename."),
4866 from_utf8(oldloc)));
4868 inset_inc->setChildBuffer(0);
4870 // invalidate cache of children
4871 d->children_positions.clear();
4872 d->position_to_children.clear();
4876 // If a child has been saved under a different name/path, it might have been
4877 // orphaned. Therefore the master needs to be reset (bug 8161).
4878 void Buffer::checkMasterBuffer()
4880 Buffer const * const master = masterBuffer();
4884 // necessary to re-register the child (bug 5873)
4885 // FIXME: clean up updateMacros (here, only
4886 // child registering is needed).
4887 master->updateMacros();
4888 // (re)set master as master buffer, but only
4889 // if we are a real child
4890 if (master->isChild(this))