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"
61 #include "TexStream.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
66 #include "VCBackend.h"
68 #include "WordLangTuple.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
82 #include "graphics/PreviewLoader.h"
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
222 typedef pair<DocIterator, MacroData> ScopeMacro;
223 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
224 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
225 /// map from the macro name to the position map,
226 /// which maps the macro definition position to the scope and the MacroData.
227 NamePositionScopeMacroMap macros;
228 /// This seem to change the way Buffer::getMacro() works
229 mutable bool macro_lock;
231 /// positions of child buffers in the buffer
232 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
233 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
234 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
235 /// position of children buffers in this buffer
236 BufferPositionMap children_positions;
237 /// map from children inclusion positions to their scope and their buffer
238 PositionScopeBufferMap position_to_children;
240 /// Container for all sort of Buffer dependant errors.
241 map<string, ErrorList> errorLists;
243 /// timestamp and checksum used to test if the file has been externally
244 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
246 unsigned long checksum_;
249 frontend::WorkAreaManager * wa_;
251 frontend::GuiBufferDelegate * gui_;
256 /// A cache for the bibfiles (including bibfiles of loaded child
257 /// documents), needed for appropriate update of natbib labels.
258 mutable support::FileNameList bibfiles_cache_;
260 // FIXME The caching mechanism could be improved. At present, we have a
261 // cache for each Buffer, that caches all the bibliography info for that
262 // Buffer. A more efficient solution would be to have a global cache per
263 // file, and then to construct the Buffer's bibinfo from that.
264 /// A cache for bibliography info
265 mutable BiblioInfo bibinfo_;
266 /// whether the bibinfo cache is valid
267 mutable bool bibinfo_cache_valid_;
268 /// whether the bibfile cache is valid
269 mutable bool bibfile_cache_valid_;
270 /// Cache of timestamps of .bib files
271 map<FileName, time_t> bibfile_status_;
272 /// Indicates whether the bibinfo has changed since the last time
273 /// we ran updateBuffer(), i.e., whether citation labels may need
275 mutable bool cite_labels_valid_;
277 mutable RefCache ref_cache_;
279 /// our Text that should be wrapped in an InsetText
283 PreviewLoader * preview_loader_;
285 /// This is here to force the test to be done whenever parent_buffer
287 Buffer const * parent() const
289 // ignore_parent temporarily "orphans" a buffer
290 // (e.g. if a child is compiled standalone)
293 // if parent_buffer is not loaded, then it has been unloaded,
294 // which means that parent_buffer is an invalid pointer. So we
295 // set it to null in that case.
296 // however, the BufferList doesn't know about cloned buffers, so
297 // they will always be regarded as unloaded. in that case, we hope
299 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
301 return parent_buffer;
305 void setParent(Buffer const * pb)
307 if (parent_buffer == pb)
310 if (!cloned_buffer_ && parent_buffer && pb)
311 LYXERR0("Warning: a buffer should not have two parents!");
313 if (!cloned_buffer_ && parent_buffer) {
314 parent_buffer->invalidateBibfileCache();
315 parent_buffer->invalidateBibinfoCache();
319 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
320 /// This one is useful for preview detached in a thread.
321 Buffer const * cloned_buffer_;
323 CloneList * clone_list_;
324 /// are we in the process of exporting this buffer?
325 mutable bool doing_export;
327 /// compute statistics
328 /// \p from initial position
329 /// \p to points to the end position
330 void updateStatistics(DocIterator & from, DocIterator & to,
331 bool skipNoOutput = true);
332 /// statistics accessor functions
333 int wordCount() const
337 int charCount(bool with_blanks) const
340 + (with_blanks ? blank_count_ : 0);
344 /// So we can force access via the accessors.
345 mutable Buffer const * parent_buffer;
354 /// Creates the per buffer temporary directory
355 static FileName createBufferTmpDir()
359 // We are in our own directory. Why bother to mangle name?
360 // In fact I wrote this code to circumvent a problematic behaviour
361 // (bug?) of EMX mkstemp().
362 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
363 convert<string>(count++));
365 if (!tmpfl.createDirectory(0777)) {
366 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
367 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
368 from_utf8(tmpfl.absFileName())));
374 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
375 Buffer const * cloned_buffer)
376 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
377 internal_buffer(false), read_only(readonly_), filename(file),
378 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
379 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
380 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
381 cite_labels_valid_(false), preview_loader_(0),
382 cloned_buffer_(cloned_buffer), clone_list_(0),
383 doing_export(false), parent_buffer(0)
385 if (!cloned_buffer_) {
386 temppath = createBufferTmpDir();
387 lyxvc.setBuffer(owner_);
389 wa_ = new frontend::WorkAreaManager;
392 temppath = cloned_buffer_->d->temppath;
393 file_fully_loaded = true;
394 params = cloned_buffer_->d->params;
395 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
396 bibinfo_ = cloned_buffer_->d->bibinfo_;
397 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
398 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
399 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
400 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
401 unnamed = cloned_buffer_->d->unnamed;
402 internal_buffer = cloned_buffer_->d->internal_buffer;
406 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
407 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
409 LYXERR(Debug::INFO, "Buffer::Buffer()");
411 d->inset = new InsetText(*cloned_buffer->d->inset);
412 d->inset->setBuffer(*this);
413 // FIXME: optimize this loop somewhat, maybe by creating a new
414 // general recursive Inset::setId().
415 DocIterator it = doc_iterator_begin(this);
416 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
417 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
418 it.paragraph().setId(cloned_it.paragraph().id());
420 d->inset = new InsetText(this);
421 d->inset->setAutoBreakRows(true);
422 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
428 LYXERR(Debug::INFO, "Buffer::~Buffer()");
429 // here the buffer should take care that it is
430 // saved properly, before it goes into the void.
432 // GuiView already destroyed
436 // No need to do additional cleanups for internal buffer.
442 // this is in case of recursive includes: we won't try to delete
443 // ourselves as a child.
444 d->clone_list_->erase(this);
445 // loop over children
446 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
447 Impl::BufferPositionMap::iterator end = d->children_positions.end();
448 for (; it != end; ++it) {
449 Buffer * child = const_cast<Buffer *>(it->first);
450 if (d->clone_list_->erase(child))
453 // if we're the master buffer, then we should get rid of the list
456 // If this is not empty, we have leaked something. Worse, one of the
457 // children still has a reference to this list. But we will try to
458 // continue, rather than shut down.
459 LATTEST(d->clone_list_->empty());
460 list<CloneList *>::iterator it =
461 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
462 if (it == cloned_buffers.end()) {
463 // We will leak in this case, but it is safe to continue.
466 cloned_buffers.erase(it);
467 delete d->clone_list_;
469 // FIXME Do we really need to do this right before we delete d?
470 // clear references to children in macro tables
471 d->children_positions.clear();
472 d->position_to_children.clear();
474 // loop over children
475 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
476 Impl::BufferPositionMap::iterator end = d->children_positions.end();
477 for (; it != end; ++it) {
478 Buffer * child = const_cast<Buffer *>(it->first);
479 if (theBufferList().isLoaded(child))
480 theBufferList().releaseChild(this, child);
484 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
485 msg += emergencyWrite();
486 Alert::warning(_("Attempting to close changed document!"), msg);
489 // FIXME Do we really need to do this right before we delete d?
490 // clear references to children in macro tables
491 d->children_positions.clear();
492 d->position_to_children.clear();
494 if (!d->temppath.destroyDirectory()) {
495 Alert::warning(_("Could not remove temporary directory"),
496 bformat(_("Could not remove the temporary directory %1$s"),
497 from_utf8(d->temppath.absFileName())));
506 Buffer * Buffer::cloneFromMaster() const
509 cloned_buffers.push_back(new CloneList);
510 CloneList * clones = cloned_buffers.back();
512 masterBuffer()->cloneWithChildren(bufmap, clones);
514 // make sure we got cloned
515 BufferMap::const_iterator bit = bufmap.find(this);
516 LASSERT(bit != bufmap.end(), return 0);
517 Buffer * cloned_buffer = bit->second;
519 return cloned_buffer;
523 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
525 // have we already been cloned?
526 if (bufmap.find(this) != bufmap.end())
529 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
531 // The clone needs its own DocumentClass, since running updateBuffer() will
532 // modify it, and we would otherwise be sharing it with the original Buffer.
533 buffer_clone->params().makeDocumentClass(true);
535 cap::switchBetweenClasses(
536 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
537 static_cast<InsetText &>(buffer_clone->inset()), el);
539 bufmap[this] = buffer_clone;
540 clones->insert(buffer_clone);
541 buffer_clone->d->clone_list_ = clones;
542 buffer_clone->d->macro_lock = true;
543 buffer_clone->d->children_positions.clear();
545 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
546 // math macro caches need to be rethought and simplified.
547 // I am not sure wether we should handle Buffer cloning here or in BufferList.
548 // Right now BufferList knows nothing about buffer clones.
549 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
550 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
551 for (; it != end; ++it) {
552 DocIterator dit = it->first.clone(buffer_clone);
553 dit.setBuffer(buffer_clone);
554 Buffer * child = const_cast<Buffer *>(it->second.second);
556 child->cloneWithChildren(bufmap, clones);
557 BufferMap::iterator const bit = bufmap.find(child);
558 LASSERT(bit != bufmap.end(), continue);
559 Buffer * child_clone = bit->second;
561 Inset * inset = dit.nextInset();
562 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
563 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
564 inset_inc->setChildBuffer(child_clone);
565 child_clone->d->setParent(buffer_clone);
566 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
567 buffer_clone->setChild(dit, child_clone);
569 buffer_clone->d->macro_lock = false;
574 Buffer * Buffer::cloneBufferOnly() const {
575 cloned_buffers.push_back(new CloneList);
576 CloneList * clones = cloned_buffers.back();
577 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
579 // The clone needs its own DocumentClass, since running updateBuffer() will
580 // modify it, and we would otherwise be sharing it with the original Buffer.
581 buffer_clone->params().makeDocumentClass(true);
583 cap::switchBetweenClasses(
584 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
585 static_cast<InsetText &>(buffer_clone->inset()), el);
587 clones->insert(buffer_clone);
588 buffer_clone->d->clone_list_ = clones;
590 // we won't be cloning the children
591 buffer_clone->d->children_positions.clear();
596 bool Buffer::isClone() const
598 return d->cloned_buffer_;
602 void Buffer::changed(bool update_metrics) const
605 d->wa_->redrawAll(update_metrics);
609 frontend::WorkAreaManager & Buffer::workAreaManager() const
616 Text & Buffer::text() const
618 return d->inset->text();
622 Inset & Buffer::inset() const
628 BufferParams & Buffer::params()
634 BufferParams const & Buffer::params() const
640 BufferParams const & Buffer::masterParams() const
642 if (masterBuffer() == this)
645 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
646 // Copy child authors to the params. We need those pointers.
647 AuthorList const & child_authors = params().authors();
648 AuthorList::Authors::const_iterator it = child_authors.begin();
649 for (; it != child_authors.end(); it++)
650 mparams.authors().record(*it);
655 ParagraphList & Buffer::paragraphs()
657 return text().paragraphs();
661 ParagraphList const & Buffer::paragraphs() const
663 return text().paragraphs();
667 LyXVC & Buffer::lyxvc()
673 LyXVC const & Buffer::lyxvc() const
679 string const Buffer::temppath() const
681 return d->temppath.absFileName();
685 TexRow & Buffer::texrow()
691 TexRow const & Buffer::texrow() const
697 TocBackend & Buffer::tocBackend() const
699 return d->toc_backend;
703 Undo & Buffer::undo()
709 void Buffer::setChild(DocIterator const & dit, Buffer * child)
711 d->children_positions[child] = dit;
715 string Buffer::latexName(bool const no_path) const
717 FileName latex_name =
718 makeLatexName(d->exportFileName());
719 return no_path ? latex_name.onlyFileName()
720 : latex_name.absFileName();
724 FileName Buffer::Impl::exportFileName() const
726 docstring const branch_suffix =
727 params.branchlist().getFileNameSuffix();
728 if (branch_suffix.empty())
731 string const name = filename.onlyFileNameWithoutExt()
732 + to_utf8(branch_suffix);
733 FileName res(filename.onlyPath().absFileName() + "/" + name);
734 res.changeExtension(filename.extension());
740 string Buffer::logName(LogType * type) const
742 string const filename = latexName(false);
744 if (filename.empty()) {
750 string const path = temppath();
752 FileName const fname(addName(temppath(),
753 onlyFileName(changeExtension(filename,
756 // FIXME: how do we know this is the name of the build log?
757 FileName const bname(
758 addName(path, onlyFileName(
759 changeExtension(filename,
760 formats.extension(params().bufferFormat()) + ".out"))));
762 // Also consider the master buffer log file
763 FileName masterfname = fname;
765 if (masterBuffer() != this) {
766 string const mlogfile = masterBuffer()->logName(&mtype);
767 masterfname = FileName(mlogfile);
770 // If no Latex log or Build log is newer, show Build log
771 if (bname.exists() &&
772 ((!fname.exists() && !masterfname.exists())
773 || (fname.lastModified() < bname.lastModified()
774 && masterfname.lastModified() < bname.lastModified()))) {
775 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
778 return bname.absFileName();
779 // If we have a newer master file log or only a master log, show this
780 } else if (fname != masterfname
781 && (!fname.exists() && (masterfname.exists()
782 || fname.lastModified() < masterfname.lastModified()))) {
783 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
786 return masterfname.absFileName();
788 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
791 return fname.absFileName();
795 void Buffer::setReadonly(bool const flag)
797 if (d->read_only != flag) {
804 void Buffer::setFileName(FileName const & fname)
806 bool const changed = fname != d->filename;
809 lyxvc().file_found_hook(fname);
810 setReadonly(d->filename.isReadOnly());
816 int Buffer::readHeader(Lexer & lex)
818 int unknown_tokens = 0;
820 int begin_header_line = -1;
822 // Initialize parameters that may be/go lacking in header:
823 params().branchlist().clear();
824 params().preamble.erase();
825 params().options.erase();
826 params().master.erase();
827 params().float_placement.erase();
828 params().paperwidth.erase();
829 params().paperheight.erase();
830 params().leftmargin.erase();
831 params().rightmargin.erase();
832 params().topmargin.erase();
833 params().bottommargin.erase();
834 params().headheight.erase();
835 params().headsep.erase();
836 params().footskip.erase();
837 params().columnsep.erase();
838 params().fonts_cjk.erase();
839 params().listings_params.clear();
840 params().clearLayoutModules();
841 params().clearRemovedModules();
842 params().clearIncludedChildren();
843 params().pdfoptions().clear();
844 params().indiceslist().clear();
845 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
846 params().isbackgroundcolor = false;
847 params().fontcolor = RGBColor(0, 0, 0);
848 params().isfontcolor = false;
849 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
850 params().boxbgcolor = RGBColor(0xFF, 0, 0);
851 params().html_latex_start.clear();
852 params().html_latex_end.clear();
853 params().html_math_img_scale = 1.0;
854 params().output_sync_macro.erase();
855 params().setLocalLayout(string(), false);
856 params().setLocalLayout(string(), true);
858 for (int i = 0; i < 4; ++i) {
859 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
860 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
863 ErrorList & errorList = d->errorLists["Parse"];
872 if (token == "\\end_header")
876 if (token == "\\begin_header") {
877 begin_header_line = line;
881 LYXERR(Debug::PARSER, "Handling document header token: `"
884 string unknown = params().readToken(lex, token, d->filename.onlyPath());
885 if (!unknown.empty()) {
886 if (unknown[0] != '\\' && token == "\\textclass") {
887 Alert::warning(_("Unknown document class"),
888 bformat(_("Using the default document class, because the "
889 "class %1$s is unknown."), from_utf8(unknown)));
892 docstring const s = bformat(_("Unknown token: "
896 errorList.push_back(ErrorItem(_("Document header error"),
901 if (begin_header_line) {
902 docstring const s = _("\\begin_header is missing");
903 errorList.push_back(ErrorItem(_("Document header error"),
907 params().makeDocumentClass();
909 return unknown_tokens;
914 // changed to be public and have one parameter
915 // Returns true if "\end_document" is not read (Asger)
916 bool Buffer::readDocument(Lexer & lex)
918 ErrorList & errorList = d->errorLists["Parse"];
921 // remove dummy empty par
922 paragraphs().clear();
924 if (!lex.checkFor("\\begin_document")) {
925 docstring const s = _("\\begin_document is missing");
926 errorList.push_back(ErrorItem(_("Document header error"),
932 if (params().output_changes) {
933 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
934 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
935 LaTeXFeatures::isAvailable("xcolor");
937 if (!dvipost && !xcolorulem) {
938 Alert::warning(_("Changes not shown in LaTeX output"),
939 _("Changes will not be highlighted in LaTeX output, "
940 "because neither dvipost nor xcolor/ulem are installed.\n"
941 "Please install these packages or redefine "
942 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
943 } else if (!xcolorulem) {
944 Alert::warning(_("Changes not shown in LaTeX output"),
945 _("Changes will not be highlighted in LaTeX output "
946 "when using pdflatex, because xcolor and ulem are not installed.\n"
947 "Please install both packages or redefine "
948 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
952 if (!parent() && !params().master.empty()) {
953 FileName const master_file = makeAbsPath(params().master,
954 onlyPath(absFileName()));
955 if (isLyXFileName(master_file.absFileName())) {
957 checkAndLoadLyXFile(master_file, true);
959 // necessary e.g. after a reload
960 // to re-register the child (bug 5873)
961 // FIXME: clean up updateMacros (here, only
962 // child registering is needed).
963 master->updateMacros();
964 // set master as master buffer, but only
965 // if we are a real child
966 if (master->isChild(this))
968 // if the master is not fully loaded
969 // it is probably just loading this
970 // child. No warning needed then.
971 else if (master->isFullyLoaded())
972 LYXERR0("The master '"
974 << "' assigned to this document ("
976 << ") does not include "
977 "this document. Ignoring the master assignment.");
982 // assure we have a default index
983 params().indiceslist().addDefault(B_("Index"));
986 bool const res = text().read(lex, errorList, d->inset);
988 // inform parent buffer about local macros
990 Buffer const * pbuf = parent();
991 UserMacroSet::const_iterator cit = usermacros.begin();
992 UserMacroSet::const_iterator end = usermacros.end();
993 for (; cit != end; ++cit)
994 pbuf->usermacros.insert(*cit);
998 updateMacroInstances(InternalUpdate);
1003 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1005 Format const * fmt = formats.getFormat(format);
1008 // It is important to use the correct extension here, since some
1009 // converters create a wrong output file otherwise (e.g. html2latex)
1010 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1011 FileName const name(tempfile.name());
1012 ofdocstream os(name.toFilesystemEncoding().c_str());
1013 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1014 bool const success = !(os << contents).fail();
1017 bool converted = false;
1019 params().compressed = false;
1021 // remove dummy empty par
1022 paragraphs().clear();
1024 converted = importFile(format, name, errorList);
1033 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1035 if (!theConverters().isReachable(format, "lyx"))
1038 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1039 FileName const lyx(tempfile.name());
1040 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1041 return readFile(lyx) == ReadSuccess;
1047 bool Buffer::readString(string const & s)
1049 params().compressed = false;
1052 istringstream is(s);
1054 FileName const fn = FileName::tempName("Buffer_readString");
1057 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1059 if (success && file_format != LYX_FORMAT) {
1060 // We need to call lyx2lyx, so write the input to a file
1061 ofstream os(fn.toFilesystemEncoding().c_str());
1064 // lyxvc in readFile
1065 if (readFile(fn) != ReadSuccess)
1069 if (readDocument(lex))
1077 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1081 if (!lex.setFile(fname)) {
1082 Alert::error(_("File Not Found"),
1083 bformat(_("Unable to open file `%1$s'."),
1084 from_utf8(fn.absFileName())));
1085 return ReadFileNotFound;
1089 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1090 if (ret_plf != ReadSuccess)
1093 if (file_format != LYX_FORMAT) {
1095 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1096 if (ret_clf != ReadSuccess)
1098 return readFile(tmpFile);
1101 // FIXME: InsetInfo needs to know whether the file is under VCS
1102 // during the parse process, so this has to be done before.
1103 lyxvc().file_found_hook(d->filename);
1105 if (readDocument(lex)) {
1106 Alert::error(_("Document format failure"),
1107 bformat(_("%1$s ended unexpectedly, which means"
1108 " that it is probably corrupted."),
1109 from_utf8(fn.absFileName())));
1110 return ReadDocumentFailure;
1113 d->file_fully_loaded = true;
1114 d->read_only = !d->filename.isWritable();
1115 params().compressed = formats.isZippedFile(d->filename);
1121 bool Buffer::isFullyLoaded() const
1123 return d->file_fully_loaded;
1127 void Buffer::setFullyLoaded(bool value)
1129 d->file_fully_loaded = value;
1133 PreviewLoader * Buffer::loader() const
1135 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1137 if (!d->preview_loader_)
1138 d->preview_loader_ = new PreviewLoader(*this);
1139 return d->preview_loader_;
1143 void Buffer::removePreviews() const
1145 delete d->preview_loader_;
1146 d->preview_loader_ = 0;
1150 void Buffer::updatePreviews() const
1152 PreviewLoader * ploader = loader();
1156 InsetIterator it = inset_iterator_begin(*d->inset);
1157 InsetIterator const end = inset_iterator_end(*d->inset);
1158 for (; it != end; ++it)
1159 it->addPreview(it, *ploader);
1161 ploader->startLoading();
1165 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1166 FileName const & fn, int & file_format) const
1168 if(!lex.checkFor("\\lyxformat")) {
1169 Alert::error(_("Document format failure"),
1170 bformat(_("%1$s is not a readable LyX document."),
1171 from_utf8(fn.absFileName())));
1172 return ReadNoLyXFormat;
1178 // LyX formats 217 and earlier were written as 2.17. This corresponds
1179 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1180 // these cases. See also: www.lyx.org/trac/changeset/1313.
1181 size_t dot = tmp_format.find_first_of(".,");
1182 if (dot != string::npos)
1183 tmp_format.erase(dot, 1);
1185 file_format = convert<int>(tmp_format);
1190 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1191 FileName & tmpfile, int from_format)
1193 tmpfile = FileName::tempName("Buffer_convertLyXFormatXXXXXX.lyx");
1194 if(tmpfile.empty()) {
1195 Alert::error(_("Conversion failed"),
1196 bformat(_("%1$s is from a different"
1197 " version of LyX, but a temporary"
1198 " file for converting it could"
1199 " not be created."),
1200 from_utf8(fn.absFileName())));
1201 return LyX2LyXNoTempFile;
1204 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1205 if (lyx2lyx.empty()) {
1206 Alert::error(_("Conversion script not found"),
1207 bformat(_("%1$s is from a different"
1208 " version of LyX, but the"
1209 " conversion script lyx2lyx"
1210 " could not be found."),
1211 from_utf8(fn.absFileName())));
1212 return LyX2LyXNotFound;
1216 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1217 ostringstream command;
1218 command << os::python()
1219 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1220 << " -t " << convert<string>(LYX_FORMAT)
1221 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1222 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1223 string const command_str = command.str();
1225 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1227 cmd_ret const ret = runCommand(command_str);
1228 if (ret.first != 0) {
1229 if (from_format < LYX_FORMAT) {
1230 Alert::error(_("Conversion script failed"),
1231 bformat(_("%1$s is from an older version"
1232 " of LyX and the lyx2lyx script"
1233 " failed to convert it."),
1234 from_utf8(fn.absFileName())));
1235 return LyX2LyXOlderFormat;
1237 Alert::error(_("Conversion script failed"),
1238 bformat(_("%1$s is from a newer version"
1239 " of LyX and the lyx2lyx script"
1240 " failed to convert it."),
1241 from_utf8(fn.absFileName())));
1242 return LyX2LyXNewerFormat;
1249 // Should probably be moved to somewhere else: BufferView? GuiView?
1250 bool Buffer::save() const
1252 docstring const file = makeDisplayPath(absFileName(), 20);
1253 d->filename.refresh();
1255 // check the read-only status before moving the file as a backup
1256 if (d->filename.exists()) {
1257 bool const read_only = !d->filename.isWritable();
1259 Alert::warning(_("File is read-only"),
1260 bformat(_("The file %1$s cannot be written because it "
1261 "is marked as read-only."), file));
1266 // ask if the disk file has been externally modified (use checksum method)
1267 if (fileName().exists() && isExternallyModified(checksum_method)) {
1269 bformat(_("Document %1$s has been externally modified. "
1270 "Are you sure you want to overwrite this file?"), file);
1271 int const ret = Alert::prompt(_("Overwrite modified file?"),
1272 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1277 // We don't need autosaves in the immediate future. (Asger)
1278 resetAutosaveTimers();
1280 FileName backupName;
1281 bool madeBackup = false;
1283 // make a backup if the file already exists
1284 if (lyxrc.make_backup && fileName().exists()) {
1285 backupName = FileName(absFileName() + '~');
1286 if (!lyxrc.backupdir_path.empty()) {
1287 string const mangledName =
1288 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1289 backupName = FileName(addName(lyxrc.backupdir_path,
1293 // Except file is symlink do not copy because of #6587.
1294 // Hard links have bad luck.
1295 if (fileName().isSymLink())
1296 madeBackup = fileName().copyTo(backupName);
1298 madeBackup = fileName().moveTo(backupName);
1301 Alert::error(_("Backup failure"),
1302 bformat(_("Cannot create backup file %1$s.\n"
1303 "Please check whether the directory exists and is writable."),
1304 from_utf8(backupName.absFileName())));
1305 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1309 if (writeFile(d->filename)) {
1313 // Saving failed, so backup is not backup
1315 backupName.moveTo(d->filename);
1321 bool Buffer::writeFile(FileName const & fname) const
1323 if (d->read_only && fname == d->filename)
1326 bool retval = false;
1328 docstring const str = bformat(_("Saving document %1$s..."),
1329 makeDisplayPath(fname.absFileName()));
1332 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1334 if (params().compressed) {
1335 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1336 retval = ofs && write(ofs);
1338 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1339 retval = ofs && write(ofs);
1343 message(str + _(" could not write file!"));
1348 // removeAutosaveFile();
1351 message(str + _(" done."));
1357 docstring Buffer::emergencyWrite()
1359 // No need to save if the buffer has not changed.
1363 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1365 docstring user_message = bformat(
1366 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1368 // We try to save three places:
1369 // 1) Same place as document. Unless it is an unnamed doc.
1371 string s = absFileName();
1374 if (writeFile(FileName(s))) {
1376 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1377 return user_message;
1379 user_message += " " + _("Save failed! Trying again...\n");
1383 // 2) In HOME directory.
1384 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1386 lyxerr << ' ' << s << endl;
1387 if (writeFile(FileName(s))) {
1389 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1390 return user_message;
1393 user_message += " " + _("Save failed! Trying yet again...\n");
1395 // 3) In "/tmp" directory.
1396 // MakeAbsPath to prepend the current
1397 // drive letter on OS/2
1398 s = addName(package().temp_dir().absFileName(), absFileName());
1400 lyxerr << ' ' << s << endl;
1401 if (writeFile(FileName(s))) {
1403 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1404 return user_message;
1407 user_message += " " + _("Save failed! Bummer. Document is lost.");
1410 return user_message;
1414 bool Buffer::write(ostream & ofs) const
1417 // Use the standard "C" locale for file output.
1418 ofs.imbue(locale::classic());
1421 // The top of the file should not be written by params().
1423 // write out a comment in the top of the file
1424 // Important: Keep the version formatting in sync with lyx2lyx and
1425 // tex2lyx (bug 7951)
1426 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1427 << " created this file. For more info see http://www.lyx.org/\n"
1428 << "\\lyxformat " << LYX_FORMAT << "\n"
1429 << "\\begin_document\n";
1431 /// For each author, set 'used' to true if there is a change
1432 /// by this author in the document; otherwise set it to 'false'.
1433 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1434 AuthorList::Authors::const_iterator a_end = params().authors().end();
1435 for (; a_it != a_end; ++a_it)
1436 a_it->setUsed(false);
1438 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1439 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1440 for ( ; it != end; ++it)
1441 it->checkAuthors(params().authors());
1443 // now write out the buffer parameters.
1444 ofs << "\\begin_header\n";
1445 params().writeFile(ofs);
1446 ofs << "\\end_header\n";
1449 ofs << "\n\\begin_body\n";
1451 ofs << "\n\\end_body\n";
1453 // Write marker that shows file is complete
1454 ofs << "\\end_document" << endl;
1456 // Shouldn't really be needed....
1459 // how to check if close went ok?
1460 // Following is an attempt... (BE 20001011)
1462 // good() returns false if any error occured, including some
1463 // formatting error.
1464 // bad() returns true if something bad happened in the buffer,
1465 // which should include file system full errors.
1470 lyxerr << "File was not closed properly." << endl;
1477 bool Buffer::makeLaTeXFile(FileName const & fname,
1478 string const & original_path,
1479 OutputParams const & runparams_in,
1480 OutputWhat output) const
1482 OutputParams runparams = runparams_in;
1484 // This is necessary for LuaTeX/XeTeX with tex fonts.
1485 // See FIXME in BufferParams::encoding()
1486 if (runparams.isFullUnicode())
1487 runparams.encoding = encodings.fromLyXName("utf8-plain");
1489 string const encoding = runparams.encoding->iconvName();
1490 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1493 try { ofs.reset(encoding); }
1494 catch (iconv_codecvt_facet_exception const & e) {
1495 lyxerr << "Caught iconv exception: " << e.what() << endl;
1496 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1497 "verify that the support software for your encoding (%1$s) is "
1498 "properly installed"), from_ascii(encoding)));
1501 if (!openFileWrite(ofs, fname))
1504 //TexStream ts(ofs.rdbuf(), &texrow());
1505 ErrorList & errorList = d->errorLists["Export"];
1507 bool failed_export = false;
1508 otexstream os(ofs, d->texrow);
1510 // make sure we are ready to export
1511 // this needs to be done before we validate
1512 // FIXME Do we need to do this all the time? I.e., in children
1513 // of a master we are exporting?
1515 updateMacroInstances(OutputUpdate);
1518 os.texrow().reset();
1519 writeLaTeXSource(os, original_path, runparams, output);
1521 catch (EncodingException const & e) {
1522 odocstringstream ods;
1523 ods.put(e.failed_char);
1525 oss << "0x" << hex << e.failed_char << dec;
1526 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1527 " (code point %2$s)"),
1528 ods.str(), from_utf8(oss.str()));
1529 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1530 "representable in the chosen encoding.\n"
1531 "Changing the document encoding to utf8 could help."),
1532 e.par_id, e.pos, e.pos + 1));
1533 failed_export = true;
1535 catch (iconv_codecvt_facet_exception const & e) {
1536 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1537 _(e.what()), -1, 0, 0));
1538 failed_export = true;
1540 catch (exception const & e) {
1541 errorList.push_back(ErrorItem(_("conversion failed"),
1542 _(e.what()), -1, 0, 0));
1543 failed_export = true;
1546 lyxerr << "Caught some really weird exception..." << endl;
1552 failed_export = true;
1553 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1556 if (runparams_in.silent)
1560 return !failed_export;
1564 void Buffer::writeLaTeXSource(otexstream & os,
1565 string const & original_path,
1566 OutputParams const & runparams_in,
1567 OutputWhat output) const
1569 // The child documents, if any, shall be already loaded at this point.
1571 OutputParams runparams = runparams_in;
1573 // If we are compiling a file standalone, even if this is the
1574 // child of some other buffer, let's cut the link here, so the
1575 // file is really independent and no concurring settings from
1576 // the master (e.g. branch state) interfere (see #8100).
1577 if (!runparams.is_child)
1578 d->ignore_parent = true;
1580 // Classify the unicode characters appearing in math insets
1581 BufferEncodings::initUnicodeMath(*this);
1583 // validate the buffer.
1584 LYXERR(Debug::LATEX, " Validating buffer...");
1585 LaTeXFeatures features(*this, params(), runparams);
1587 // This is only set once per document (in master)
1588 if (!runparams.is_child)
1589 runparams.use_polyglossia = features.usePolyglossia();
1590 LYXERR(Debug::LATEX, " Buffer validation done.");
1592 bool const output_preamble =
1593 output == FullSource || output == OnlyPreamble;
1594 bool const output_body =
1595 output == FullSource || output == OnlyBody;
1597 // The starting paragraph of the coming rows is the
1598 // first paragraph of the document. (Asger)
1599 if (output_preamble && runparams.nice) {
1600 os << "%% LyX " << lyx_version << " created this file. "
1601 "For more info, see http://www.lyx.org/.\n"
1602 "%% Do not edit unless you really know what "
1605 LYXERR(Debug::INFO, "lyx document header finished");
1607 // There are a few differences between nice LaTeX and usual files:
1608 // usual files have \batchmode and special input@path to allow
1609 // inclusion of figures specified by an explicitly relative path
1610 // (i.e., a path starting with './' or '../') with either \input or
1611 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1612 // input@path is set when the actual parameter original_path is set.
1613 // This is done for usual tex-file, but not for nice-latex-file.
1614 // (Matthias 250696)
1615 // Note that input@path is only needed for something the user does
1616 // in the preamble, included .tex files or ERT, files included by
1617 // LyX work without it.
1618 if (output_preamble) {
1619 if (!runparams.nice) {
1620 // code for usual, NOT nice-latex-file
1621 os << "\\batchmode\n"; // changed from \nonstopmode
1623 if (!original_path.empty()) {
1625 // We don't know the encoding of inputpath
1626 docstring const inputpath = from_utf8(original_path);
1627 docstring uncodable_glyphs;
1628 Encoding const * const enc = runparams.encoding;
1630 for (size_t n = 0; n < inputpath.size(); ++n) {
1631 if (!enc->encodable(inputpath[n])) {
1632 docstring const glyph(1, inputpath[n]);
1633 LYXERR0("Uncodable character '"
1635 << "' in input path!");
1636 uncodable_glyphs += glyph;
1641 // warn user if we found uncodable glyphs.
1642 if (!uncodable_glyphs.empty()) {
1643 frontend::Alert::warning(
1644 _("Uncodable character in file path"),
1646 _("The path of your document\n"
1648 "contains glyphs that are unknown "
1649 "in the current document encoding "
1650 "(namely %2$s). This may result in "
1651 "incomplete output, unless "
1652 "TEXINPUTS contains the document "
1653 "directory and you don't use "
1654 "explicitly relative paths (i.e., "
1655 "paths starting with './' or "
1656 "'../') in the preamble or in ERT."
1657 "\n\nIn case of problems, choose "
1658 "an appropriate document encoding\n"
1659 "(such as utf8) or change the "
1661 inputpath, uncodable_glyphs));
1664 support::latex_path(original_path);
1665 if (contains(docdir, '#')) {
1666 docdir = subst(docdir, "#", "\\#");
1667 os << "\\catcode`\\#=11"
1668 "\\def\\#{#}\\catcode`\\#=6\n";
1670 if (contains(docdir, '%')) {
1671 docdir = subst(docdir, "%", "\\%");
1672 os << "\\catcode`\\%=11"
1673 "\\def\\%{%}\\catcode`\\%=14\n";
1675 os << "\\makeatletter\n"
1676 << "\\def\\input@path{{"
1677 << docdir << "/}}\n"
1678 << "\\makeatother\n";
1682 // get parent macros (if this buffer has a parent) which will be
1683 // written at the document begin further down.
1684 MacroSet parentMacros;
1685 listParentMacros(parentMacros, features);
1687 // Write the preamble
1688 runparams.use_babel = params().writeLaTeX(os, features,
1689 d->filename.onlyPath());
1691 // Japanese might be required only in some children of a document,
1692 // but once required, we must keep use_japanese true.
1693 runparams.use_japanese |= features.isRequired("japanese");
1696 // Restore the parenthood if needed
1697 if (!runparams.is_child)
1698 d->ignore_parent = false;
1703 os << "\\begin{document}\n";
1705 // output the parent macros
1706 MacroSet::iterator it = parentMacros.begin();
1707 MacroSet::iterator end = parentMacros.end();
1708 for (; it != end; ++it) {
1709 int num_lines = (*it)->write(os.os(), true);
1710 os.texrow().newlines(num_lines);
1713 } // output_preamble
1715 os.texrow().start(paragraphs().begin()->id(), 0);
1717 LYXERR(Debug::INFO, "preamble finished, now the body.");
1720 latexParagraphs(*this, text(), os, runparams);
1722 // Restore the parenthood if needed
1723 if (!runparams.is_child)
1724 d->ignore_parent = false;
1726 // add this just in case after all the paragraphs
1729 if (output_preamble) {
1730 os << "\\end{document}\n";
1731 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1733 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1735 runparams_in.encoding = runparams.encoding;
1737 // Just to be sure. (Asger)
1738 os.texrow().newline();
1740 //for (int i = 0; i<d->texrow.rows(); i++) {
1742 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1743 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1746 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1747 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1751 void Buffer::makeDocBookFile(FileName const & fname,
1752 OutputParams const & runparams,
1753 OutputWhat output) const
1755 LYXERR(Debug::LATEX, "makeDocBookFile...");
1758 if (!openFileWrite(ofs, fname))
1761 // make sure we are ready to export
1762 // this needs to be done before we validate
1764 updateMacroInstances(OutputUpdate);
1766 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1770 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1774 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1775 OutputParams const & runparams,
1776 OutputWhat output) const
1778 LaTeXFeatures features(*this, params(), runparams);
1783 DocumentClass const & tclass = params().documentClass();
1784 string const top_element = tclass.latexname();
1786 bool const output_preamble =
1787 output == FullSource || output == OnlyPreamble;
1788 bool const output_body =
1789 output == FullSource || output == OnlyBody;
1791 if (output_preamble) {
1792 if (runparams.flavor == OutputParams::XML)
1793 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1796 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1799 if (! tclass.class_header().empty())
1800 os << from_ascii(tclass.class_header());
1801 else if (runparams.flavor == OutputParams::XML)
1802 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1803 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1805 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1807 docstring preamble = from_utf8(params().preamble);
1808 if (runparams.flavor != OutputParams::XML ) {
1809 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1810 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1811 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1812 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1815 string const name = runparams.nice
1816 ? changeExtension(absFileName(), ".sgml") : fname;
1817 preamble += features.getIncludedFiles(name);
1818 preamble += features.getLyXSGMLEntities();
1820 if (!preamble.empty()) {
1821 os << "\n [ " << preamble << " ]";
1827 string top = top_element;
1829 if (runparams.flavor == OutputParams::XML)
1830 top += params().language->code();
1832 top += params().language->code().substr(0, 2);
1835 if (!params().options.empty()) {
1837 top += params().options;
1840 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1841 << " file was created by LyX " << lyx_version
1842 << "\n See http://www.lyx.org/ for more information -->\n";
1844 params().documentClass().counters().reset();
1846 sgml::openTag(os, top);
1848 docbookParagraphs(text(), *this, os, runparams);
1849 sgml::closeTag(os, top_element);
1854 void Buffer::makeLyXHTMLFile(FileName const & fname,
1855 OutputParams const & runparams) const
1857 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1860 if (!openFileWrite(ofs, fname))
1863 // make sure we are ready to export
1864 // this has to be done before we validate
1865 updateBuffer(UpdateMaster, OutputUpdate);
1866 updateMacroInstances(OutputUpdate);
1868 writeLyXHTMLSource(ofs, runparams, FullSource);
1872 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1876 void Buffer::writeLyXHTMLSource(odocstream & os,
1877 OutputParams const & runparams,
1878 OutputWhat output) const
1880 LaTeXFeatures features(*this, params(), runparams);
1882 d->bibinfo_.makeCitationLabels(*this);
1884 bool const output_preamble =
1885 output == FullSource || output == OnlyPreamble;
1886 bool const output_body =
1887 output == FullSource || output == OnlyBody || output == IncludedFile;
1889 if (output_preamble) {
1890 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1891 << "<!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"
1892 // FIXME Language should be set properly.
1893 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1895 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1896 // FIXME Presumably need to set this right
1897 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1899 docstring const & doctitle = features.htmlTitle();
1901 << (doctitle.empty() ?
1902 from_ascii("LyX Document") :
1903 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1906 docstring styles = features.getTClassHTMLPreamble();
1907 if (!styles.empty())
1908 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1910 styles = from_utf8(features.getPreambleSnippets());
1911 if (!styles.empty())
1912 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1914 // we will collect CSS information in a stream, and then output it
1915 // either here, as part of the header, or else in a separate file.
1916 odocstringstream css;
1917 styles = from_utf8(features.getCSSSnippets());
1918 if (!styles.empty())
1919 css << "/* LyX Provided Styles */\n" << styles << '\n';
1921 styles = features.getTClassHTMLStyles();
1922 if (!styles.empty())
1923 css << "/* Layout-provided Styles */\n" << styles << '\n';
1925 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1926 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1927 if (needfg || needbg) {
1928 css << "\nbody {\n";
1931 << from_ascii(X11hexname(params().fontcolor))
1934 css << " background-color: "
1935 << from_ascii(X11hexname(params().backgroundcolor))
1940 docstring const dstyles = css.str();
1941 if (!dstyles.empty()) {
1942 bool written = false;
1943 if (params().html_css_as_file) {
1944 // open a file for CSS info
1946 string const fcssname = addName(temppath(), "docstyle.css");
1947 FileName const fcssfile = FileName(fcssname);
1948 if (openFileWrite(ocss, fcssfile)) {
1952 // write link to header
1953 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1955 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1958 // we are here if the CSS is supposed to be written to the header
1959 // or if we failed to write it to an external file.
1961 os << "<style type='text/css'>\n"
1970 bool const output_body_tag = (output != IncludedFile);
1971 if (output_body_tag)
1974 if (output != IncludedFile)
1975 // if we're an included file, the counters are in the master.
1976 params().documentClass().counters().reset();
1977 xhtmlParagraphs(text(), *this, xs, runparams);
1978 if (output_body_tag)
1982 if (output_preamble)
1987 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1988 // Other flags: -wall -v0 -x
1989 int Buffer::runChktex()
1993 // get LaTeX-Filename
1994 FileName const path(temppath());
1995 string const name = addName(path.absFileName(), latexName());
1996 string const org_path = filePath();
1998 PathChanger p(path); // path to LaTeX file
1999 message(_("Running chktex..."));
2001 // Generate the LaTeX file if neccessary
2002 OutputParams runparams(¶ms().encoding());
2003 runparams.flavor = OutputParams::LATEX;
2004 runparams.nice = false;
2005 runparams.linelen = lyxrc.plaintext_linelen;
2006 makeLaTeXFile(FileName(name), org_path, runparams);
2009 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2010 int const res = chktex.run(terr); // run chktex
2013 Alert::error(_("chktex failure"),
2014 _("Could not run chktex successfully."));
2016 ErrorList & errlist = d->errorLists["ChkTeX"];
2018 bufferErrors(terr, errlist);
2023 if (runparams.silent)
2024 d->errorLists["ChkTeX"].clear();
2032 void Buffer::validate(LaTeXFeatures & features) const
2034 // Validate the buffer params, but not for included
2035 // files, since they also use the parent buffer's
2037 if (!features.runparams().is_child)
2038 params().validate(features);
2040 for_each(paragraphs().begin(), paragraphs().end(),
2041 bind(&Paragraph::validate, _1, ref(features)));
2043 if (lyxerr.debugging(Debug::LATEX)) {
2044 features.showStruct();
2049 void Buffer::getLabelList(vector<docstring> & list) const
2051 // If this is a child document, use the master's list instead.
2053 masterBuffer()->getLabelList(list);
2058 Toc & toc = d->toc_backend.toc("label");
2059 TocIterator toc_it = toc.begin();
2060 TocIterator end = toc.end();
2061 for (; toc_it != end; ++toc_it) {
2062 if (toc_it->depth() == 0)
2063 list.push_back(toc_it->str());
2068 void Buffer::updateBibfilesCache(UpdateScope scope) const
2070 // FIXME This is probably unnecssary, given where we call this.
2071 // If this is a child document, use the parent's cache instead.
2072 if (parent() && scope != UpdateChildOnly) {
2073 masterBuffer()->updateBibfilesCache();
2077 d->bibfiles_cache_.clear();
2078 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2079 if (it->lyxCode() == BIBTEX_CODE) {
2080 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2081 support::FileNameList const bibfiles = inset.getBibFiles();
2082 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2085 } else if (it->lyxCode() == INCLUDE_CODE) {
2086 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2087 Buffer const * const incbuf = inset.getChildBuffer();
2090 support::FileNameList const & bibfiles =
2091 incbuf->getBibfilesCache(UpdateChildOnly);
2092 if (!bibfiles.empty()) {
2093 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2099 d->bibfile_cache_valid_ = true;
2100 d->bibinfo_cache_valid_ = false;
2101 d->cite_labels_valid_ = false;
2105 void Buffer::invalidateBibinfoCache() const
2107 d->bibinfo_cache_valid_ = false;
2108 d->cite_labels_valid_ = false;
2109 // also invalidate the cache for the parent buffer
2110 Buffer const * const pbuf = d->parent();
2112 pbuf->invalidateBibinfoCache();
2116 void Buffer::invalidateBibfileCache() const
2118 d->bibfile_cache_valid_ = false;
2119 d->bibinfo_cache_valid_ = false;
2120 d->cite_labels_valid_ = false;
2121 // also invalidate the cache for the parent buffer
2122 Buffer const * const pbuf = d->parent();
2124 pbuf->invalidateBibfileCache();
2128 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2130 // FIXME This is probably unnecessary, given where we call this.
2131 // If this is a child document, use the master's cache instead.
2132 Buffer const * const pbuf = masterBuffer();
2133 if (pbuf != this && scope != UpdateChildOnly)
2134 return pbuf->getBibfilesCache();
2136 if (!d->bibfile_cache_valid_)
2137 this->updateBibfilesCache(scope);
2139 return d->bibfiles_cache_;
2143 BiblioInfo const & Buffer::masterBibInfo() const
2145 Buffer const * const tmp = masterBuffer();
2147 return tmp->masterBibInfo();
2152 void Buffer::checkIfBibInfoCacheIsValid() const
2154 // use the master's cache
2155 Buffer const * const tmp = masterBuffer();
2157 tmp->checkIfBibInfoCacheIsValid();
2161 // compare the cached timestamps with the actual ones.
2162 FileNameList const & bibfiles_cache = getBibfilesCache();
2163 FileNameList::const_iterator ei = bibfiles_cache.begin();
2164 FileNameList::const_iterator en = bibfiles_cache.end();
2165 for (; ei != en; ++ ei) {
2166 time_t lastw = ei->lastModified();
2167 time_t prevw = d->bibfile_status_[*ei];
2168 if (lastw != prevw) {
2169 d->bibinfo_cache_valid_ = false;
2170 d->cite_labels_valid_ = false;
2171 d->bibfile_status_[*ei] = lastw;
2177 void Buffer::reloadBibInfoCache() const
2179 // use the master's cache
2180 Buffer const * const tmp = masterBuffer();
2182 tmp->reloadBibInfoCache();
2186 checkIfBibInfoCacheIsValid();
2187 if (d->bibinfo_cache_valid_)
2190 d->bibinfo_.clear();
2192 d->bibinfo_cache_valid_ = true;
2196 void Buffer::collectBibKeys() const
2198 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2199 it->collectBibKeys(it);
2203 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2205 Buffer const * tmp = masterBuffer();
2206 BiblioInfo & masterbi = (tmp == this) ?
2207 d->bibinfo_ : tmp->d->bibinfo_;
2208 masterbi.mergeBiblioInfo(bi);
2212 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2214 Buffer const * tmp = masterBuffer();
2215 BiblioInfo & masterbi = (tmp == this) ?
2216 d->bibinfo_ : tmp->d->bibinfo_;
2221 void Buffer::makeCitationLabels() const
2223 Buffer const * const master = masterBuffer();
2224 return d->bibinfo_.makeCitationLabels(*master);
2228 bool Buffer::citeLabelsValid() const
2230 return masterBuffer()->d->cite_labels_valid_;
2234 void Buffer::removeBiblioTempFiles() const
2236 // We remove files that contain LaTeX commands specific to the
2237 // particular bibliographic style being used, in order to avoid
2238 // LaTeX errors when we switch style.
2239 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2240 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2241 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2242 aux_file.removeFile();
2243 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2244 bbl_file.removeFile();
2245 // Also for the parent buffer
2246 Buffer const * const pbuf = parent();
2248 pbuf->removeBiblioTempFiles();
2252 bool Buffer::isDepClean(string const & name) const
2254 DepClean::const_iterator const it = d->dep_clean.find(name);
2255 if (it == d->dep_clean.end())
2261 void Buffer::markDepClean(string const & name)
2263 d->dep_clean[name] = true;
2267 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2270 // FIXME? if there is an Buffer LFUN that can be dispatched even
2271 // if internal, put a switch '(cmd.action)' here.
2277 switch (cmd.action()) {
2279 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2280 flag.setOnOff(isReadonly());
2283 // FIXME: There is need for a command-line import.
2284 //case LFUN_BUFFER_IMPORT:
2286 case LFUN_BUFFER_AUTO_SAVE:
2289 case LFUN_BUFFER_EXPORT_CUSTOM:
2290 // FIXME: Nothing to check here?
2293 case LFUN_BUFFER_EXPORT: {
2294 docstring const arg = cmd.argument();
2295 if (arg == "custom") {
2299 string format = to_utf8(arg);
2300 size_t pos = format.find(' ');
2301 if (pos != string::npos)
2302 format = format.substr(0, pos);
2303 enable = params().isExportable(format);
2305 flag.message(bformat(
2306 _("Don't know how to export to format: %1$s"), arg));
2310 case LFUN_BUFFER_CHKTEX:
2311 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2314 case LFUN_BUILD_PROGRAM:
2315 enable = params().isExportable("program");
2318 case LFUN_BRANCH_ACTIVATE:
2319 case LFUN_BRANCH_DEACTIVATE:
2320 case LFUN_BRANCH_MASTER_ACTIVATE:
2321 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2322 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2323 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2324 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2325 : params().branchlist();
2326 docstring const branchName = cmd.argument();
2327 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2331 case LFUN_BRANCH_ADD:
2332 case LFUN_BRANCHES_RENAME:
2333 case LFUN_BUFFER_PRINT:
2334 // if no Buffer is present, then of course we won't be called!
2337 case LFUN_BUFFER_LANGUAGE:
2338 enable = !isReadonly();
2344 flag.setEnabled(enable);
2349 void Buffer::dispatch(string const & command, DispatchResult & result)
2351 return dispatch(lyxaction.lookupFunc(command), result);
2355 // NOTE We can end up here even if we have no GUI, because we are called
2356 // by LyX::exec to handled command-line requests. So we may need to check
2357 // whether we have a GUI or not. The boolean use_gui holds this information.
2358 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2361 // FIXME? if there is an Buffer LFUN that can be dispatched even
2362 // if internal, put a switch '(cmd.action())' here.
2363 dr.dispatched(false);
2366 string const argument = to_utf8(func.argument());
2367 // We'll set this back to false if need be.
2368 bool dispatched = true;
2369 undo().beginUndoGroup();
2371 switch (func.action()) {
2372 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2373 if (lyxvc().inUse()) {
2374 string log = lyxvc().toggleReadOnly();
2379 setReadonly(!isReadonly());
2382 case LFUN_BUFFER_EXPORT: {
2383 ExportStatus const status = doExport(argument, false);
2384 dr.setError(status != ExportSuccess);
2385 if (status != ExportSuccess)
2386 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2391 case LFUN_BUILD_PROGRAM: {
2392 ExportStatus const status = doExport("program", true);
2393 dr.setError(status != ExportSuccess);
2394 if (status != ExportSuccess)
2395 dr.setMessage(_("Error generating literate programming code."));
2399 case LFUN_BUFFER_CHKTEX:
2403 case LFUN_BUFFER_EXPORT_CUSTOM: {
2405 string command = split(argument, format_name, ' ');
2406 Format const * format = formats.getFormat(format_name);
2408 lyxerr << "Format \"" << format_name
2409 << "\" not recognized!"
2414 // The name of the file created by the conversion process
2417 // Output to filename
2418 if (format->name() == "lyx") {
2419 string const latexname = latexName(false);
2420 filename = changeExtension(latexname,
2421 format->extension());
2422 filename = addName(temppath(), filename);
2424 if (!writeFile(FileName(filename)))
2428 doExport(format_name, true, filename);
2431 // Substitute $$FName for filename
2432 if (!contains(command, "$$FName"))
2433 command = "( " + command + " ) < $$FName";
2434 command = subst(command, "$$FName", filename);
2436 // Execute the command in the background
2438 call.startscript(Systemcall::DontWait, command, filePath());
2442 // FIXME: There is need for a command-line import.
2444 case LFUN_BUFFER_IMPORT:
2449 case LFUN_BUFFER_AUTO_SAVE:
2451 resetAutosaveTimers();
2454 case LFUN_BRANCH_ACTIVATE:
2455 case LFUN_BRANCH_DEACTIVATE:
2456 case LFUN_BRANCH_MASTER_ACTIVATE:
2457 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2458 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2459 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2460 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2463 docstring const branch_name = func.argument();
2464 // the case without a branch name is handled elsewhere
2465 if (branch_name.empty()) {
2469 Branch * branch = buf->params().branchlist().find(branch_name);
2471 LYXERR0("Branch " << branch_name << " does not exist.");
2473 docstring const msg =
2474 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2478 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2479 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2480 if (branch->isSelected() != activate) {
2481 buf->undo().recordUndoFullDocument(CursorData());
2482 branch->setSelected(activate);
2484 dr.screenUpdate(Update::Force);
2485 dr.forceBufferUpdate();
2490 case LFUN_BRANCH_ADD: {
2491 docstring branch_name = func.argument();
2492 if (branch_name.empty()) {
2496 BranchList & branch_list = params().branchlist();
2497 vector<docstring> const branches =
2498 getVectorFromString(branch_name, branch_list.separator());
2500 for (vector<docstring>::const_iterator it = branches.begin();
2501 it != branches.end(); ++it) {
2503 Branch * branch = branch_list.find(branch_name);
2505 LYXERR0("Branch " << branch_name << " already exists.");
2509 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2511 undo().recordUndoFullDocument(CursorData());
2512 branch_list.add(branch_name);
2513 branch = branch_list.find(branch_name);
2514 string const x11hexname = X11hexname(branch->color());
2515 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2516 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2518 dr.screenUpdate(Update::Force);
2526 case LFUN_BRANCHES_RENAME: {
2527 if (func.argument().empty())
2530 docstring const oldname = from_utf8(func.getArg(0));
2531 docstring const newname = from_utf8(func.getArg(1));
2532 InsetIterator it = inset_iterator_begin(inset());
2533 InsetIterator const end = inset_iterator_end(inset());
2534 bool success = false;
2535 for (; it != end; ++it) {
2536 if (it->lyxCode() == BRANCH_CODE) {
2537 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2538 if (ins.branch() == oldname) {
2539 undo().recordUndo(CursorData(it));
2540 ins.rename(newname);
2545 if (it->lyxCode() == INCLUDE_CODE) {
2546 // get buffer of external file
2547 InsetInclude const & ins =
2548 static_cast<InsetInclude const &>(*it);
2549 Buffer * child = ins.getChildBuffer();
2552 child->dispatch(func, dr);
2557 dr.screenUpdate(Update::Force);
2558 dr.forceBufferUpdate();
2563 case LFUN_BUFFER_PRINT: {
2564 // we'll assume there's a problem until we succeed
2566 string target = func.getArg(0);
2567 string target_name = func.getArg(1);
2568 string command = func.getArg(2);
2571 || target_name.empty()
2572 || command.empty()) {
2573 LYXERR0("Unable to parse " << func.argument());
2574 docstring const msg =
2575 bformat(_("Unable to parse \"%1$s\""), func.argument());
2579 if (target != "printer" && target != "file") {
2580 LYXERR0("Unrecognized target \"" << target << '"');
2581 docstring const msg =
2582 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2587 if (doExport("dvi", true) != ExportSuccess) {
2588 showPrintError(absFileName());
2589 dr.setMessage(_("Error exporting to DVI."));
2593 // Push directory path.
2594 string const path = temppath();
2595 // Prevent the compiler from optimizing away p
2599 // there are three cases here:
2600 // 1. we print to a file
2601 // 2. we print directly to a printer
2602 // 3. we print using a spool command (print to file first)
2605 string const dviname = changeExtension(latexName(true), "dvi");
2607 if (target == "printer") {
2608 if (!lyxrc.print_spool_command.empty()) {
2609 // case 3: print using a spool
2610 string const psname = changeExtension(dviname,".ps");
2611 command += ' ' + lyxrc.print_to_file
2614 + quoteName(dviname);
2616 string command2 = lyxrc.print_spool_command + ' ';
2617 if (target_name != "default") {
2618 command2 += lyxrc.print_spool_printerprefix
2622 command2 += quoteName(psname);
2624 // If successful, then spool command
2625 res = one.startscript(Systemcall::Wait, command,
2629 // If there's no GUI, we have to wait on this command. Otherwise,
2630 // LyX deletes the temporary directory, and with it the spooled
2631 // file, before it can be printed!!
2632 Systemcall::Starttype stype = use_gui ?
2633 Systemcall::DontWait : Systemcall::Wait;
2634 res = one.startscript(stype, command2,
2638 // case 2: print directly to a printer
2639 if (target_name != "default")
2640 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2642 Systemcall::Starttype stype = use_gui ?
2643 Systemcall::DontWait : Systemcall::Wait;
2644 res = one.startscript(stype, command +
2645 quoteName(dviname), filePath());
2649 // case 1: print to a file
2650 FileName const filename(makeAbsPath(target_name, filePath()));
2651 FileName const dvifile(makeAbsPath(dviname, path));
2652 if (filename.exists()) {
2653 docstring text = bformat(
2654 _("The file %1$s already exists.\n\n"
2655 "Do you want to overwrite that file?"),
2656 makeDisplayPath(filename.absFileName()));
2657 if (Alert::prompt(_("Overwrite file?"),
2658 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2661 command += ' ' + lyxrc.print_to_file
2662 + quoteName(filename.toFilesystemEncoding())
2664 + quoteName(dvifile.toFilesystemEncoding());
2666 Systemcall::Starttype stype = use_gui ?
2667 Systemcall::DontWait : Systemcall::Wait;
2668 res = one.startscript(stype, command, filePath());
2674 dr.setMessage(_("Error running external commands."));
2675 showPrintError(absFileName());
2684 dr.dispatched(dispatched);
2685 undo().endUndoGroup();
2689 void Buffer::changeLanguage(Language const * from, Language const * to)
2691 LASSERT(from, return);
2692 LASSERT(to, return);
2694 for_each(par_iterator_begin(),
2696 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2700 bool Buffer::isMultiLingual() const
2702 ParConstIterator end = par_iterator_end();
2703 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2704 if (it->isMultiLingual(params()))
2711 std::set<Language const *> Buffer::getLanguages() const
2713 std::set<Language const *> languages;
2714 getLanguages(languages);
2719 void Buffer::getLanguages(std::set<Language const *> & languages) const
2721 ParConstIterator end = par_iterator_end();
2722 // add the buffer language, even if it's not actively used
2723 languages.insert(language());
2724 // iterate over the paragraphs
2725 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2726 it->getLanguages(languages);
2728 ListOfBuffers clist = getDescendents();
2729 ListOfBuffers::const_iterator cit = clist.begin();
2730 ListOfBuffers::const_iterator const cen = clist.end();
2731 for (; cit != cen; ++cit)
2732 (*cit)->getLanguages(languages);
2736 DocIterator Buffer::getParFromID(int const id) const
2738 Buffer * buf = const_cast<Buffer *>(this);
2740 // John says this is called with id == -1 from undo
2741 lyxerr << "getParFromID(), id: " << id << endl;
2742 return doc_iterator_end(buf);
2745 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2746 if (it.paragraph().id() == id)
2749 return doc_iterator_end(buf);
2753 bool Buffer::hasParWithID(int const id) const
2755 return !getParFromID(id).atEnd();
2759 ParIterator Buffer::par_iterator_begin()
2761 return ParIterator(doc_iterator_begin(this));
2765 ParIterator Buffer::par_iterator_end()
2767 return ParIterator(doc_iterator_end(this));
2771 ParConstIterator Buffer::par_iterator_begin() const
2773 return ParConstIterator(doc_iterator_begin(this));
2777 ParConstIterator Buffer::par_iterator_end() const
2779 return ParConstIterator(doc_iterator_end(this));
2783 Language const * Buffer::language() const
2785 return params().language;
2789 docstring const Buffer::B_(string const & l10n) const
2791 return params().B_(l10n);
2795 bool Buffer::isClean() const
2797 return d->lyx_clean;
2801 bool Buffer::isExternallyModified(CheckMethod method) const
2803 LASSERT(d->filename.exists(), return false);
2804 // if method == timestamp, check timestamp before checksum
2805 return (method == checksum_method
2806 || d->timestamp_ != d->filename.lastModified())
2807 && d->checksum_ != d->filename.checksum();
2811 void Buffer::saveCheckSum() const
2813 FileName const & file = d->filename;
2816 if (file.exists()) {
2817 d->timestamp_ = file.lastModified();
2818 d->checksum_ = file.checksum();
2820 // in the case of save to a new file.
2827 void Buffer::markClean() const
2829 if (!d->lyx_clean) {
2830 d->lyx_clean = true;
2833 // if the .lyx file has been saved, we don't need an
2835 d->bak_clean = true;
2836 d->undo_.markDirty();
2840 void Buffer::setUnnamed(bool flag)
2846 bool Buffer::isUnnamed() const
2853 /// Don't check unnamed, here: isInternal() is used in
2854 /// newBuffer(), where the unnamed flag has not been set by anyone
2855 /// yet. Also, for an internal buffer, there should be no need for
2856 /// retrieving fileName() nor for checking if it is unnamed or not.
2857 bool Buffer::isInternal() const
2859 return d->internal_buffer;
2863 void Buffer::setInternal(bool flag)
2865 d->internal_buffer = flag;
2869 void Buffer::markDirty()
2872 d->lyx_clean = false;
2875 d->bak_clean = false;
2877 DepClean::iterator it = d->dep_clean.begin();
2878 DepClean::const_iterator const end = d->dep_clean.end();
2880 for (; it != end; ++it)
2885 FileName Buffer::fileName() const
2891 string Buffer::absFileName() const
2893 return d->filename.absFileName();
2897 string Buffer::filePath() const
2899 string const abs = d->filename.onlyPath().absFileName();
2902 int last = abs.length() - 1;
2904 return abs[last] == '/' ? abs : abs + '/';
2908 bool Buffer::isReadonly() const
2910 return d->read_only;
2914 void Buffer::setParent(Buffer const * buffer)
2916 // Avoids recursive include.
2917 d->setParent(buffer == this ? 0 : buffer);
2922 Buffer const * Buffer::parent() const
2928 ListOfBuffers Buffer::allRelatives() const
2930 ListOfBuffers lb = masterBuffer()->getDescendents();
2931 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2936 Buffer const * Buffer::masterBuffer() const
2938 // FIXME Should be make sure we are not in some kind
2939 // of recursive include? A -> B -> A will crash this.
2940 Buffer const * const pbuf = d->parent();
2944 return pbuf->masterBuffer();
2948 bool Buffer::isChild(Buffer * child) const
2950 return d->children_positions.find(child) != d->children_positions.end();
2954 DocIterator Buffer::firstChildPosition(Buffer const * child)
2956 Impl::BufferPositionMap::iterator it;
2957 it = d->children_positions.find(child);
2958 if (it == d->children_positions.end())
2959 return DocIterator(this);
2964 bool Buffer::hasChildren() const
2966 return !d->children_positions.empty();
2970 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2972 // loop over children
2973 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2974 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2975 for (; it != end; ++it) {
2976 Buffer * child = const_cast<Buffer *>(it->first);
2978 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2979 if (bit != clist.end())
2981 clist.push_back(child);
2983 // there might be grandchildren
2984 child->collectChildren(clist, true);
2989 ListOfBuffers Buffer::getChildren() const
2992 collectChildren(v, false);
2993 // Make sure we have not included ourselves.
2994 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2995 if (bit != v.end()) {
2996 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3003 ListOfBuffers Buffer::getDescendents() const
3006 collectChildren(v, true);
3007 // Make sure we have not included ourselves.
3008 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3009 if (bit != v.end()) {
3010 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3017 template<typename M>
3018 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3023 typename M::const_iterator it = m.lower_bound(x);
3024 if (it == m.begin())
3032 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3033 DocIterator const & pos) const
3035 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3037 // if paragraphs have no macro context set, pos will be empty
3041 // we haven't found anything yet
3042 DocIterator bestPos = owner_->par_iterator_begin();
3043 MacroData const * bestData = 0;
3045 // find macro definitions for name
3046 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3047 if (nameIt != macros.end()) {
3048 // find last definition in front of pos or at pos itself
3049 PositionScopeMacroMap::const_iterator it
3050 = greatest_below(nameIt->second, pos);
3051 if (it != nameIt->second.end()) {
3053 // scope ends behind pos?
3054 if (pos < it->second.first) {
3055 // Looks good, remember this. If there
3056 // is no external macro behind this,
3057 // we found the right one already.
3058 bestPos = it->first;
3059 bestData = &it->second.second;
3063 // try previous macro if there is one
3064 if (it == nameIt->second.begin())
3071 // find macros in included files
3072 PositionScopeBufferMap::const_iterator it
3073 = greatest_below(position_to_children, pos);
3074 if (it == position_to_children.end())
3075 // no children before
3079 // do we know something better (i.e. later) already?
3080 if (it->first < bestPos )
3083 // scope ends behind pos?
3084 if (pos < it->second.first
3085 && (cloned_buffer_ ||
3086 theBufferList().isLoaded(it->second.second))) {
3087 // look for macro in external file
3089 MacroData const * data
3090 = it->second.second->getMacro(name, false);
3093 bestPos = it->first;
3099 // try previous file if there is one
3100 if (it == position_to_children.begin())
3105 // return the best macro we have found
3110 MacroData const * Buffer::getMacro(docstring const & name,
3111 DocIterator const & pos, bool global) const
3116 // query buffer macros
3117 MacroData const * data = d->getBufferMacro(name, pos);
3121 // If there is a master buffer, query that
3122 Buffer const * const pbuf = d->parent();
3124 d->macro_lock = true;
3125 MacroData const * macro = pbuf->getMacro(
3126 name, *this, false);
3127 d->macro_lock = false;
3133 data = MacroTable::globalMacros().get(name);
3142 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3144 // set scope end behind the last paragraph
3145 DocIterator scope = par_iterator_begin();
3146 scope.pit() = scope.lastpit() + 1;
3148 return getMacro(name, scope, global);
3152 MacroData const * Buffer::getMacro(docstring const & name,
3153 Buffer const & child, bool global) const
3155 // look where the child buffer is included first
3156 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3157 if (it == d->children_positions.end())
3160 // check for macros at the inclusion position
3161 return getMacro(name, it->second, global);
3165 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3167 pit_type const lastpit = it.lastpit();
3169 // look for macros in each paragraph
3170 while (it.pit() <= lastpit) {
3171 Paragraph & par = it.paragraph();
3173 // iterate over the insets of the current paragraph
3174 InsetList const & insets = par.insetList();
3175 InsetList::const_iterator iit = insets.begin();
3176 InsetList::const_iterator end = insets.end();
3177 for (; iit != end; ++iit) {
3178 it.pos() = iit->pos;
3180 // is it a nested text inset?
3181 if (iit->inset->asInsetText()) {
3182 // Inset needs its own scope?
3183 InsetText const * itext = iit->inset->asInsetText();
3184 bool newScope = itext->isMacroScope();
3186 // scope which ends just behind the inset
3187 DocIterator insetScope = it;
3190 // collect macros in inset
3191 it.push_back(CursorSlice(*iit->inset));
3192 updateMacros(it, newScope ? insetScope : scope);
3197 if (iit->inset->asInsetTabular()) {
3198 CursorSlice slice(*iit->inset);
3199 size_t const numcells = slice.nargs();
3200 for (; slice.idx() < numcells; slice.forwardIdx()) {
3201 it.push_back(slice);
3202 updateMacros(it, scope);
3208 // is it an external file?
3209 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3210 // get buffer of external file
3211 InsetInclude const & inset =
3212 static_cast<InsetInclude const &>(*iit->inset);
3214 Buffer * child = inset.getChildBuffer();
3219 // register its position, but only when it is
3220 // included first in the buffer
3221 if (children_positions.find(child) ==
3222 children_positions.end())
3223 children_positions[child] = it;
3225 // register child with its scope
3226 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3230 InsetMath * im = iit->inset->asInsetMath();
3231 if (doing_export && im) {
3232 InsetMathHull * hull = im->asHullInset();
3234 hull->recordLocation(it);
3237 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3241 MathMacroTemplate & macroTemplate =
3242 *iit->inset->asInsetMath()->asMacroTemplate();
3243 MacroContext mc(owner_, it);
3244 macroTemplate.updateToContext(mc);
3247 bool valid = macroTemplate.validMacro();
3248 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3249 // then the BufferView's cursor will be invalid in
3250 // some cases which leads to crashes.
3255 // FIXME (Abdel), I don't understandt why we pass 'it' here
3256 // instead of 'macroTemplate' defined above... is this correct?
3257 macros[macroTemplate.name()][it] =
3258 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3268 void Buffer::updateMacros() const
3273 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3275 // start with empty table
3277 d->children_positions.clear();
3278 d->position_to_children.clear();
3280 // Iterate over buffer, starting with first paragraph
3281 // The scope must be bigger than any lookup DocIterator
3282 // later. For the global lookup, lastpit+1 is used, hence
3283 // we use lastpit+2 here.
3284 DocIterator it = par_iterator_begin();
3285 DocIterator outerScope = it;
3286 outerScope.pit() = outerScope.lastpit() + 2;
3287 d->updateMacros(it, outerScope);
3291 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3293 InsetIterator it = inset_iterator_begin(inset());
3294 InsetIterator const end = inset_iterator_end(inset());
3295 for (; it != end; ++it) {
3296 if (it->lyxCode() == BRANCH_CODE) {
3297 InsetBranch & br = static_cast<InsetBranch &>(*it);
3298 docstring const name = br.branch();
3299 if (!from_master && !params().branchlist().find(name))
3300 result.push_back(name);
3301 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3302 result.push_back(name);
3305 if (it->lyxCode() == INCLUDE_CODE) {
3306 // get buffer of external file
3307 InsetInclude const & ins =
3308 static_cast<InsetInclude const &>(*it);
3309 Buffer * child = ins.getChildBuffer();
3312 child->getUsedBranches(result, true);
3315 // remove duplicates
3320 void Buffer::updateMacroInstances(UpdateType utype) const
3322 LYXERR(Debug::MACROS, "updateMacroInstances for "
3323 << d->filename.onlyFileName());
3324 DocIterator it = doc_iterator_begin(this);
3326 DocIterator const end = doc_iterator_end(this);
3327 for (; it != end; it.forwardInset()) {
3328 // look for MathData cells in InsetMathNest insets
3329 InsetMath * minset = it.nextInset()->asInsetMath();
3333 // update macro in all cells of the InsetMathNest
3334 DocIterator::idx_type n = minset->nargs();
3335 MacroContext mc = MacroContext(this, it);
3336 for (DocIterator::idx_type i = 0; i < n; ++i) {
3337 MathData & data = minset->cell(i);
3338 data.updateMacros(0, mc, utype);
3344 void Buffer::listMacroNames(MacroNameSet & macros) const
3349 d->macro_lock = true;
3351 // loop over macro names
3352 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3353 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3354 for (; nameIt != nameEnd; ++nameIt)
3355 macros.insert(nameIt->first);
3357 // loop over children
3358 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3359 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3360 for (; it != end; ++it)
3361 it->first->listMacroNames(macros);
3364 Buffer const * const pbuf = d->parent();
3366 pbuf->listMacroNames(macros);
3368 d->macro_lock = false;
3372 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3374 Buffer const * const pbuf = d->parent();
3379 pbuf->listMacroNames(names);
3382 MacroNameSet::iterator it = names.begin();
3383 MacroNameSet::iterator end = names.end();
3384 for (; it != end; ++it) {
3386 MacroData const * data =
3387 pbuf->getMacro(*it, *this, false);
3389 macros.insert(data);
3391 // we cannot access the original MathMacroTemplate anymore
3392 // here to calls validate method. So we do its work here manually.
3393 // FIXME: somehow make the template accessible here.
3394 if (data->optionals() > 0)
3395 features.require("xargs");
3401 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3404 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3406 RefCache::iterator it = d->ref_cache_.find(label);
3407 if (it != d->ref_cache_.end())
3408 return it->second.second;
3410 static InsetLabel const * dummy_il = 0;
3411 static References const dummy_refs;
3412 it = d->ref_cache_.insert(
3413 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3414 return it->second.second;
3418 Buffer::References const & Buffer::references(docstring const & label) const
3420 return const_cast<Buffer *>(this)->getReferenceCache(label);
3424 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3426 References & refs = getReferenceCache(label);
3427 refs.push_back(make_pair(inset, it));
3431 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3433 masterBuffer()->d->ref_cache_[label].first = il;
3437 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3439 return masterBuffer()->d->ref_cache_[label].first;
3443 void Buffer::clearReferenceCache() const
3446 d->ref_cache_.clear();
3450 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3452 //FIXME: This does not work for child documents yet.
3453 reloadBibInfoCache();
3455 // Check if the label 'from' appears more than once
3456 BiblioInfo const & keys = masterBibInfo();
3457 BiblioInfo::const_iterator bit = keys.begin();
3458 BiblioInfo::const_iterator bend = keys.end();
3459 vector<docstring> labels;
3461 for (; bit != bend; ++bit)
3463 labels.push_back(bit->first);
3465 if (count(labels.begin(), labels.end(), from) > 1)
3468 string const paramName = "key";
3469 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3470 if (it->lyxCode() != CITE_CODE)
3472 InsetCommand * inset = it->asInsetCommand();
3473 docstring const oldValue = inset->getParam(paramName);
3474 if (oldValue == from)
3475 inset->setParam(paramName, to);
3480 void Buffer::getSourceCode(odocstream & os, string const format,
3481 pit_type par_begin, pit_type par_end,
3482 OutputWhat output, bool master) const
3484 OutputParams runparams(¶ms().encoding());
3485 runparams.nice = true;
3486 runparams.flavor = params().getOutputFlavor(format);
3487 runparams.linelen = lyxrc.plaintext_linelen;
3488 // No side effect of file copying and image conversion
3489 runparams.dryrun = true;
3491 if (output == CurrentParagraph) {
3492 runparams.par_begin = par_begin;
3493 runparams.par_end = par_end;
3494 if (par_begin + 1 == par_end) {
3496 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3500 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3501 convert<docstring>(par_begin),
3502 convert<docstring>(par_end - 1))
3505 // output paragraphs
3506 if (runparams.flavor == OutputParams::LYX) {
3507 Paragraph const & par = text().paragraphs()[par_begin];
3509 depth_type dt = par.getDepth();
3510 par.write(ods, params(), dt);
3511 os << from_utf8(ods.str());
3512 } else if (runparams.flavor == OutputParams::HTML) {
3514 setMathFlavor(runparams);
3515 xhtmlParagraphs(text(), *this, xs, runparams);
3516 } else if (runparams.flavor == OutputParams::TEXT) {
3518 // FIXME Handles only one paragraph, unlike the others.
3519 // Probably should have some routine with a signature like them.
3520 writePlaintextParagraph(*this,
3521 text().paragraphs()[par_begin], os, runparams, dummy);
3522 } else if (params().isDocBook()) {
3523 docbookParagraphs(text(), *this, os, runparams);
3525 // If we are previewing a paragraph, even if this is the
3526 // child of some other buffer, let's cut the link here,
3527 // so that no concurring settings from the master
3528 // (e.g. branch state) interfere (see #8101).
3530 d->ignore_parent = true;
3531 // We need to validate the Buffer params' features here
3532 // in order to know if we should output polyglossia
3533 // macros (instead of babel macros)
3534 LaTeXFeatures features(*this, params(), runparams);
3535 params().validate(features);
3536 runparams.use_polyglossia = features.usePolyglossia();
3541 // latex or literate
3542 otexstream ots(os, texrow);
3545 latexParagraphs(*this, text(), ots, runparams);
3547 // Restore the parenthood
3549 d->ignore_parent = false;
3553 if (output == FullSource)
3554 os << _("Preview source code");
3555 else if (output == OnlyPreamble)
3556 os << _("Preview preamble");
3557 else if (output == OnlyBody)
3558 os << _("Preview body");
3560 if (runparams.flavor == OutputParams::LYX) {
3562 if (output == FullSource)
3564 else if (output == OnlyPreamble)
3565 params().writeFile(ods);
3566 else if (output == OnlyBody)
3568 os << from_utf8(ods.str());
3569 } else if (runparams.flavor == OutputParams::HTML) {
3570 writeLyXHTMLSource(os, runparams, output);
3571 } else if (runparams.flavor == OutputParams::TEXT) {
3572 if (output == OnlyPreamble) {
3573 os << "% "<< _("Plain text does not have a preamble.");
3575 writePlaintextFile(*this, os, runparams);
3576 } else if (params().isDocBook()) {
3577 writeDocBookSource(os, absFileName(), runparams, output);
3579 // latex or literate
3581 d->texrow.newline();
3582 d->texrow.newline();
3583 otexstream ots(os, d->texrow);
3585 runparams.is_child = true;
3586 writeLaTeXSource(ots, string(), runparams, output);
3592 ErrorList & Buffer::errorList(string const & type) const
3594 return d->errorLists[type];
3598 void Buffer::updateTocItem(std::string const & type,
3599 DocIterator const & dit) const
3602 d->gui_->updateTocItem(type, dit);
3606 void Buffer::structureChanged() const
3609 d->gui_->structureChanged();
3613 void Buffer::errors(string const & err, bool from_master) const
3616 d->gui_->errors(err, from_master);
3620 void Buffer::message(docstring const & msg) const
3623 d->gui_->message(msg);
3627 void Buffer::setBusy(bool on) const
3630 d->gui_->setBusy(on);
3634 void Buffer::updateTitles() const
3637 d->wa_->updateTitles();
3641 void Buffer::resetAutosaveTimers() const
3644 d->gui_->resetAutosaveTimers();
3648 bool Buffer::hasGuiDelegate() const
3654 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3663 class AutoSaveBuffer : public ForkedProcess {
3666 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3667 : buffer_(buffer), fname_(fname) {}
3669 virtual shared_ptr<ForkedProcess> clone() const
3671 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3676 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3677 from_utf8(fname_.absFileName())));
3678 return run(DontWait);
3682 virtual int generateChild();
3684 Buffer const & buffer_;
3689 int AutoSaveBuffer::generateChild()
3691 #if defined(__APPLE__)
3692 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3693 * We should use something else like threads.
3695 * Since I do not know how to determine at run time what is the OS X
3696 * version, I just disable forking altogether for now (JMarc)
3698 pid_t const pid = -1;
3700 // tmp_ret will be located (usually) in /tmp
3701 // will that be a problem?
3702 // Note that this calls ForkedCalls::fork(), so it's
3703 // ok cross-platform.
3704 pid_t const pid = fork();
3705 // If you want to debug the autosave
3706 // you should set pid to -1, and comment out the fork.
3707 if (pid != 0 && pid != -1)
3711 // pid = -1 signifies that lyx was unable
3712 // to fork. But we will do the save
3714 bool failed = false;
3715 FileName const tmp_ret = FileName::tempName("lyxauto");
3716 if (!tmp_ret.empty()) {
3717 buffer_.writeFile(tmp_ret);
3718 // assume successful write of tmp_ret
3719 if (!tmp_ret.moveTo(fname_))
3725 // failed to write/rename tmp_ret so try writing direct
3726 if (!buffer_.writeFile(fname_)) {
3727 // It is dangerous to do this in the child,
3728 // but safe in the parent, so...
3729 if (pid == -1) // emit message signal.
3730 buffer_.message(_("Autosave failed!"));
3734 if (pid == 0) // we are the child so...
3743 FileName Buffer::getEmergencyFileName() const
3745 return FileName(d->filename.absFileName() + ".emergency");
3749 FileName Buffer::getAutosaveFileName() const
3751 // if the document is unnamed try to save in the backup dir, else
3752 // in the default document path, and as a last try in the filePath,
3753 // which will most often be the temporary directory
3756 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3757 : lyxrc.backupdir_path;
3758 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3761 string const fname = "#" + d->filename.onlyFileName() + "#";
3763 return makeAbsPath(fname, fpath);
3767 void Buffer::removeAutosaveFile() const
3769 FileName const f = getAutosaveFileName();
3775 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3777 FileName const newauto = getAutosaveFileName();
3779 if (newauto != oldauto && oldauto.exists())
3780 if (!oldauto.moveTo(newauto))
3781 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3785 bool Buffer::autoSave() const
3787 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3788 if (buf->d->bak_clean || isReadonly())
3791 message(_("Autosaving current document..."));
3792 buf->d->bak_clean = true;
3794 FileName const fname = getAutosaveFileName();
3795 LASSERT(d->cloned_buffer_, return false);
3797 // If this buffer is cloned, we assume that
3798 // we are running in a separate thread already.
3799 FileName const tmp_ret = FileName::tempName("lyxauto");
3800 if (!tmp_ret.empty()) {
3802 // assume successful write of tmp_ret
3803 if (tmp_ret.moveTo(fname))
3806 // failed to write/rename tmp_ret so try writing direct
3807 return writeFile(fname);
3811 void Buffer::setExportStatus(bool e) const
3813 d->doing_export = e;
3814 ListOfBuffers clist = getDescendents();
3815 ListOfBuffers::const_iterator cit = clist.begin();
3816 ListOfBuffers::const_iterator const cen = clist.end();
3817 for (; cit != cen; ++cit)
3818 (*cit)->d->doing_export = e;
3822 bool Buffer::isExporting() const
3824 return d->doing_export;
3828 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3832 return doExport(target, put_in_tempdir, result_file);
3835 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3836 string & result_file) const
3838 bool const update_unincluded =
3839 params().maintain_unincluded_children
3840 && !params().getIncludedChildren().empty();
3842 // (1) export with all included children (omit \includeonly)
3843 if (update_unincluded) {
3844 ExportStatus const status =
3845 doExport(target, put_in_tempdir, true, result_file);
3846 if (status != ExportSuccess)
3849 // (2) export with included children only
3850 return doExport(target, put_in_tempdir, false, result_file);
3854 void Buffer::setMathFlavor(OutputParams & op) const
3856 switch (params().html_math_output) {
3857 case BufferParams::MathML:
3858 op.math_flavor = OutputParams::MathAsMathML;
3860 case BufferParams::HTML:
3861 op.math_flavor = OutputParams::MathAsHTML;
3863 case BufferParams::Images:
3864 op.math_flavor = OutputParams::MathAsImages;
3866 case BufferParams::LaTeX:
3867 op.math_flavor = OutputParams::MathAsLaTeX;
3873 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3874 bool includeall, string & result_file) const
3876 LYXERR(Debug::FILES, "target=" << target);
3877 OutputParams runparams(¶ms().encoding());
3878 string format = target;
3879 string dest_filename;
3880 size_t pos = target.find(' ');
3881 if (pos != string::npos) {
3882 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3883 format = target.substr(0, pos);
3884 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3885 FileName(dest_filename).onlyPath().createPath();
3886 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3888 MarkAsExporting exporting(this);
3889 string backend_format;
3890 runparams.flavor = OutputParams::LATEX;
3891 runparams.linelen = lyxrc.plaintext_linelen;
3892 runparams.includeall = includeall;
3893 vector<string> backs = params().backends();
3894 Converters converters = theConverters();
3895 bool need_nice_file = false;
3896 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3897 // Get shortest path to format
3898 converters.buildGraph();
3899 Graph::EdgePath path;
3900 for (vector<string>::const_iterator it = backs.begin();
3901 it != backs.end(); ++it) {
3902 Graph::EdgePath p = converters.getPath(*it, format);
3903 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3904 backend_format = *it;
3909 if (!put_in_tempdir) {
3910 // Only show this alert if this is an export to a non-temporary
3911 // file (not for previewing).
3912 Alert::error(_("Couldn't export file"), bformat(
3913 _("No information for exporting the format %1$s."),
3914 formats.prettyName(format)));
3916 return ExportNoPathToFormat;
3918 runparams.flavor = converters.getFlavor(path, this);
3919 Graph::EdgePath::const_iterator it = path.begin();
3920 Graph::EdgePath::const_iterator en = path.end();
3921 for (; it != en; ++it)
3922 if (theConverters().get(*it).nice) {
3923 need_nice_file = true;
3928 backend_format = format;
3929 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3930 // FIXME: Don't hardcode format names here, but use a flag
3931 if (backend_format == "pdflatex")
3932 runparams.flavor = OutputParams::PDFLATEX;
3933 else if (backend_format == "luatex")
3934 runparams.flavor = OutputParams::LUATEX;
3935 else if (backend_format == "dviluatex")
3936 runparams.flavor = OutputParams::DVILUATEX;
3937 else if (backend_format == "xetex")
3938 runparams.flavor = OutputParams::XETEX;
3941 string filename = latexName(false);
3942 filename = addName(temppath(), filename);
3943 filename = changeExtension(filename,
3944 formats.extension(backend_format));
3945 LYXERR(Debug::FILES, "filename=" << filename);
3947 // Plain text backend
3948 if (backend_format == "text") {
3949 runparams.flavor = OutputParams::TEXT;
3950 writePlaintextFile(*this, FileName(filename), runparams);
3953 else if (backend_format == "xhtml") {
3954 runparams.flavor = OutputParams::HTML;
3955 setMathFlavor(runparams);
3956 makeLyXHTMLFile(FileName(filename), runparams);
3957 } else if (backend_format == "lyx")
3958 writeFile(FileName(filename));
3960 else if (params().isDocBook()) {
3961 runparams.nice = !put_in_tempdir;
3962 makeDocBookFile(FileName(filename), runparams);
3965 else if (backend_format == format || need_nice_file) {
3966 runparams.nice = true;
3967 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3968 if (d->cloned_buffer_)
3969 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3972 } else if (!lyxrc.tex_allows_spaces
3973 && contains(filePath(), ' ')) {
3974 Alert::error(_("File name error"),
3975 _("The directory path to the document cannot contain spaces."));
3976 return ExportTexPathHasSpaces;
3978 runparams.nice = false;
3979 bool const success = makeLaTeXFile(
3980 FileName(filename), filePath(), runparams);
3981 if (d->cloned_buffer_)
3982 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3987 string const error_type = (format == "program")
3988 ? "Build" : params().bufferFormat();
3989 ErrorList & error_list = d->errorLists[error_type];
3990 string const ext = formats.extension(format);
3991 FileName const tmp_result_file(changeExtension(filename, ext));
3992 bool const success = converters.convert(this, FileName(filename),
3993 tmp_result_file, FileName(absFileName()), backend_format, format,
3996 // Emit the signal to show the error list or copy it back to the
3997 // cloned Buffer so that it can be emitted afterwards.
3998 if (format != backend_format) {
3999 if (runparams.silent)
4001 else if (d->cloned_buffer_)
4002 d->cloned_buffer_->d->errorLists[error_type] =
4003 d->errorLists[error_type];
4006 // also to the children, in case of master-buffer-view
4007 ListOfBuffers clist = getDescendents();
4008 ListOfBuffers::const_iterator cit = clist.begin();
4009 ListOfBuffers::const_iterator const cen = clist.end();
4010 for (; cit != cen; ++cit) {
4011 if (runparams.silent)
4012 (*cit)->d->errorLists[error_type].clear();
4013 else if (d->cloned_buffer_) {
4014 // Enable reverse search by copying back the
4015 // texrow object to the cloned buffer.
4016 // FIXME: this is not thread safe.
4017 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4018 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4019 (*cit)->d->errorLists[error_type];
4021 (*cit)->errors(error_type, true);
4025 if (d->cloned_buffer_) {
4026 // Enable reverse dvi or pdf to work by copying back the texrow
4027 // object to the cloned buffer.
4028 // FIXME: There is a possibility of concurrent access to texrow
4029 // here from the main GUI thread that should be securized.
4030 d->cloned_buffer_->d->texrow = d->texrow;
4031 string const error_type = params().bufferFormat();
4032 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4036 return ExportConverterError;
4038 if (put_in_tempdir) {
4039 result_file = tmp_result_file.absFileName();
4040 return ExportSuccess;
4043 if (dest_filename.empty())
4044 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4046 result_file = dest_filename;
4047 // We need to copy referenced files (e. g. included graphics
4048 // if format == "dvi") to the result dir.
4049 vector<ExportedFile> const files =
4050 runparams.exportdata->externalFiles(format);
4051 string const dest = runparams.export_folder.empty() ?
4052 onlyPath(result_file) : runparams.export_folder;
4053 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4054 : force_overwrite == ALL_FILES;
4055 CopyStatus status = use_force ? FORCE : SUCCESS;
4057 vector<ExportedFile>::const_iterator it = files.begin();
4058 vector<ExportedFile>::const_iterator const en = files.end();
4059 for (; it != en && status != CANCEL; ++it) {
4060 string const fmt = formats.getFormatFromFile(it->sourceName);
4061 string fixedName = it->exportName;
4062 if (!runparams.export_folder.empty()) {
4063 // Relative pathnames starting with ../ will be sanitized
4064 // if exporting to a different folder
4065 while (fixedName.substr(0, 3) == "../")
4066 fixedName = fixedName.substr(3, fixedName.length() - 3);
4068 FileName fixedFileName = makeAbsPath(fixedName, dest);
4069 fixedFileName.onlyPath().createPath();
4070 status = copyFile(fmt, it->sourceName,
4072 it->exportName, status == FORCE,
4073 runparams.export_folder.empty());
4076 if (status == CANCEL) {
4077 message(_("Document export cancelled."));
4078 return ExportCancel;
4081 if (tmp_result_file.exists()) {
4082 // Finally copy the main file
4083 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4084 : force_overwrite != NO_FILES;
4085 if (status == SUCCESS && use_force)
4087 status = copyFile(format, tmp_result_file,
4088 FileName(result_file), result_file,
4090 if (status == CANCEL) {
4091 message(_("Document export cancelled."));
4092 return ExportCancel;
4094 message(bformat(_("Document exported as %1$s "
4096 formats.prettyName(format),
4097 makeDisplayPath(result_file)));
4100 // This must be a dummy converter like fax (bug 1888)
4101 message(bformat(_("Document exported as %1$s"),
4102 formats.prettyName(format)));
4105 return ExportSuccess;
4109 Buffer::ExportStatus Buffer::preview(string const & format) const
4111 bool const update_unincluded =
4112 params().maintain_unincluded_children
4113 && !params().getIncludedChildren().empty();
4114 return preview(format, update_unincluded);
4117 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4119 MarkAsExporting exporting(this);
4121 // (1) export with all included children (omit \includeonly)
4123 ExportStatus const status = doExport(format, true, true, result_file);
4124 if (status != ExportSuccess)
4127 // (2) export with included children only
4128 ExportStatus const status = doExport(format, true, false, result_file);
4129 if (status != ExportSuccess)
4131 if (!formats.view(*this, FileName(result_file), format))
4132 return PreviewError;
4133 return PreviewSuccess;
4137 Buffer::ReadStatus Buffer::extractFromVC()
4139 bool const found = LyXVC::file_not_found_hook(d->filename);
4141 return ReadFileNotFound;
4142 if (!d->filename.isReadableFile())
4148 Buffer::ReadStatus Buffer::loadEmergency()
4150 FileName const emergencyFile = getEmergencyFileName();
4151 if (!emergencyFile.exists()
4152 || emergencyFile.lastModified() <= d->filename.lastModified())
4153 return ReadFileNotFound;
4155 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4156 docstring const text = bformat(_("An emergency save of the document "
4157 "%1$s exists.\n\nRecover emergency save?"), file);
4159 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4160 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4166 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4167 bool const success = (ret_llf == ReadSuccess);
4170 Alert::warning(_("File is read-only"),
4171 bformat(_("An emergency file is successfully loaded, "
4172 "but the original file %1$s is marked read-only. "
4173 "Please make sure to save the document as a different "
4174 "file."), from_utf8(d->filename.absFileName())));
4177 lyxvc().file_found_hook(d->filename);
4178 str = _("Document was successfully recovered.");
4180 str = _("Document was NOT successfully recovered.");
4181 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4182 makeDisplayPath(emergencyFile.absFileName()));
4184 int const del_emerg =
4185 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4186 _("&Remove"), _("&Keep"));
4187 if (del_emerg == 0) {
4188 emergencyFile.removeFile();
4190 Alert::warning(_("Emergency file deleted"),
4191 _("Do not forget to save your file now!"), true);
4193 return success ? ReadSuccess : ReadEmergencyFailure;
4196 int const del_emerg =
4197 Alert::prompt(_("Delete emergency file?"),
4198 _("Remove emergency file now?"), 1, 1,
4199 _("&Remove"), _("&Keep"));
4201 emergencyFile.removeFile();
4202 return ReadOriginal;
4212 Buffer::ReadStatus Buffer::loadAutosave()
4214 // Now check if autosave file is newer.
4215 FileName const autosaveFile = getAutosaveFileName();
4216 if (!autosaveFile.exists()
4217 || autosaveFile.lastModified() <= d->filename.lastModified())
4218 return ReadFileNotFound;
4220 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4221 docstring const text = bformat(_("The backup of the document %1$s "
4222 "is newer.\n\nLoad the backup instead?"), file);
4223 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4224 _("&Load backup"), _("Load &original"), _("&Cancel"));
4229 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4230 // the file is not saved if we load the autosave file.
4231 if (ret_llf == ReadSuccess) {
4233 Alert::warning(_("File is read-only"),
4234 bformat(_("A backup file is successfully loaded, "
4235 "but the original file %1$s is marked read-only. "
4236 "Please make sure to save the document as a "
4238 from_utf8(d->filename.absFileName())));
4241 lyxvc().file_found_hook(d->filename);
4244 return ReadAutosaveFailure;
4247 // Here we delete the autosave
4248 autosaveFile.removeFile();
4249 return ReadOriginal;
4257 Buffer::ReadStatus Buffer::loadLyXFile()
4259 if (!d->filename.isReadableFile()) {
4260 ReadStatus const ret_rvc = extractFromVC();
4261 if (ret_rvc != ReadSuccess)
4265 ReadStatus const ret_re = loadEmergency();
4266 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4269 ReadStatus const ret_ra = loadAutosave();
4270 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4273 return loadThisLyXFile(d->filename);
4277 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4279 return readFile(fn);
4283 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4285 TeXErrors::Errors::const_iterator it = terr.begin();
4286 TeXErrors::Errors::const_iterator end = terr.end();
4287 ListOfBuffers clist = getDescendents();
4288 ListOfBuffers::const_iterator cen = clist.end();
4290 for (; it != end; ++it) {
4293 int errorRow = it->error_in_line;
4294 Buffer const * buf = 0;
4296 if (it->child_name.empty())
4297 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4299 // The error occurred in a child
4300 ListOfBuffers::const_iterator cit = clist.begin();
4301 for (; cit != cen; ++cit) {
4302 string const child_name =
4303 DocFileName(changeExtension(
4304 (*cit)->absFileName(), "tex")).
4306 if (it->child_name != child_name)
4308 (*cit)->d->texrow.getIdFromRow(errorRow,
4309 id_start, pos_start);
4310 if (id_start != -1) {
4311 buf = d->cloned_buffer_
4312 ? (*cit)->d->cloned_buffer_->d->owner_
4313 : (*cit)->d->owner_;
4324 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4325 } while (found && id_start == id_end && pos_start == pos_end);
4327 if (id_start != id_end) {
4328 // Next registered position is outside the inset where
4329 // the error occurred, so signal end-of-paragraph
4333 errorList.push_back(ErrorItem(it->error_desc,
4334 it->error_text, id_start, pos_start, pos_end, buf));
4339 void Buffer::setBuffersForInsets() const
4341 inset().setBuffer(const_cast<Buffer &>(*this));
4345 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4347 LBUFERR(!text().paragraphs().empty());
4349 // Use the master text class also for child documents
4350 Buffer const * const master = masterBuffer();
4351 DocumentClass const & textclass = master->params().documentClass();
4353 // do this only if we are the top-level Buffer
4354 if (master == this) {
4355 textclass.counters().reset(from_ascii("bibitem"));
4356 reloadBibInfoCache();
4359 // keep the buffers to be children in this set. If the call from the
4360 // master comes back we can see which of them were actually seen (i.e.
4361 // via an InsetInclude). The remaining ones in the set need still be updated.
4362 static std::set<Buffer const *> bufToUpdate;
4363 if (scope == UpdateMaster) {
4364 // If this is a child document start with the master
4365 if (master != this) {
4366 bufToUpdate.insert(this);
4367 master->updateBuffer(UpdateMaster, utype);
4368 // If the master buffer has no gui associated with it, then the TocModel is
4369 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4370 // (bug 5699). The same happens if the master buffer is open in a different
4371 // window. This test catches both possibilities.
4372 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4373 // There remains a problem here: If there is another child open in yet a third
4374 // window, that TOC is not updated. So some more general solution is needed at
4376 if (master->d->gui_ != d->gui_)
4379 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4380 if (bufToUpdate.find(this) == bufToUpdate.end())
4384 // start over the counters in the master
4385 textclass.counters().reset();
4388 // update will be done below for this buffer
4389 bufToUpdate.erase(this);
4391 // update all caches
4392 clearReferenceCache();
4395 Buffer & cbuf = const_cast<Buffer &>(*this);
4398 ParIterator parit = cbuf.par_iterator_begin();
4399 updateBuffer(parit, utype);
4402 // TocBackend update will be done later.
4405 d->bibinfo_cache_valid_ = true;
4406 d->cite_labels_valid_ = true;
4407 cbuf.tocBackend().update(utype == OutputUpdate);
4408 if (scope == UpdateMaster)
4409 cbuf.structureChanged();
4413 static depth_type getDepth(DocIterator const & it)
4415 depth_type depth = 0;
4416 for (size_t i = 0 ; i < it.depth() ; ++i)
4417 if (!it[i].inset().inMathed())
4418 depth += it[i].paragraph().getDepth() + 1;
4419 // remove 1 since the outer inset does not count
4423 static depth_type getItemDepth(ParIterator const & it)
4425 Paragraph const & par = *it;
4426 LabelType const labeltype = par.layout().labeltype;
4428 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4431 // this will hold the lowest depth encountered up to now.
4432 depth_type min_depth = getDepth(it);
4433 ParIterator prev_it = it;
4436 --prev_it.top().pit();
4438 // start of nested inset: go to outer par
4440 if (prev_it.empty()) {
4441 // start of document: nothing to do
4446 // We search for the first paragraph with same label
4447 // that is not more deeply nested.
4448 Paragraph & prev_par = *prev_it;
4449 depth_type const prev_depth = getDepth(prev_it);
4450 if (labeltype == prev_par.layout().labeltype) {
4451 if (prev_depth < min_depth)
4452 return prev_par.itemdepth + 1;
4453 if (prev_depth == min_depth)
4454 return prev_par.itemdepth;
4456 min_depth = min(min_depth, prev_depth);
4457 // small optimization: if we are at depth 0, we won't
4458 // find anything else
4459 if (prev_depth == 0)
4465 static bool needEnumCounterReset(ParIterator const & it)
4467 Paragraph const & par = *it;
4468 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4469 depth_type const cur_depth = par.getDepth();
4470 ParIterator prev_it = it;
4471 while (prev_it.pit()) {
4472 --prev_it.top().pit();
4473 Paragraph const & prev_par = *prev_it;
4474 if (prev_par.getDepth() <= cur_depth)
4475 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4477 // start of nested inset: reset
4482 // set the label of a paragraph. This includes the counters.
4483 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4485 BufferParams const & bp = owner_->masterBuffer()->params();
4486 DocumentClass const & textclass = bp.documentClass();
4487 Paragraph & par = it.paragraph();
4488 Layout const & layout = par.layout();
4489 Counters & counters = textclass.counters();
4491 if (par.params().startOfAppendix()) {
4492 // We want to reset the counter corresponding to toplevel sectioning
4493 Layout const & lay = textclass.getTOCLayout();
4494 docstring const cnt = lay.counter;
4496 counters.reset(cnt);
4497 counters.appendix(true);
4499 par.params().appendix(counters.appendix());
4501 // Compute the item depth of the paragraph
4502 par.itemdepth = getItemDepth(it);
4504 if (layout.margintype == MARGIN_MANUAL) {
4505 if (par.params().labelWidthString().empty())
4506 par.params().labelWidthString(par.expandLabel(layout, bp));
4507 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4508 // we do not need to do anything here, since the empty case is
4509 // handled during export.
4511 par.params().labelWidthString(docstring());
4514 switch(layout.labeltype) {
4515 case LABEL_ITEMIZE: {
4516 // At some point of time we should do something more
4517 // clever here, like:
4518 // par.params().labelString(
4519 // bp.user_defined_bullet(par.itemdepth).getText());
4520 // for now, use a simple hardcoded label
4521 docstring itemlabel;
4522 switch (par.itemdepth) {
4524 itemlabel = char_type(0x2022);
4527 itemlabel = char_type(0x2013);
4530 itemlabel = char_type(0x2217);
4533 itemlabel = char_type(0x2219); // or 0x00b7
4536 par.params().labelString(itemlabel);
4540 case LABEL_ENUMERATE: {
4541 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4543 switch (par.itemdepth) {
4552 enumcounter += "iv";
4555 // not a valid enumdepth...
4559 // Maybe we have to reset the enumeration counter.
4560 if (needEnumCounterReset(it))
4561 counters.reset(enumcounter);
4562 counters.step(enumcounter, utype);
4564 string const & lang = par.getParLanguage(bp)->code();
4565 par.params().labelString(counters.theCounter(enumcounter, lang));
4570 case LABEL_SENSITIVE: {
4571 string const & type = counters.current_float();
4572 docstring full_label;
4574 full_label = owner_->B_("Senseless!!! ");
4576 docstring name = owner_->B_(textclass.floats().getType(type).name());
4577 if (counters.hasCounter(from_utf8(type))) {
4578 string const & lang = par.getParLanguage(bp)->code();
4579 counters.step(from_utf8(type), utype);
4580 full_label = bformat(from_ascii("%1$s %2$s:"),
4582 counters.theCounter(from_utf8(type), lang));
4584 full_label = bformat(from_ascii("%1$s #:"), name);
4586 par.params().labelString(full_label);
4590 case LABEL_NO_LABEL:
4591 par.params().labelString(docstring());
4595 case LABEL_CENTERED:
4596 case LABEL_STATIC: {
4597 docstring const & lcounter = layout.counter;
4598 if (!lcounter.empty()) {
4599 if (layout.toclevel <= bp.secnumdepth
4600 && (layout.latextype != LATEX_ENVIRONMENT
4601 || it.text()->isFirstInSequence(it.pit()))) {
4602 if (counters.hasCounter(lcounter))
4603 counters.step(lcounter, utype);
4604 par.params().labelString(par.expandLabel(layout, bp));
4606 par.params().labelString(docstring());
4608 par.params().labelString(par.expandLabel(layout, bp));
4614 par.params().labelString(par.expandLabel(layout, bp));
4619 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4621 // LASSERT: Is it safe to continue here, or should we just return?
4622 LASSERT(parit.pit() == 0, /**/);
4624 // Set the position of the text in the buffer to be able
4625 // to resolve macros in it.
4626 parit.text()->setMacrocontextPosition(parit);
4628 depth_type maxdepth = 0;
4629 pit_type const lastpit = parit.lastpit();
4630 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4631 // reduce depth if necessary
4632 if (parit->params().depth() > maxdepth) {
4633 /** FIXME: this function is const, but
4634 * nevertheless it modifies the buffer. To be
4635 * cleaner, one should modify the buffer in
4636 * another function, which is actually
4637 * non-const. This would however be costly in
4638 * terms of code duplication.
4640 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4641 parit->params().depth(maxdepth);
4643 maxdepth = parit->getMaxDepthAfter();
4645 if (utype == OutputUpdate) {
4646 // track the active counters
4647 // we have to do this for the master buffer, since the local
4648 // buffer isn't tracking anything.
4649 masterBuffer()->params().documentClass().counters().
4650 setActiveLayout(parit->layout());
4653 // set the counter for this paragraph
4654 d->setLabel(parit, utype);
4657 InsetList::const_iterator iit = parit->insetList().begin();
4658 InsetList::const_iterator end = parit->insetList().end();
4659 for (; iit != end; ++iit) {
4660 parit.pos() = iit->pos;
4661 iit->inset->updateBuffer(parit, utype);
4667 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4668 WordLangTuple & word_lang, docstring_list & suggestions) const
4672 suggestions.clear();
4673 word_lang = WordLangTuple();
4674 bool const to_end = to.empty();
4675 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4676 // OK, we start from here.
4677 for (; from != end; from.forwardPos()) {
4678 // We are only interested in text so remove the math CursorSlice.
4679 while (from.inMathed()) {
4683 // If from is at the end of the document (which is possible
4684 // when leaving the mathed) LyX will crash later otherwise.
4685 if (from.atEnd() || (!to_end && from >= end))
4688 from.paragraph().spellCheck();
4689 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4690 if (SpellChecker::misspelled(res)) {
4695 // Do not increase progress when from == to, otherwise the word
4696 // count will be wrong.
4706 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4708 bool inword = false;
4713 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4714 if (!dit.inTexted()) {
4719 Paragraph const & par = dit.paragraph();
4720 pos_type const pos = dit.pos();
4722 // Copied and adapted from isWordSeparator() in Paragraph
4723 if (pos == dit.lastpos()) {
4726 Inset const * ins = par.getInset(pos);
4727 if (ins && skipNoOutput && !ins->producesOutput()) {
4730 // stop if end of range was skipped
4731 if (!to.atEnd() && dit >= to)
4734 } else if (!par.isDeleted(pos)) {
4735 if (par.isWordSeparator(pos))
4741 if (ins && ins->isLetter())
4743 else if (ins && ins->isSpace())
4746 char_type const c = par.getChar(pos);
4747 if (isPrintableNonspace(c))
4749 else if (isSpace(c))
4759 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4761 d->updateStatistics(from, to, skipNoOutput);
4765 int Buffer::wordCount() const
4767 return d->wordCount();
4771 int Buffer::charCount(bool with_blanks) const
4773 return d->charCount(with_blanks);
4777 Buffer::ReadStatus Buffer::reload()
4780 // c.f. bug http://www.lyx.org/trac/ticket/6587
4781 removeAutosaveFile();
4782 // e.g., read-only status could have changed due to version control
4783 d->filename.refresh();
4784 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4786 // clear parent. this will get reset if need be.
4788 ReadStatus const status = loadLyXFile();
4789 if (status == ReadSuccess) {
4794 message(bformat(_("Document %1$s reloaded."), disp_fn));
4797 message(bformat(_("Could not reload document %1$s."), disp_fn));
4807 bool Buffer::saveAs(FileName const & fn)
4809 FileName const old_name = fileName();
4810 FileName const old_auto = getAutosaveFileName();
4811 bool const old_unnamed = isUnnamed();
4818 // bring the autosave file with us, just in case.
4819 moveAutosaveFile(old_auto);
4820 // validate version control data and
4821 // correct buffer title
4822 lyxvc().file_found_hook(fileName());
4824 // the file has now been saved to the new location.
4825 // we need to check that the locations of child buffers
4827 checkChildBuffers();
4828 checkMasterBuffer();
4832 // reset the old filename and unnamed state
4833 setFileName(old_name);
4834 setUnnamed(old_unnamed);
4840 // FIXME We could do better here, but it is complicated. What would be
4841 // nice is to offer either (a) to save the child buffer to an appropriate
4842 // location, so that it would "move with the master", or else (b) to update
4843 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4844 // complicated, because the code for this lives in GuiView.
4845 void Buffer::checkChildBuffers()
4847 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4848 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4849 for (; it != en; ++it) {
4850 DocIterator dit = it->second;
4851 Buffer * cbuf = const_cast<Buffer *>(it->first);
4852 if (!cbuf || !theBufferList().isLoaded(cbuf))
4854 Inset * inset = dit.nextInset();
4855 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4856 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4857 docstring const & incfile = inset_inc->getParam("filename");
4858 string oldloc = cbuf->absFileName();
4859 string newloc = makeAbsPath(to_utf8(incfile),
4860 onlyPath(absFileName())).absFileName();
4861 if (oldloc == newloc)
4863 // the location of the child file is incorrect.
4864 Alert::warning(_("Included File Invalid"),
4865 bformat(_("Saving this document to a new location has made the file:\n"
4867 "inaccessible. You will need to update the included filename."),
4868 from_utf8(oldloc)));
4870 inset_inc->setChildBuffer(0);
4872 // invalidate cache of children
4873 d->children_positions.clear();
4874 d->position_to_children.clear();
4878 // If a child has been saved under a different name/path, it might have been
4879 // orphaned. Therefore the master needs to be reset (bug 8161).
4880 void Buffer::checkMasterBuffer()
4882 Buffer const * const master = masterBuffer();
4886 // necessary to re-register the child (bug 5873)
4887 // FIXME: clean up updateMacros (here, only
4888 // child registering is needed).
4889 master->updateMacros();
4890 // (re)set master as master buffer, but only
4891 // if we are a real child
4892 if (master->isChild(this))