3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
25 #include "Converter.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
41 #include "LaTeXFeatures.h"
45 #include "LyXAction.h"
49 #include "output_docbook.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
81 #include "graphics/PreviewLoader.h"
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/os.h"
101 #include "support/Package.h"
102 #include "support/PathChanger.h"
103 #include "support/Systemcall.h"
104 #include "support/TempFile.h"
105 #include "support/textutils.h"
106 #include "support/types.h"
108 #include "support/bind.h"
109 #include "support/shared_ptr.h"
120 using namespace lyx::support;
121 using namespace lyx::graphics;
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135 void showPrintError(string const & name)
137 docstring str = bformat(_("Could not print the document %1$s.\n"
138 "Check that your printer is set up correctly."),
139 makeDisplayPath(name, 50));
140 Alert::error(_("Print document failed"), str);
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
153 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
157 delete preview_loader_;
165 /// search for macro in local (buffer) table or in children
166 MacroData const * getBufferMacro(docstring const & name,
167 DocIterator const & pos) const;
169 /// Update macro table starting with position of it \param it in some
171 void updateMacros(DocIterator & it, DocIterator & scope);
173 void setLabel(ParIterator & it, UpdateType utype) const;
175 /** If we have branches that use the file suffix
176 feature, return the file name with suffix appended.
178 support::FileName exportFileName() const;
185 mutable TexRow texrow;
187 /// need to regenerate .tex?
191 mutable bool lyx_clean;
193 /// is autosave needed?
194 mutable bool bak_clean;
196 /// is this an unnamed file (New...)?
199 /// is this an internal bufffer?
200 bool internal_buffer;
205 /// name of the file the buffer is associated with.
208 /** Set to true only when the file is fully loaded.
209 * Used to prevent the premature generation of previews
210 * and by the citation inset.
212 bool file_fully_loaded;
214 /// Ignore the parent (e.g. when exporting a child standalone)?
218 mutable TocBackend toc_backend;
221 typedef pair<DocIterator, MacroData> ScopeMacro;
222 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224 /// map from the macro name to the position map,
225 /// which maps the macro definition position to the scope and the MacroData.
226 NamePositionScopeMacroMap macros;
227 /// This seem to change the way Buffer::getMacro() works
228 mutable bool macro_lock;
230 /// positions of child buffers in the buffer
231 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234 /// position of children buffers in this buffer
235 BufferPositionMap children_positions;
236 /// map from children inclusion positions to their scope and their buffer
237 PositionScopeBufferMap position_to_children;
239 /// Container for all sort of Buffer dependant errors.
240 map<string, ErrorList> errorLists;
242 /// timestamp and checksum used to test if the file has been externally
243 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
245 unsigned long checksum_;
248 frontend::WorkAreaManager * wa_;
250 frontend::GuiBufferDelegate * gui_;
255 /// A cache for the bibfiles (including bibfiles of loaded child
256 /// documents), needed for appropriate update of natbib labels.
257 mutable support::FileNameList bibfiles_cache_;
259 // FIXME The caching mechanism could be improved. At present, we have a
260 // cache for each Buffer, that caches all the bibliography info for that
261 // Buffer. A more efficient solution would be to have a global cache per
262 // file, and then to construct the Buffer's bibinfo from that.
263 /// A cache for bibliography info
264 mutable BiblioInfo bibinfo_;
265 /// whether the bibinfo cache is valid
266 mutable bool bibinfo_cache_valid_;
267 /// whether the bibfile cache is valid
268 mutable bool bibfile_cache_valid_;
269 /// Cache of timestamps of .bib files
270 map<FileName, time_t> bibfile_status_;
271 /// Indicates whether the bibinfo has changed since the last time
272 /// we ran updateBuffer(), i.e., whether citation labels may need
274 mutable bool cite_labels_valid_;
276 mutable RefCache ref_cache_;
278 /// our Text that should be wrapped in an InsetText
282 PreviewLoader * preview_loader_;
284 /// This is here to force the test to be done whenever parent_buffer
286 Buffer const * parent() const
288 // ignore_parent temporarily "orphans" a buffer
289 // (e.g. if a child is compiled standalone)
292 // if parent_buffer is not loaded, then it has been unloaded,
293 // which means that parent_buffer is an invalid pointer. So we
294 // set it to null in that case.
295 // however, the BufferList doesn't know about cloned buffers, so
296 // they will always be regarded as unloaded. in that case, we hope
298 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
300 return parent_buffer;
304 void setParent(Buffer const * pb)
306 if (parent_buffer == pb)
309 if (!cloned_buffer_ && parent_buffer && pb)
310 LYXERR0("Warning: a buffer should not have two parents!");
312 if (!cloned_buffer_ && parent_buffer) {
313 parent_buffer->invalidateBibfileCache();
314 parent_buffer->invalidateBibinfoCache();
318 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
319 /// This one is useful for preview detached in a thread.
320 Buffer const * cloned_buffer_;
322 CloneList * clone_list_;
323 /// are we in the process of exporting this buffer?
324 mutable bool doing_export;
326 /// compute statistics
327 /// \p from initial position
328 /// \p to points to the end position
329 void updateStatistics(DocIterator & from, DocIterator & to,
330 bool skipNoOutput = true);
331 /// statistics accessor functions
332 int wordCount() const
336 int charCount(bool with_blanks) const
339 + (with_blanks ? blank_count_ : 0);
343 /// So we can force access via the accessors.
344 mutable Buffer const * parent_buffer;
353 /// Creates the per buffer temporary directory
354 static FileName createBufferTmpDir()
358 // We are in our own directory. Why bother to mangle name?
359 // In fact I wrote this code to circumvent a problematic behaviour
360 // (bug?) of EMX mkstemp().
361 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
362 convert<string>(count++));
364 if (!tmpfl.createDirectory(0777)) {
365 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
366 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
367 from_utf8(tmpfl.absFileName())));
373 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
374 Buffer const * cloned_buffer)
375 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
376 internal_buffer(false), read_only(readonly_), filename(file),
377 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
378 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
379 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
380 cite_labels_valid_(false), preview_loader_(0),
381 cloned_buffer_(cloned_buffer), clone_list_(0),
382 doing_export(false), parent_buffer(0)
384 if (!cloned_buffer_) {
385 temppath = createBufferTmpDir();
386 lyxvc.setBuffer(owner_);
388 wa_ = new frontend::WorkAreaManager;
391 temppath = cloned_buffer_->d->temppath;
392 file_fully_loaded = true;
393 params = cloned_buffer_->d->params;
394 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
395 bibinfo_ = cloned_buffer_->d->bibinfo_;
396 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
397 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
398 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
399 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
400 unnamed = cloned_buffer_->d->unnamed;
401 internal_buffer = cloned_buffer_->d->internal_buffer;
405 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
406 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
408 LYXERR(Debug::INFO, "Buffer::Buffer()");
410 d->inset = new InsetText(*cloned_buffer->d->inset);
411 d->inset->setBuffer(*this);
412 // FIXME: optimize this loop somewhat, maybe by creating a new
413 // general recursive Inset::setId().
414 DocIterator it = doc_iterator_begin(this);
415 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
416 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
417 it.paragraph().setId(cloned_it.paragraph().id());
419 d->inset = new InsetText(this);
420 d->inset->setAutoBreakRows(true);
421 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
427 LYXERR(Debug::INFO, "Buffer::~Buffer()");
428 // here the buffer should take care that it is
429 // saved properly, before it goes into the void.
431 // GuiView already destroyed
435 // No need to do additional cleanups for internal buffer.
441 // this is in case of recursive includes: we won't try to delete
442 // ourselves as a child.
443 d->clone_list_->erase(this);
444 // loop over children
445 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
446 Impl::BufferPositionMap::iterator end = d->children_positions.end();
447 for (; it != end; ++it) {
448 Buffer * child = const_cast<Buffer *>(it->first);
449 if (d->clone_list_->erase(child))
452 // if we're the master buffer, then we should get rid of the list
455 // If this is not empty, we have leaked something. Worse, one of the
456 // children still has a reference to this list. But we will try to
457 // continue, rather than shut down.
458 LATTEST(d->clone_list_->empty());
459 list<CloneList *>::iterator it =
460 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
461 if (it == cloned_buffers.end()) {
462 // We will leak in this case, but it is safe to continue.
465 cloned_buffers.erase(it);
466 delete d->clone_list_;
468 // FIXME Do we really need to do this right before we delete d?
469 // clear references to children in macro tables
470 d->children_positions.clear();
471 d->position_to_children.clear();
473 // loop over children
474 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
475 Impl::BufferPositionMap::iterator end = d->children_positions.end();
476 for (; it != end; ++it) {
477 Buffer * child = const_cast<Buffer *>(it->first);
478 if (theBufferList().isLoaded(child))
479 theBufferList().releaseChild(this, child);
483 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
484 msg += emergencyWrite();
485 Alert::warning(_("Attempting to close changed document!"), msg);
488 // FIXME Do we really need to do this right before we delete d?
489 // clear references to children in macro tables
490 d->children_positions.clear();
491 d->position_to_children.clear();
493 if (!d->temppath.destroyDirectory()) {
494 Alert::warning(_("Could not remove temporary directory"),
495 bformat(_("Could not remove the temporary directory %1$s"),
496 from_utf8(d->temppath.absFileName())));
505 Buffer * Buffer::cloneFromMaster() const
508 cloned_buffers.push_back(new CloneList);
509 CloneList * clones = cloned_buffers.back();
511 masterBuffer()->cloneWithChildren(bufmap, clones);
513 // make sure we got cloned
514 BufferMap::const_iterator bit = bufmap.find(this);
515 LASSERT(bit != bufmap.end(), return 0);
516 Buffer * cloned_buffer = bit->second;
518 return cloned_buffer;
522 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
524 // have we already been cloned?
525 if (bufmap.find(this) != bufmap.end())
528 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
530 // The clone needs its own DocumentClass, since running updateBuffer() will
531 // modify it, and we would otherwise be sharing it with the original Buffer.
532 buffer_clone->params().makeDocumentClass(true);
534 cap::switchBetweenClasses(
535 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
536 static_cast<InsetText &>(buffer_clone->inset()), el);
538 bufmap[this] = buffer_clone;
539 clones->insert(buffer_clone);
540 buffer_clone->d->clone_list_ = clones;
541 buffer_clone->d->macro_lock = true;
542 buffer_clone->d->children_positions.clear();
544 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
545 // math macro caches need to be rethought and simplified.
546 // I am not sure wether we should handle Buffer cloning here or in BufferList.
547 // Right now BufferList knows nothing about buffer clones.
548 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
549 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
550 for (; it != end; ++it) {
551 DocIterator dit = it->first.clone(buffer_clone);
552 dit.setBuffer(buffer_clone);
553 Buffer * child = const_cast<Buffer *>(it->second.second);
555 child->cloneWithChildren(bufmap, clones);
556 BufferMap::iterator const bit = bufmap.find(child);
557 LASSERT(bit != bufmap.end(), continue);
558 Buffer * child_clone = bit->second;
560 Inset * inset = dit.nextInset();
561 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
562 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
563 inset_inc->setChildBuffer(child_clone);
564 child_clone->d->setParent(buffer_clone);
565 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
566 buffer_clone->setChild(dit, child_clone);
568 buffer_clone->d->macro_lock = false;
573 Buffer * Buffer::cloneBufferOnly() const {
574 cloned_buffers.push_back(new CloneList);
575 CloneList * clones = cloned_buffers.back();
576 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
578 // The clone needs its own DocumentClass, since running updateBuffer() will
579 // modify it, and we would otherwise be sharing it with the original Buffer.
580 buffer_clone->params().makeDocumentClass(true);
582 cap::switchBetweenClasses(
583 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
584 static_cast<InsetText &>(buffer_clone->inset()), el);
586 clones->insert(buffer_clone);
587 buffer_clone->d->clone_list_ = clones;
589 // we won't be cloning the children
590 buffer_clone->d->children_positions.clear();
595 bool Buffer::isClone() const
597 return d->cloned_buffer_;
601 void Buffer::changed(bool update_metrics) const
604 d->wa_->redrawAll(update_metrics);
608 frontend::WorkAreaManager & Buffer::workAreaManager() const
615 Text & Buffer::text() const
617 return d->inset->text();
621 Inset & Buffer::inset() const
627 BufferParams & Buffer::params()
633 BufferParams const & Buffer::params() const
639 BufferParams const & Buffer::masterParams() const
641 if (masterBuffer() == this)
644 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
645 // Copy child authors to the params. We need those pointers.
646 AuthorList const & child_authors = params().authors();
647 AuthorList::Authors::const_iterator it = child_authors.begin();
648 for (; it != child_authors.end(); it++)
649 mparams.authors().record(*it);
654 ParagraphList & Buffer::paragraphs()
656 return text().paragraphs();
660 ParagraphList const & Buffer::paragraphs() const
662 return text().paragraphs();
666 LyXVC & Buffer::lyxvc()
672 LyXVC const & Buffer::lyxvc() const
678 string const Buffer::temppath() const
680 return d->temppath.absFileName();
684 TexRow & Buffer::texrow()
690 TexRow const & Buffer::texrow() const
696 TocBackend & Buffer::tocBackend() const
698 return d->toc_backend;
702 Undo & Buffer::undo()
708 void Buffer::setChild(DocIterator const & dit, Buffer * child)
710 d->children_positions[child] = dit;
714 string Buffer::latexName(bool const no_path) const
716 FileName latex_name =
717 makeLatexName(d->exportFileName());
718 return no_path ? latex_name.onlyFileName()
719 : latex_name.absFileName();
723 FileName Buffer::Impl::exportFileName() const
725 docstring const branch_suffix =
726 params.branchlist().getFileNameSuffix();
727 if (branch_suffix.empty())
730 string const name = filename.onlyFileNameWithoutExt()
731 + to_utf8(branch_suffix);
732 FileName res(filename.onlyPath().absFileName() + "/" + name);
733 res.changeExtension(filename.extension());
739 string Buffer::logName(LogType * type) const
741 string const filename = latexName(false);
743 if (filename.empty()) {
749 string const path = temppath();
751 FileName const fname(addName(temppath(),
752 onlyFileName(changeExtension(filename,
755 // FIXME: how do we know this is the name of the build log?
756 FileName const bname(
757 addName(path, onlyFileName(
758 changeExtension(filename,
759 formats.extension(params().bufferFormat()) + ".out"))));
761 // Also consider the master buffer log file
762 FileName masterfname = fname;
764 if (masterBuffer() != this) {
765 string const mlogfile = masterBuffer()->logName(&mtype);
766 masterfname = FileName(mlogfile);
769 // If no Latex log or Build log is newer, show Build log
770 if (bname.exists() &&
771 ((!fname.exists() && !masterfname.exists())
772 || (fname.lastModified() < bname.lastModified()
773 && masterfname.lastModified() < bname.lastModified()))) {
774 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
777 return bname.absFileName();
778 // If we have a newer master file log or only a master log, show this
779 } else if (fname != masterfname
780 && (!fname.exists() && (masterfname.exists()
781 || fname.lastModified() < masterfname.lastModified()))) {
782 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
785 return masterfname.absFileName();
787 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
790 return fname.absFileName();
794 void Buffer::setReadonly(bool const flag)
796 if (d->read_only != flag) {
803 void Buffer::setFileName(FileName const & fname)
805 bool const changed = fname != d->filename;
808 lyxvc().file_found_hook(fname);
809 setReadonly(d->filename.isReadOnly());
815 int Buffer::readHeader(Lexer & lex)
817 int unknown_tokens = 0;
819 int begin_header_line = -1;
821 // Initialize parameters that may be/go lacking in header:
822 params().branchlist().clear();
823 params().preamble.erase();
824 params().options.erase();
825 params().master.erase();
826 params().float_placement.erase();
827 params().paperwidth.erase();
828 params().paperheight.erase();
829 params().leftmargin.erase();
830 params().rightmargin.erase();
831 params().topmargin.erase();
832 params().bottommargin.erase();
833 params().headheight.erase();
834 params().headsep.erase();
835 params().footskip.erase();
836 params().columnsep.erase();
837 params().fonts_cjk.erase();
838 params().listings_params.clear();
839 params().clearLayoutModules();
840 params().clearRemovedModules();
841 params().clearIncludedChildren();
842 params().pdfoptions().clear();
843 params().indiceslist().clear();
844 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
845 params().isbackgroundcolor = false;
846 params().fontcolor = RGBColor(0, 0, 0);
847 params().isfontcolor = false;
848 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
849 params().boxbgcolor = RGBColor(0xFF, 0, 0);
850 params().html_latex_start.clear();
851 params().html_latex_end.clear();
852 params().html_math_img_scale = 1.0;
853 params().output_sync_macro.erase();
854 params().setLocalLayout(string(), false);
855 params().setLocalLayout(string(), true);
857 for (int i = 0; i < 4; ++i) {
858 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
859 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
862 ErrorList & errorList = d->errorLists["Parse"];
871 if (token == "\\end_header")
875 if (token == "\\begin_header") {
876 begin_header_line = line;
880 LYXERR(Debug::PARSER, "Handling document header token: `"
883 string unknown = params().readToken(lex, token, d->filename.onlyPath());
884 if (!unknown.empty()) {
885 if (unknown[0] != '\\' && token == "\\textclass") {
886 Alert::warning(_("Unknown document class"),
887 bformat(_("Using the default document class, because the "
888 "class %1$s is unknown."), from_utf8(unknown)));
891 docstring const s = bformat(_("Unknown token: "
895 errorList.push_back(ErrorItem(_("Document header error"),
900 if (begin_header_line) {
901 docstring const s = _("\\begin_header is missing");
902 errorList.push_back(ErrorItem(_("Document header error"),
906 params().makeDocumentClass();
908 return unknown_tokens;
913 // changed to be public and have one parameter
914 // Returns true if "\end_document" is not read (Asger)
915 bool Buffer::readDocument(Lexer & lex)
917 ErrorList & errorList = d->errorLists["Parse"];
920 // remove dummy empty par
921 paragraphs().clear();
923 if (!lex.checkFor("\\begin_document")) {
924 docstring const s = _("\\begin_document is missing");
925 errorList.push_back(ErrorItem(_("Document header error"),
931 if (params().output_changes) {
932 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
933 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
934 LaTeXFeatures::isAvailable("xcolor");
936 if (!dvipost && !xcolorulem) {
937 Alert::warning(_("Changes not shown in LaTeX output"),
938 _("Changes will not be highlighted in LaTeX output, "
939 "because neither dvipost nor xcolor/ulem are installed.\n"
940 "Please install these packages or redefine "
941 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
942 } else if (!xcolorulem) {
943 Alert::warning(_("Changes not shown in LaTeX output"),
944 _("Changes will not be highlighted in LaTeX output "
945 "when using pdflatex, because xcolor and ulem are not installed.\n"
946 "Please install both packages or redefine "
947 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
951 if (!parent() && !params().master.empty()) {
952 FileName const master_file = makeAbsPath(params().master,
953 onlyPath(absFileName()));
954 if (isLyXFileName(master_file.absFileName())) {
956 checkAndLoadLyXFile(master_file, true);
958 // necessary e.g. after a reload
959 // to re-register the child (bug 5873)
960 // FIXME: clean up updateMacros (here, only
961 // child registering is needed).
962 master->updateMacros();
963 // set master as master buffer, but only
964 // if we are a real child
965 if (master->isChild(this))
967 // if the master is not fully loaded
968 // it is probably just loading this
969 // child. No warning needed then.
970 else if (master->isFullyLoaded())
971 LYXERR0("The master '"
973 << "' assigned to this document ("
975 << ") does not include "
976 "this document. Ignoring the master assignment.");
981 // assure we have a default index
982 params().indiceslist().addDefault(B_("Index"));
985 bool const res = text().read(lex, errorList, d->inset);
987 // inform parent buffer about local macros
989 Buffer const * pbuf = parent();
990 UserMacroSet::const_iterator cit = usermacros.begin();
991 UserMacroSet::const_iterator end = usermacros.end();
992 for (; cit != end; ++cit)
993 pbuf->usermacros.insert(*cit);
997 updateMacroInstances(InternalUpdate);
1002 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1004 Format const * fmt = formats.getFormat(format);
1007 // It is important to use the correct extension here, since some
1008 // converters create a wrong output file otherwise (e.g. html2latex)
1009 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1010 FileName const name(tempfile.name());
1011 ofdocstream os(name.toFilesystemEncoding().c_str());
1012 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1013 bool const success = !(os << contents).fail();
1016 bool converted = false;
1018 params().compressed = false;
1020 // remove dummy empty par
1021 paragraphs().clear();
1023 converted = importFile(format, name, errorList);
1032 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1034 if (!theConverters().isReachable(format, "lyx"))
1037 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1038 FileName const lyx(tempfile.name());
1039 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1040 return readFile(lyx) == ReadSuccess;
1046 bool Buffer::readString(string const & s)
1048 params().compressed = false;
1051 istringstream is(s);
1053 FileName const fn = FileName::tempName("Buffer_readString");
1056 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1058 if (success && file_format != LYX_FORMAT) {
1059 // We need to call lyx2lyx, so write the input to a file
1060 ofstream os(fn.toFilesystemEncoding().c_str());
1063 // lyxvc in readFile
1064 if (readFile(fn) != ReadSuccess)
1068 if (readDocument(lex))
1076 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1080 if (!lex.setFile(fname)) {
1081 Alert::error(_("File Not Found"),
1082 bformat(_("Unable to open file `%1$s'."),
1083 from_utf8(fn.absFileName())));
1084 return ReadFileNotFound;
1088 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1089 if (ret_plf != ReadSuccess)
1092 if (file_format != LYX_FORMAT) {
1094 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1095 if (ret_clf != ReadSuccess)
1097 return readFile(tmpFile);
1100 // FIXME: InsetInfo needs to know whether the file is under VCS
1101 // during the parse process, so this has to be done before.
1102 lyxvc().file_found_hook(d->filename);
1104 if (readDocument(lex)) {
1105 Alert::error(_("Document format failure"),
1106 bformat(_("%1$s ended unexpectedly, which means"
1107 " that it is probably corrupted."),
1108 from_utf8(fn.absFileName())));
1109 return ReadDocumentFailure;
1112 d->file_fully_loaded = true;
1113 d->read_only = !d->filename.isWritable();
1114 params().compressed = formats.isZippedFile(d->filename);
1120 bool Buffer::isFullyLoaded() const
1122 return d->file_fully_loaded;
1126 void Buffer::setFullyLoaded(bool value)
1128 d->file_fully_loaded = value;
1132 PreviewLoader * Buffer::loader() const
1134 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1136 if (!d->preview_loader_)
1137 d->preview_loader_ = new PreviewLoader(*this);
1138 return d->preview_loader_;
1142 void Buffer::removePreviews() const
1144 delete d->preview_loader_;
1145 d->preview_loader_ = 0;
1149 void Buffer::updatePreviews() const
1151 PreviewLoader * ploader = loader();
1155 InsetIterator it = inset_iterator_begin(*d->inset);
1156 InsetIterator const end = inset_iterator_end(*d->inset);
1157 for (; it != end; ++it)
1158 it->addPreview(it, *ploader);
1160 ploader->startLoading();
1164 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1165 FileName const & fn, int & file_format) const
1167 if(!lex.checkFor("\\lyxformat")) {
1168 Alert::error(_("Document format failure"),
1169 bformat(_("%1$s is not a readable LyX document."),
1170 from_utf8(fn.absFileName())));
1171 return ReadNoLyXFormat;
1177 // LyX formats 217 and earlier were written as 2.17. This corresponds
1178 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1179 // these cases. See also: www.lyx.org/trac/changeset/1313.
1180 size_t dot = tmp_format.find_first_of(".,");
1181 if (dot != string::npos)
1182 tmp_format.erase(dot, 1);
1184 file_format = convert<int>(tmp_format);
1189 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1190 FileName & tmpfile, int from_format)
1192 tmpfile = FileName::tempName("Buffer_convertLyXFormatXXXXXX.lyx");
1193 if(tmpfile.empty()) {
1194 Alert::error(_("Conversion failed"),
1195 bformat(_("%1$s is from a different"
1196 " version of LyX, but a temporary"
1197 " file for converting it could"
1198 " not be created."),
1199 from_utf8(fn.absFileName())));
1200 return LyX2LyXNoTempFile;
1203 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1204 if (lyx2lyx.empty()) {
1205 Alert::error(_("Conversion script not found"),
1206 bformat(_("%1$s is from a different"
1207 " version of LyX, but the"
1208 " conversion script lyx2lyx"
1209 " could not be found."),
1210 from_utf8(fn.absFileName())));
1211 return LyX2LyXNotFound;
1215 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1216 ostringstream command;
1217 command << os::python()
1218 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1219 << " -t " << convert<string>(LYX_FORMAT)
1220 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1221 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1222 string const command_str = command.str();
1224 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1226 cmd_ret const ret = runCommand(command_str);
1227 if (ret.first != 0) {
1228 if (from_format < LYX_FORMAT) {
1229 Alert::error(_("Conversion script failed"),
1230 bformat(_("%1$s is from an older version"
1231 " of LyX and the lyx2lyx script"
1232 " failed to convert it."),
1233 from_utf8(fn.absFileName())));
1234 return LyX2LyXOlderFormat;
1236 Alert::error(_("Conversion script failed"),
1237 bformat(_("%1$s is from a newer version"
1238 " of LyX and the lyx2lyx script"
1239 " failed to convert it."),
1240 from_utf8(fn.absFileName())));
1241 return LyX2LyXNewerFormat;
1248 // Should probably be moved to somewhere else: BufferView? GuiView?
1249 bool Buffer::save() const
1251 docstring const file = makeDisplayPath(absFileName(), 20);
1252 d->filename.refresh();
1254 // check the read-only status before moving the file as a backup
1255 if (d->filename.exists()) {
1256 bool const read_only = !d->filename.isWritable();
1258 Alert::warning(_("File is read-only"),
1259 bformat(_("The file %1$s cannot be written because it "
1260 "is marked as read-only."), file));
1265 // ask if the disk file has been externally modified (use checksum method)
1266 if (fileName().exists() && isExternallyModified(checksum_method)) {
1268 bformat(_("Document %1$s has been externally modified. "
1269 "Are you sure you want to overwrite this file?"), file);
1270 int const ret = Alert::prompt(_("Overwrite modified file?"),
1271 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1276 // We don't need autosaves in the immediate future. (Asger)
1277 resetAutosaveTimers();
1279 // if the file does not yet exist, none of the backup activity
1280 // that follows is necessary
1281 if (!fileName().exists())
1282 return writeFile(fileName());
1284 // we first write the file to a new name, then move it to its
1285 // proper location once that has been done successfully. that
1286 // way we preserve the original file if something goes wrong.
1287 string const savepath = fileName().onlyPath().absFileName();
1289 string const fname = fileName().onlyFileName();
1290 string savename = "tmp-" + convert<string>(fnum) + "-" + fname;
1291 FileName savefile(addName(savepath, savename));
1292 while (savefile.exists()) {
1293 // surely that is enough tries?
1295 Alert::error(_("Write failure"),
1296 bformat(_("Cannot find temporary filename for:\n %1$s.\n"
1297 "Even %2$s exists!"),
1298 from_utf8(fileName().absFileName()),
1299 from_utf8(savefile.absFileName())));
1303 savename = "tmp-" + convert<string>(fnum) + "-" + fname;
1304 savefile.set(addName(savepath, savename));
1307 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1308 if (!writeFile(savefile))
1311 // we will set this to false if we fail
1312 bool made_backup = true;
1313 if (lyxrc.make_backup) {
1314 FileName backupName(absFileName() + '~');
1315 if (!lyxrc.backupdir_path.empty()) {
1316 string const mangledName =
1317 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1318 backupName = FileName(addName(lyxrc.backupdir_path,
1322 // Except file is symlink do not copy because of #6587.
1323 // Hard links have bad luck.
1324 made_backup = fileName().isSymLink() ?
1325 fileName().copyTo(backupName):
1326 fileName().moveTo(backupName);
1329 Alert::error(_("Backup failure"),
1330 bformat(_("Cannot create backup file %1$s.\n"
1331 "Please check whether the directory exists and is writable."),
1332 from_utf8(backupName.absFileName())));
1333 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1337 if (made_backup && savefile.moveTo(fileName())) {
1342 Alert::error(_("Write failure"),
1343 bformat(_("Cannot move saved file to:\n %1$s.\n"
1344 "But the file has successfully been saved as:\n %2$s."),
1345 from_utf8(fileName().absFileName()),
1346 from_utf8(savefile.absFileName())));
1351 bool Buffer::writeFile(FileName const & fname) const
1353 if (d->read_only && fname == d->filename)
1356 bool retval = false;
1358 docstring const str = bformat(_("Saving document %1$s..."),
1359 makeDisplayPath(fname.absFileName()));
1362 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1364 if (params().compressed) {
1365 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1366 retval = ofs && write(ofs);
1368 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1369 retval = ofs && write(ofs);
1373 message(str + _(" could not write file!"));
1378 // removeAutosaveFile();
1381 message(str + _(" done."));
1387 docstring Buffer::emergencyWrite()
1389 // No need to save if the buffer has not changed.
1393 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1395 docstring user_message = bformat(
1396 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1398 // We try to save three places:
1399 // 1) Same place as document. Unless it is an unnamed doc.
1401 string s = absFileName();
1404 if (writeFile(FileName(s))) {
1406 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1407 return user_message;
1409 user_message += " " + _("Save failed! Trying again...\n");
1413 // 2) In HOME directory.
1414 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1416 lyxerr << ' ' << s << endl;
1417 if (writeFile(FileName(s))) {
1419 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1420 return user_message;
1423 user_message += " " + _("Save failed! Trying yet again...\n");
1425 // 3) In "/tmp" directory.
1426 // MakeAbsPath to prepend the current
1427 // drive letter on OS/2
1428 s = addName(package().temp_dir().absFileName(), absFileName());
1430 lyxerr << ' ' << s << endl;
1431 if (writeFile(FileName(s))) {
1433 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1434 return user_message;
1437 user_message += " " + _("Save failed! Bummer. Document is lost.");
1440 return user_message;
1444 bool Buffer::write(ostream & ofs) const
1447 // Use the standard "C" locale for file output.
1448 ofs.imbue(locale::classic());
1451 // The top of the file should not be written by params().
1453 // write out a comment in the top of the file
1454 // Important: Keep the version formatting in sync with lyx2lyx and
1455 // tex2lyx (bug 7951)
1456 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1457 << " created this file. For more info see http://www.lyx.org/\n"
1458 << "\\lyxformat " << LYX_FORMAT << "\n"
1459 << "\\begin_document\n";
1461 /// For each author, set 'used' to true if there is a change
1462 /// by this author in the document; otherwise set it to 'false'.
1463 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1464 AuthorList::Authors::const_iterator a_end = params().authors().end();
1465 for (; a_it != a_end; ++a_it)
1466 a_it->setUsed(false);
1468 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1469 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1470 for ( ; it != end; ++it)
1471 it->checkAuthors(params().authors());
1473 // now write out the buffer parameters.
1474 ofs << "\\begin_header\n";
1475 params().writeFile(ofs);
1476 ofs << "\\end_header\n";
1479 ofs << "\n\\begin_body\n";
1481 ofs << "\n\\end_body\n";
1483 // Write marker that shows file is complete
1484 ofs << "\\end_document" << endl;
1486 // Shouldn't really be needed....
1489 // how to check if close went ok?
1490 // Following is an attempt... (BE 20001011)
1492 // good() returns false if any error occured, including some
1493 // formatting error.
1494 // bad() returns true if something bad happened in the buffer,
1495 // which should include file system full errors.
1500 lyxerr << "File was not closed properly." << endl;
1507 bool Buffer::makeLaTeXFile(FileName const & fname,
1508 string const & original_path,
1509 OutputParams const & runparams_in,
1510 OutputWhat output) const
1512 OutputParams runparams = runparams_in;
1514 // This is necessary for LuaTeX/XeTeX with tex fonts.
1515 // See FIXME in BufferParams::encoding()
1516 if (runparams.isFullUnicode())
1517 runparams.encoding = encodings.fromLyXName("utf8-plain");
1519 string const encoding = runparams.encoding->iconvName();
1520 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1523 try { ofs.reset(encoding); }
1524 catch (iconv_codecvt_facet_exception const & e) {
1525 lyxerr << "Caught iconv exception: " << e.what() << endl;
1526 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1527 "verify that the support software for your encoding (%1$s) is "
1528 "properly installed"), from_ascii(encoding)));
1531 if (!openFileWrite(ofs, fname))
1534 ErrorList & errorList = d->errorLists["Export"];
1536 bool failed_export = false;
1537 otexstream os(ofs, d->texrow);
1539 // make sure we are ready to export
1540 // this needs to be done before we validate
1541 // FIXME Do we need to do this all the time? I.e., in children
1542 // of a master we are exporting?
1544 updateMacroInstances(OutputUpdate);
1547 os.texrow().reset();
1548 writeLaTeXSource(os, original_path, runparams, output);
1550 catch (EncodingException const & e) {
1551 odocstringstream ods;
1552 ods.put(e.failed_char);
1554 oss << "0x" << hex << e.failed_char << dec;
1555 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1556 " (code point %2$s)"),
1557 ods.str(), from_utf8(oss.str()));
1558 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1559 "representable in the chosen encoding.\n"
1560 "Changing the document encoding to utf8 could help."),
1561 e.par_id, e.pos, e.pos + 1));
1562 failed_export = true;
1564 catch (iconv_codecvt_facet_exception const & e) {
1565 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1566 _(e.what()), -1, 0, 0));
1567 failed_export = true;
1569 catch (exception const & e) {
1570 errorList.push_back(ErrorItem(_("conversion failed"),
1571 _(e.what()), -1, 0, 0));
1572 failed_export = true;
1575 lyxerr << "Caught some really weird exception..." << endl;
1581 failed_export = true;
1582 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1585 if (runparams_in.silent)
1589 return !failed_export;
1593 void Buffer::writeLaTeXSource(otexstream & os,
1594 string const & original_path,
1595 OutputParams const & runparams_in,
1596 OutputWhat output) const
1598 // The child documents, if any, shall be already loaded at this point.
1600 OutputParams runparams = runparams_in;
1602 // If we are compiling a file standalone, even if this is the
1603 // child of some other buffer, let's cut the link here, so the
1604 // file is really independent and no concurring settings from
1605 // the master (e.g. branch state) interfere (see #8100).
1606 if (!runparams.is_child)
1607 d->ignore_parent = true;
1609 // Classify the unicode characters appearing in math insets
1610 BufferEncodings::initUnicodeMath(*this);
1612 // validate the buffer.
1613 LYXERR(Debug::LATEX, " Validating buffer...");
1614 LaTeXFeatures features(*this, params(), runparams);
1616 // This is only set once per document (in master)
1617 if (!runparams.is_child)
1618 runparams.use_polyglossia = features.usePolyglossia();
1619 LYXERR(Debug::LATEX, " Buffer validation done.");
1621 bool const output_preamble =
1622 output == FullSource || output == OnlyPreamble;
1623 bool const output_body =
1624 output == FullSource || output == OnlyBody;
1626 // The starting paragraph of the coming rows is the
1627 // first paragraph of the document. (Asger)
1628 if (output_preamble && runparams.nice) {
1629 os << "%% LyX " << lyx_version << " created this file. "
1630 "For more info, see http://www.lyx.org/.\n"
1631 "%% Do not edit unless you really know what "
1634 LYXERR(Debug::INFO, "lyx document header finished");
1636 // There are a few differences between nice LaTeX and usual files:
1637 // usual files have \batchmode and special input@path to allow
1638 // inclusion of figures specified by an explicitly relative path
1639 // (i.e., a path starting with './' or '../') with either \input or
1640 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1641 // input@path is set when the actual parameter original_path is set.
1642 // This is done for usual tex-file, but not for nice-latex-file.
1643 // (Matthias 250696)
1644 // Note that input@path is only needed for something the user does
1645 // in the preamble, included .tex files or ERT, files included by
1646 // LyX work without it.
1647 if (output_preamble) {
1648 if (!runparams.nice) {
1649 // code for usual, NOT nice-latex-file
1650 os << "\\batchmode\n"; // changed from \nonstopmode
1652 if (!original_path.empty()) {
1654 // We don't know the encoding of inputpath
1655 docstring const inputpath = from_utf8(original_path);
1656 docstring uncodable_glyphs;
1657 Encoding const * const enc = runparams.encoding;
1659 for (size_t n = 0; n < inputpath.size(); ++n) {
1660 if (!enc->encodable(inputpath[n])) {
1661 docstring const glyph(1, inputpath[n]);
1662 LYXERR0("Uncodable character '"
1664 << "' in input path!");
1665 uncodable_glyphs += glyph;
1670 // warn user if we found uncodable glyphs.
1671 if (!uncodable_glyphs.empty()) {
1672 frontend::Alert::warning(
1673 _("Uncodable character in file path"),
1675 _("The path of your document\n"
1677 "contains glyphs that are unknown "
1678 "in the current document encoding "
1679 "(namely %2$s). This may result in "
1680 "incomplete output, unless "
1681 "TEXINPUTS contains the document "
1682 "directory and you don't use "
1683 "explicitly relative paths (i.e., "
1684 "paths starting with './' or "
1685 "'../') in the preamble or in ERT."
1686 "\n\nIn case of problems, choose "
1687 "an appropriate document encoding\n"
1688 "(such as utf8) or change the "
1690 inputpath, uncodable_glyphs));
1693 support::latex_path(original_path);
1694 if (contains(docdir, '#')) {
1695 docdir = subst(docdir, "#", "\\#");
1696 os << "\\catcode`\\#=11"
1697 "\\def\\#{#}\\catcode`\\#=6\n";
1699 if (contains(docdir, '%')) {
1700 docdir = subst(docdir, "%", "\\%");
1701 os << "\\catcode`\\%=11"
1702 "\\def\\%{%}\\catcode`\\%=14\n";
1704 os << "\\makeatletter\n"
1705 << "\\def\\input@path{{"
1706 << docdir << "/}}\n"
1707 << "\\makeatother\n";
1711 // get parent macros (if this buffer has a parent) which will be
1712 // written at the document begin further down.
1713 MacroSet parentMacros;
1714 listParentMacros(parentMacros, features);
1716 // Write the preamble
1717 runparams.use_babel = params().writeLaTeX(os, features,
1718 d->filename.onlyPath());
1720 // Japanese might be required only in some children of a document,
1721 // but once required, we must keep use_japanese true.
1722 runparams.use_japanese |= features.isRequired("japanese");
1725 // Restore the parenthood if needed
1726 if (!runparams.is_child)
1727 d->ignore_parent = false;
1732 os << "\\begin{document}\n";
1734 // output the parent macros
1735 MacroSet::iterator it = parentMacros.begin();
1736 MacroSet::iterator end = parentMacros.end();
1737 for (; it != end; ++it) {
1738 int num_lines = (*it)->write(os.os(), true);
1739 os.texrow().newlines(num_lines);
1742 } // output_preamble
1744 os.texrow().start(paragraphs().begin()->id(), 0);
1746 LYXERR(Debug::INFO, "preamble finished, now the body.");
1749 latexParagraphs(*this, text(), os, runparams);
1751 // Restore the parenthood if needed
1752 if (!runparams.is_child)
1753 d->ignore_parent = false;
1755 // add this just in case after all the paragraphs
1758 if (output_preamble) {
1759 os << "\\end{document}\n";
1760 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1762 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1764 runparams_in.encoding = runparams.encoding;
1766 // Just to be sure. (Asger)
1767 os.texrow().newline();
1769 //for (int i = 0; i<d->texrow.rows(); i++) {
1771 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1772 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1775 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1776 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1780 void Buffer::makeDocBookFile(FileName const & fname,
1781 OutputParams const & runparams,
1782 OutputWhat output) const
1784 LYXERR(Debug::LATEX, "makeDocBookFile...");
1787 if (!openFileWrite(ofs, fname))
1790 // make sure we are ready to export
1791 // this needs to be done before we validate
1793 updateMacroInstances(OutputUpdate);
1795 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1799 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1803 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1804 OutputParams const & runparams,
1805 OutputWhat output) const
1807 LaTeXFeatures features(*this, params(), runparams);
1812 DocumentClass const & tclass = params().documentClass();
1813 string const top_element = tclass.latexname();
1815 bool const output_preamble =
1816 output == FullSource || output == OnlyPreamble;
1817 bool const output_body =
1818 output == FullSource || output == OnlyBody;
1820 if (output_preamble) {
1821 if (runparams.flavor == OutputParams::XML)
1822 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1825 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1828 if (! tclass.class_header().empty())
1829 os << from_ascii(tclass.class_header());
1830 else if (runparams.flavor == OutputParams::XML)
1831 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1832 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1834 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1836 docstring preamble = from_utf8(params().preamble);
1837 if (runparams.flavor != OutputParams::XML ) {
1838 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1839 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1840 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1841 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1844 string const name = runparams.nice
1845 ? changeExtension(absFileName(), ".sgml") : fname;
1846 preamble += features.getIncludedFiles(name);
1847 preamble += features.getLyXSGMLEntities();
1849 if (!preamble.empty()) {
1850 os << "\n [ " << preamble << " ]";
1856 string top = top_element;
1858 if (runparams.flavor == OutputParams::XML)
1859 top += params().language->code();
1861 top += params().language->code().substr(0, 2);
1864 if (!params().options.empty()) {
1866 top += params().options;
1869 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1870 << " file was created by LyX " << lyx_version
1871 << "\n See http://www.lyx.org/ for more information -->\n";
1873 params().documentClass().counters().reset();
1875 sgml::openTag(os, top);
1877 docbookParagraphs(text(), *this, os, runparams);
1878 sgml::closeTag(os, top_element);
1883 void Buffer::makeLyXHTMLFile(FileName const & fname,
1884 OutputParams const & runparams) const
1886 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1889 if (!openFileWrite(ofs, fname))
1892 // make sure we are ready to export
1893 // this has to be done before we validate
1894 updateBuffer(UpdateMaster, OutputUpdate);
1895 updateMacroInstances(OutputUpdate);
1897 writeLyXHTMLSource(ofs, runparams, FullSource);
1901 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1905 void Buffer::writeLyXHTMLSource(odocstream & os,
1906 OutputParams const & runparams,
1907 OutputWhat output) const
1909 LaTeXFeatures features(*this, params(), runparams);
1911 d->bibinfo_.makeCitationLabels(*this);
1913 bool const output_preamble =
1914 output == FullSource || output == OnlyPreamble;
1915 bool const output_body =
1916 output == FullSource || output == OnlyBody || output == IncludedFile;
1918 if (output_preamble) {
1919 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1920 << "<!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"
1921 // FIXME Language should be set properly.
1922 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1924 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1925 // FIXME Presumably need to set this right
1926 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1928 docstring const & doctitle = features.htmlTitle();
1930 << (doctitle.empty() ?
1931 from_ascii("LyX Document") :
1932 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1935 docstring styles = features.getTClassHTMLPreamble();
1936 if (!styles.empty())
1937 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1939 styles = from_utf8(features.getPreambleSnippets());
1940 if (!styles.empty())
1941 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1943 // we will collect CSS information in a stream, and then output it
1944 // either here, as part of the header, or else in a separate file.
1945 odocstringstream css;
1946 styles = from_utf8(features.getCSSSnippets());
1947 if (!styles.empty())
1948 css << "/* LyX Provided Styles */\n" << styles << '\n';
1950 styles = features.getTClassHTMLStyles();
1951 if (!styles.empty())
1952 css << "/* Layout-provided Styles */\n" << styles << '\n';
1954 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1955 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1956 if (needfg || needbg) {
1957 css << "\nbody {\n";
1960 << from_ascii(X11hexname(params().fontcolor))
1963 css << " background-color: "
1964 << from_ascii(X11hexname(params().backgroundcolor))
1969 docstring const dstyles = css.str();
1970 if (!dstyles.empty()) {
1971 bool written = false;
1972 if (params().html_css_as_file) {
1973 // open a file for CSS info
1975 string const fcssname = addName(temppath(), "docstyle.css");
1976 FileName const fcssfile = FileName(fcssname);
1977 if (openFileWrite(ocss, fcssfile)) {
1981 // write link to header
1982 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1984 runparams.exportdata->addExternalFile("xhtml", fcssfile);
1987 // we are here if the CSS is supposed to be written to the header
1988 // or if we failed to write it to an external file.
1990 os << "<style type='text/css'>\n"
1999 bool const output_body_tag = (output != IncludedFile);
2000 if (output_body_tag)
2003 if (output != IncludedFile)
2004 // if we're an included file, the counters are in the master.
2005 params().documentClass().counters().reset();
2006 xhtmlParagraphs(text(), *this, xs, runparams);
2007 if (output_body_tag)
2011 if (output_preamble)
2016 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2017 // Other flags: -wall -v0 -x
2018 int Buffer::runChktex()
2022 // get LaTeX-Filename
2023 FileName const path(temppath());
2024 string const name = addName(path.absFileName(), latexName());
2025 string const org_path = filePath();
2027 PathChanger p(path); // path to LaTeX file
2028 message(_("Running chktex..."));
2030 // Generate the LaTeX file if neccessary
2031 OutputParams runparams(¶ms().encoding());
2032 runparams.flavor = OutputParams::LATEX;
2033 runparams.nice = false;
2034 runparams.linelen = lyxrc.plaintext_linelen;
2035 makeLaTeXFile(FileName(name), org_path, runparams);
2038 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2039 int const res = chktex.run(terr); // run chktex
2042 Alert::error(_("chktex failure"),
2043 _("Could not run chktex successfully."));
2045 ErrorList & errlist = d->errorLists["ChkTeX"];
2047 bufferErrors(terr, errlist);
2052 if (runparams.silent)
2053 d->errorLists["ChkTeX"].clear();
2061 void Buffer::validate(LaTeXFeatures & features) const
2063 // Validate the buffer params, but not for included
2064 // files, since they also use the parent buffer's
2066 if (!features.runparams().is_child)
2067 params().validate(features);
2069 for_each(paragraphs().begin(), paragraphs().end(),
2070 bind(&Paragraph::validate, _1, ref(features)));
2072 if (lyxerr.debugging(Debug::LATEX)) {
2073 features.showStruct();
2078 void Buffer::getLabelList(vector<docstring> & list) const
2080 // If this is a child document, use the master's list instead.
2082 masterBuffer()->getLabelList(list);
2087 Toc & toc = d->toc_backend.toc("label");
2088 TocIterator toc_it = toc.begin();
2089 TocIterator end = toc.end();
2090 for (; toc_it != end; ++toc_it) {
2091 if (toc_it->depth() == 0)
2092 list.push_back(toc_it->str());
2097 void Buffer::updateBibfilesCache(UpdateScope scope) const
2099 // FIXME This is probably unnecssary, given where we call this.
2100 // If this is a child document, use the parent's cache instead.
2101 if (parent() && scope != UpdateChildOnly) {
2102 masterBuffer()->updateBibfilesCache();
2106 d->bibfiles_cache_.clear();
2107 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2108 if (it->lyxCode() == BIBTEX_CODE) {
2109 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2110 support::FileNameList const bibfiles = inset.getBibFiles();
2111 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2114 } else if (it->lyxCode() == INCLUDE_CODE) {
2115 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2116 Buffer const * const incbuf = inset.getChildBuffer();
2119 support::FileNameList const & bibfiles =
2120 incbuf->getBibfilesCache(UpdateChildOnly);
2121 if (!bibfiles.empty()) {
2122 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2128 d->bibfile_cache_valid_ = true;
2129 d->bibinfo_cache_valid_ = false;
2130 d->cite_labels_valid_ = false;
2134 void Buffer::invalidateBibinfoCache() const
2136 d->bibinfo_cache_valid_ = false;
2137 d->cite_labels_valid_ = false;
2138 // also invalidate the cache for the parent buffer
2139 Buffer const * const pbuf = d->parent();
2141 pbuf->invalidateBibinfoCache();
2145 void Buffer::invalidateBibfileCache() const
2147 d->bibfile_cache_valid_ = false;
2148 d->bibinfo_cache_valid_ = false;
2149 d->cite_labels_valid_ = false;
2150 // also invalidate the cache for the parent buffer
2151 Buffer const * const pbuf = d->parent();
2153 pbuf->invalidateBibfileCache();
2157 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2159 // FIXME This is probably unnecessary, given where we call this.
2160 // If this is a child document, use the master's cache instead.
2161 Buffer const * const pbuf = masterBuffer();
2162 if (pbuf != this && scope != UpdateChildOnly)
2163 return pbuf->getBibfilesCache();
2165 if (!d->bibfile_cache_valid_)
2166 this->updateBibfilesCache(scope);
2168 return d->bibfiles_cache_;
2172 BiblioInfo const & Buffer::masterBibInfo() const
2174 Buffer const * const tmp = masterBuffer();
2176 return tmp->masterBibInfo();
2181 void Buffer::checkIfBibInfoCacheIsValid() const
2183 // use the master's cache
2184 Buffer const * const tmp = masterBuffer();
2186 tmp->checkIfBibInfoCacheIsValid();
2190 // compare the cached timestamps with the actual ones.
2191 FileNameList const & bibfiles_cache = getBibfilesCache();
2192 FileNameList::const_iterator ei = bibfiles_cache.begin();
2193 FileNameList::const_iterator en = bibfiles_cache.end();
2194 for (; ei != en; ++ ei) {
2195 time_t lastw = ei->lastModified();
2196 time_t prevw = d->bibfile_status_[*ei];
2197 if (lastw != prevw) {
2198 d->bibinfo_cache_valid_ = false;
2199 d->cite_labels_valid_ = false;
2200 d->bibfile_status_[*ei] = lastw;
2206 void Buffer::reloadBibInfoCache() const
2208 // use the master's cache
2209 Buffer const * const tmp = masterBuffer();
2211 tmp->reloadBibInfoCache();
2215 checkIfBibInfoCacheIsValid();
2216 if (d->bibinfo_cache_valid_)
2219 d->bibinfo_.clear();
2221 d->bibinfo_cache_valid_ = true;
2225 void Buffer::collectBibKeys() const
2227 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2228 it->collectBibKeys(it);
2232 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2234 Buffer const * tmp = masterBuffer();
2235 BiblioInfo & masterbi = (tmp == this) ?
2236 d->bibinfo_ : tmp->d->bibinfo_;
2237 masterbi.mergeBiblioInfo(bi);
2241 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2243 Buffer const * tmp = masterBuffer();
2244 BiblioInfo & masterbi = (tmp == this) ?
2245 d->bibinfo_ : tmp->d->bibinfo_;
2250 void Buffer::makeCitationLabels() const
2252 Buffer const * const master = masterBuffer();
2253 return d->bibinfo_.makeCitationLabels(*master);
2257 bool Buffer::citeLabelsValid() const
2259 return masterBuffer()->d->cite_labels_valid_;
2263 void Buffer::removeBiblioTempFiles() const
2265 // We remove files that contain LaTeX commands specific to the
2266 // particular bibliographic style being used, in order to avoid
2267 // LaTeX errors when we switch style.
2268 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2269 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2270 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2271 aux_file.removeFile();
2272 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2273 bbl_file.removeFile();
2274 // Also for the parent buffer
2275 Buffer const * const pbuf = parent();
2277 pbuf->removeBiblioTempFiles();
2281 bool Buffer::isDepClean(string const & name) const
2283 DepClean::const_iterator const it = d->dep_clean.find(name);
2284 if (it == d->dep_clean.end())
2290 void Buffer::markDepClean(string const & name)
2292 d->dep_clean[name] = true;
2296 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2299 // FIXME? if there is an Buffer LFUN that can be dispatched even
2300 // if internal, put a switch '(cmd.action)' here.
2306 switch (cmd.action()) {
2308 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2309 flag.setOnOff(isReadonly());
2312 // FIXME: There is need for a command-line import.
2313 //case LFUN_BUFFER_IMPORT:
2315 case LFUN_BUFFER_AUTO_SAVE:
2318 case LFUN_BUFFER_EXPORT_CUSTOM:
2319 // FIXME: Nothing to check here?
2322 case LFUN_BUFFER_EXPORT: {
2323 docstring const arg = cmd.argument();
2324 if (arg == "custom") {
2328 string format = to_utf8(arg);
2329 size_t pos = format.find(' ');
2330 if (pos != string::npos)
2331 format = format.substr(0, pos);
2332 enable = params().isExportable(format);
2334 flag.message(bformat(
2335 _("Don't know how to export to format: %1$s"), arg));
2339 case LFUN_BUFFER_CHKTEX:
2340 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2343 case LFUN_BUILD_PROGRAM:
2344 enable = params().isExportable("program");
2347 case LFUN_BRANCH_ACTIVATE:
2348 case LFUN_BRANCH_DEACTIVATE:
2349 case LFUN_BRANCH_MASTER_ACTIVATE:
2350 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2351 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2352 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2353 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2354 : params().branchlist();
2355 docstring const branchName = cmd.argument();
2356 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2360 case LFUN_BRANCH_ADD:
2361 case LFUN_BRANCHES_RENAME:
2362 case LFUN_BUFFER_PRINT:
2363 // if no Buffer is present, then of course we won't be called!
2366 case LFUN_BUFFER_LANGUAGE:
2367 enable = !isReadonly();
2373 flag.setEnabled(enable);
2378 void Buffer::dispatch(string const & command, DispatchResult & result)
2380 return dispatch(lyxaction.lookupFunc(command), result);
2384 // NOTE We can end up here even if we have no GUI, because we are called
2385 // by LyX::exec to handled command-line requests. So we may need to check
2386 // whether we have a GUI or not. The boolean use_gui holds this information.
2387 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2390 // FIXME? if there is an Buffer LFUN that can be dispatched even
2391 // if internal, put a switch '(cmd.action())' here.
2392 dr.dispatched(false);
2395 string const argument = to_utf8(func.argument());
2396 // We'll set this back to false if need be.
2397 bool dispatched = true;
2398 undo().beginUndoGroup();
2400 switch (func.action()) {
2401 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2402 if (lyxvc().inUse()) {
2403 string log = lyxvc().toggleReadOnly();
2408 setReadonly(!isReadonly());
2411 case LFUN_BUFFER_EXPORT: {
2412 ExportStatus const status = doExport(argument, false);
2413 dr.setError(status != ExportSuccess);
2414 if (status != ExportSuccess)
2415 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2420 case LFUN_BUILD_PROGRAM: {
2421 ExportStatus const status = doExport("program", true);
2422 dr.setError(status != ExportSuccess);
2423 if (status != ExportSuccess)
2424 dr.setMessage(_("Error generating literate programming code."));
2428 case LFUN_BUFFER_CHKTEX:
2432 case LFUN_BUFFER_EXPORT_CUSTOM: {
2434 string command = split(argument, format_name, ' ');
2435 Format const * format = formats.getFormat(format_name);
2437 lyxerr << "Format \"" << format_name
2438 << "\" not recognized!"
2443 // The name of the file created by the conversion process
2446 // Output to filename
2447 if (format->name() == "lyx") {
2448 string const latexname = latexName(false);
2449 filename = changeExtension(latexname,
2450 format->extension());
2451 filename = addName(temppath(), filename);
2453 if (!writeFile(FileName(filename)))
2457 doExport(format_name, true, filename);
2460 // Substitute $$FName for filename
2461 if (!contains(command, "$$FName"))
2462 command = "( " + command + " ) < $$FName";
2463 command = subst(command, "$$FName", filename);
2465 // Execute the command in the background
2467 call.startscript(Systemcall::DontWait, command, filePath());
2471 // FIXME: There is need for a command-line import.
2473 case LFUN_BUFFER_IMPORT:
2478 case LFUN_BUFFER_AUTO_SAVE:
2480 resetAutosaveTimers();
2483 case LFUN_BRANCH_ACTIVATE:
2484 case LFUN_BRANCH_DEACTIVATE:
2485 case LFUN_BRANCH_MASTER_ACTIVATE:
2486 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2487 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2488 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2489 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2492 docstring const branch_name = func.argument();
2493 // the case without a branch name is handled elsewhere
2494 if (branch_name.empty()) {
2498 Branch * branch = buf->params().branchlist().find(branch_name);
2500 LYXERR0("Branch " << branch_name << " does not exist.");
2502 docstring const msg =
2503 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2507 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2508 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2509 if (branch->isSelected() != activate) {
2510 buf->undo().recordUndoFullDocument(CursorData());
2511 branch->setSelected(activate);
2513 dr.screenUpdate(Update::Force);
2514 dr.forceBufferUpdate();
2519 case LFUN_BRANCH_ADD: {
2520 docstring branch_name = func.argument();
2521 if (branch_name.empty()) {
2525 BranchList & branch_list = params().branchlist();
2526 vector<docstring> const branches =
2527 getVectorFromString(branch_name, branch_list.separator());
2529 for (vector<docstring>::const_iterator it = branches.begin();
2530 it != branches.end(); ++it) {
2532 Branch * branch = branch_list.find(branch_name);
2534 LYXERR0("Branch " << branch_name << " already exists.");
2538 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2540 undo().recordUndoFullDocument(CursorData());
2541 branch_list.add(branch_name);
2542 branch = branch_list.find(branch_name);
2543 string const x11hexname = X11hexname(branch->color());
2544 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2545 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2547 dr.screenUpdate(Update::Force);
2555 case LFUN_BRANCHES_RENAME: {
2556 if (func.argument().empty())
2559 docstring const oldname = from_utf8(func.getArg(0));
2560 docstring const newname = from_utf8(func.getArg(1));
2561 InsetIterator it = inset_iterator_begin(inset());
2562 InsetIterator const end = inset_iterator_end(inset());
2563 bool success = false;
2564 for (; it != end; ++it) {
2565 if (it->lyxCode() == BRANCH_CODE) {
2566 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2567 if (ins.branch() == oldname) {
2568 undo().recordUndo(CursorData(it));
2569 ins.rename(newname);
2574 if (it->lyxCode() == INCLUDE_CODE) {
2575 // get buffer of external file
2576 InsetInclude const & ins =
2577 static_cast<InsetInclude const &>(*it);
2578 Buffer * child = ins.getChildBuffer();
2581 child->dispatch(func, dr);
2586 dr.screenUpdate(Update::Force);
2587 dr.forceBufferUpdate();
2592 case LFUN_BUFFER_PRINT: {
2593 // we'll assume there's a problem until we succeed
2595 string target = func.getArg(0);
2596 string target_name = func.getArg(1);
2597 string command = func.getArg(2);
2600 || target_name.empty()
2601 || command.empty()) {
2602 LYXERR0("Unable to parse " << func.argument());
2603 docstring const msg =
2604 bformat(_("Unable to parse \"%1$s\""), func.argument());
2608 if (target != "printer" && target != "file") {
2609 LYXERR0("Unrecognized target \"" << target << '"');
2610 docstring const msg =
2611 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2616 if (doExport("dvi", true) != ExportSuccess) {
2617 showPrintError(absFileName());
2618 dr.setMessage(_("Error exporting to DVI."));
2622 // Push directory path.
2623 string const path = temppath();
2624 // Prevent the compiler from optimizing away p
2628 // there are three cases here:
2629 // 1. we print to a file
2630 // 2. we print directly to a printer
2631 // 3. we print using a spool command (print to file first)
2634 string const dviname = changeExtension(latexName(true), "dvi");
2636 if (target == "printer") {
2637 if (!lyxrc.print_spool_command.empty()) {
2638 // case 3: print using a spool
2639 string const psname = changeExtension(dviname,".ps");
2640 command += ' ' + lyxrc.print_to_file
2643 + quoteName(dviname);
2645 string command2 = lyxrc.print_spool_command + ' ';
2646 if (target_name != "default") {
2647 command2 += lyxrc.print_spool_printerprefix
2651 command2 += quoteName(psname);
2653 // If successful, then spool command
2654 res = one.startscript(Systemcall::Wait, command,
2658 // If there's no GUI, we have to wait on this command. Otherwise,
2659 // LyX deletes the temporary directory, and with it the spooled
2660 // file, before it can be printed!!
2661 Systemcall::Starttype stype = use_gui ?
2662 Systemcall::DontWait : Systemcall::Wait;
2663 res = one.startscript(stype, command2,
2667 // case 2: print directly to a printer
2668 if (target_name != "default")
2669 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2671 Systemcall::Starttype stype = use_gui ?
2672 Systemcall::DontWait : Systemcall::Wait;
2673 res = one.startscript(stype, command +
2674 quoteName(dviname), filePath());
2678 // case 1: print to a file
2679 FileName const filename(makeAbsPath(target_name, filePath()));
2680 FileName const dvifile(makeAbsPath(dviname, path));
2681 if (filename.exists()) {
2682 docstring text = bformat(
2683 _("The file %1$s already exists.\n\n"
2684 "Do you want to overwrite that file?"),
2685 makeDisplayPath(filename.absFileName()));
2686 if (Alert::prompt(_("Overwrite file?"),
2687 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2690 command += ' ' + lyxrc.print_to_file
2691 + quoteName(filename.toFilesystemEncoding())
2693 + quoteName(dvifile.toFilesystemEncoding());
2695 Systemcall::Starttype stype = use_gui ?
2696 Systemcall::DontWait : Systemcall::Wait;
2697 res = one.startscript(stype, command, filePath());
2703 dr.setMessage(_("Error running external commands."));
2704 showPrintError(absFileName());
2713 dr.dispatched(dispatched);
2714 undo().endUndoGroup();
2718 void Buffer::changeLanguage(Language const * from, Language const * to)
2720 LASSERT(from, return);
2721 LASSERT(to, return);
2723 for_each(par_iterator_begin(),
2725 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2729 bool Buffer::isMultiLingual() const
2731 ParConstIterator end = par_iterator_end();
2732 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2733 if (it->isMultiLingual(params()))
2740 std::set<Language const *> Buffer::getLanguages() const
2742 std::set<Language const *> languages;
2743 getLanguages(languages);
2748 void Buffer::getLanguages(std::set<Language const *> & languages) const
2750 ParConstIterator end = par_iterator_end();
2751 // add the buffer language, even if it's not actively used
2752 languages.insert(language());
2753 // iterate over the paragraphs
2754 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2755 it->getLanguages(languages);
2757 ListOfBuffers clist = getDescendents();
2758 ListOfBuffers::const_iterator cit = clist.begin();
2759 ListOfBuffers::const_iterator const cen = clist.end();
2760 for (; cit != cen; ++cit)
2761 (*cit)->getLanguages(languages);
2765 DocIterator Buffer::getParFromID(int const id) const
2767 Buffer * buf = const_cast<Buffer *>(this);
2769 // John says this is called with id == -1 from undo
2770 lyxerr << "getParFromID(), id: " << id << endl;
2771 return doc_iterator_end(buf);
2774 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2775 if (it.paragraph().id() == id)
2778 return doc_iterator_end(buf);
2782 bool Buffer::hasParWithID(int const id) const
2784 return !getParFromID(id).atEnd();
2788 ParIterator Buffer::par_iterator_begin()
2790 return ParIterator(doc_iterator_begin(this));
2794 ParIterator Buffer::par_iterator_end()
2796 return ParIterator(doc_iterator_end(this));
2800 ParConstIterator Buffer::par_iterator_begin() const
2802 return ParConstIterator(doc_iterator_begin(this));
2806 ParConstIterator Buffer::par_iterator_end() const
2808 return ParConstIterator(doc_iterator_end(this));
2812 Language const * Buffer::language() const
2814 return params().language;
2818 docstring const Buffer::B_(string const & l10n) const
2820 return params().B_(l10n);
2824 bool Buffer::isClean() const
2826 return d->lyx_clean;
2830 bool Buffer::isExternallyModified(CheckMethod method) const
2832 LASSERT(d->filename.exists(), return false);
2833 // if method == timestamp, check timestamp before checksum
2834 return (method == checksum_method
2835 || d->timestamp_ != d->filename.lastModified())
2836 && d->checksum_ != d->filename.checksum();
2840 void Buffer::saveCheckSum() const
2842 FileName const & file = d->filename;
2845 if (file.exists()) {
2846 d->timestamp_ = file.lastModified();
2847 d->checksum_ = file.checksum();
2849 // in the case of save to a new file.
2856 void Buffer::markClean() const
2858 if (!d->lyx_clean) {
2859 d->lyx_clean = true;
2862 // if the .lyx file has been saved, we don't need an
2864 d->bak_clean = true;
2865 d->undo_.markDirty();
2869 void Buffer::setUnnamed(bool flag)
2875 bool Buffer::isUnnamed() const
2882 /// Don't check unnamed, here: isInternal() is used in
2883 /// newBuffer(), where the unnamed flag has not been set by anyone
2884 /// yet. Also, for an internal buffer, there should be no need for
2885 /// retrieving fileName() nor for checking if it is unnamed or not.
2886 bool Buffer::isInternal() const
2888 return d->internal_buffer;
2892 void Buffer::setInternal(bool flag)
2894 d->internal_buffer = flag;
2898 void Buffer::markDirty()
2901 d->lyx_clean = false;
2904 d->bak_clean = false;
2906 DepClean::iterator it = d->dep_clean.begin();
2907 DepClean::const_iterator const end = d->dep_clean.end();
2909 for (; it != end; ++it)
2914 FileName Buffer::fileName() const
2920 string Buffer::absFileName() const
2922 return d->filename.absFileName();
2926 string Buffer::filePath() const
2928 string const abs = d->filename.onlyPath().absFileName();
2931 int last = abs.length() - 1;
2933 return abs[last] == '/' ? abs : abs + '/';
2937 bool Buffer::isReadonly() const
2939 return d->read_only;
2943 void Buffer::setParent(Buffer const * buffer)
2945 // Avoids recursive include.
2946 d->setParent(buffer == this ? 0 : buffer);
2951 Buffer const * Buffer::parent() const
2957 ListOfBuffers Buffer::allRelatives() const
2959 ListOfBuffers lb = masterBuffer()->getDescendents();
2960 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2965 Buffer const * Buffer::masterBuffer() const
2967 // FIXME Should be make sure we are not in some kind
2968 // of recursive include? A -> B -> A will crash this.
2969 Buffer const * const pbuf = d->parent();
2973 return pbuf->masterBuffer();
2977 bool Buffer::isChild(Buffer * child) const
2979 return d->children_positions.find(child) != d->children_positions.end();
2983 DocIterator Buffer::firstChildPosition(Buffer const * child)
2985 Impl::BufferPositionMap::iterator it;
2986 it = d->children_positions.find(child);
2987 if (it == d->children_positions.end())
2988 return DocIterator(this);
2993 bool Buffer::hasChildren() const
2995 return !d->children_positions.empty();
2999 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3001 // loop over children
3002 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3003 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3004 for (; it != end; ++it) {
3005 Buffer * child = const_cast<Buffer *>(it->first);
3007 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3008 if (bit != clist.end())
3010 clist.push_back(child);
3012 // there might be grandchildren
3013 child->collectChildren(clist, true);
3018 ListOfBuffers Buffer::getChildren() const
3021 collectChildren(v, false);
3022 // Make sure we have not included ourselves.
3023 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3024 if (bit != v.end()) {
3025 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3032 ListOfBuffers Buffer::getDescendents() const
3035 collectChildren(v, true);
3036 // Make sure we have not included ourselves.
3037 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3038 if (bit != v.end()) {
3039 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3046 template<typename M>
3047 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3052 typename M::const_iterator it = m.lower_bound(x);
3053 if (it == m.begin())
3061 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3062 DocIterator const & pos) const
3064 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3066 // if paragraphs have no macro context set, pos will be empty
3070 // we haven't found anything yet
3071 DocIterator bestPos = owner_->par_iterator_begin();
3072 MacroData const * bestData = 0;
3074 // find macro definitions for name
3075 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3076 if (nameIt != macros.end()) {
3077 // find last definition in front of pos or at pos itself
3078 PositionScopeMacroMap::const_iterator it
3079 = greatest_below(nameIt->second, pos);
3080 if (it != nameIt->second.end()) {
3082 // scope ends behind pos?
3083 if (pos < it->second.first) {
3084 // Looks good, remember this. If there
3085 // is no external macro behind this,
3086 // we found the right one already.
3087 bestPos = it->first;
3088 bestData = &it->second.second;
3092 // try previous macro if there is one
3093 if (it == nameIt->second.begin())
3100 // find macros in included files
3101 PositionScopeBufferMap::const_iterator it
3102 = greatest_below(position_to_children, pos);
3103 if (it == position_to_children.end())
3104 // no children before
3108 // do we know something better (i.e. later) already?
3109 if (it->first < bestPos )
3112 // scope ends behind pos?
3113 if (pos < it->second.first
3114 && (cloned_buffer_ ||
3115 theBufferList().isLoaded(it->second.second))) {
3116 // look for macro in external file
3118 MacroData const * data
3119 = it->second.second->getMacro(name, false);
3122 bestPos = it->first;
3128 // try previous file if there is one
3129 if (it == position_to_children.begin())
3134 // return the best macro we have found
3139 MacroData const * Buffer::getMacro(docstring const & name,
3140 DocIterator const & pos, bool global) const
3145 // query buffer macros
3146 MacroData const * data = d->getBufferMacro(name, pos);
3150 // If there is a master buffer, query that
3151 Buffer const * const pbuf = d->parent();
3153 d->macro_lock = true;
3154 MacroData const * macro = pbuf->getMacro(
3155 name, *this, false);
3156 d->macro_lock = false;
3162 data = MacroTable::globalMacros().get(name);
3171 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3173 // set scope end behind the last paragraph
3174 DocIterator scope = par_iterator_begin();
3175 scope.pit() = scope.lastpit() + 1;
3177 return getMacro(name, scope, global);
3181 MacroData const * Buffer::getMacro(docstring const & name,
3182 Buffer const & child, bool global) const
3184 // look where the child buffer is included first
3185 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3186 if (it == d->children_positions.end())
3189 // check for macros at the inclusion position
3190 return getMacro(name, it->second, global);
3194 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3196 pit_type const lastpit = it.lastpit();
3198 // look for macros in each paragraph
3199 while (it.pit() <= lastpit) {
3200 Paragraph & par = it.paragraph();
3202 // iterate over the insets of the current paragraph
3203 InsetList const & insets = par.insetList();
3204 InsetList::const_iterator iit = insets.begin();
3205 InsetList::const_iterator end = insets.end();
3206 for (; iit != end; ++iit) {
3207 it.pos() = iit->pos;
3209 // is it a nested text inset?
3210 if (iit->inset->asInsetText()) {
3211 // Inset needs its own scope?
3212 InsetText const * itext = iit->inset->asInsetText();
3213 bool newScope = itext->isMacroScope();
3215 // scope which ends just behind the inset
3216 DocIterator insetScope = it;
3219 // collect macros in inset
3220 it.push_back(CursorSlice(*iit->inset));
3221 updateMacros(it, newScope ? insetScope : scope);
3226 if (iit->inset->asInsetTabular()) {
3227 CursorSlice slice(*iit->inset);
3228 size_t const numcells = slice.nargs();
3229 for (; slice.idx() < numcells; slice.forwardIdx()) {
3230 it.push_back(slice);
3231 updateMacros(it, scope);
3237 // is it an external file?
3238 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3239 // get buffer of external file
3240 InsetInclude const & inset =
3241 static_cast<InsetInclude const &>(*iit->inset);
3243 Buffer * child = inset.getChildBuffer();
3248 // register its position, but only when it is
3249 // included first in the buffer
3250 if (children_positions.find(child) ==
3251 children_positions.end())
3252 children_positions[child] = it;
3254 // register child with its scope
3255 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3259 InsetMath * im = iit->inset->asInsetMath();
3260 if (doing_export && im) {
3261 InsetMathHull * hull = im->asHullInset();
3263 hull->recordLocation(it);
3266 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3270 MathMacroTemplate & macroTemplate =
3271 *iit->inset->asInsetMath()->asMacroTemplate();
3272 MacroContext mc(owner_, it);
3273 macroTemplate.updateToContext(mc);
3276 bool valid = macroTemplate.validMacro();
3277 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3278 // then the BufferView's cursor will be invalid in
3279 // some cases which leads to crashes.
3284 // FIXME (Abdel), I don't understandt why we pass 'it' here
3285 // instead of 'macroTemplate' defined above... is this correct?
3286 macros[macroTemplate.name()][it] =
3287 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3297 void Buffer::updateMacros() const
3302 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3304 // start with empty table
3306 d->children_positions.clear();
3307 d->position_to_children.clear();
3309 // Iterate over buffer, starting with first paragraph
3310 // The scope must be bigger than any lookup DocIterator
3311 // later. For the global lookup, lastpit+1 is used, hence
3312 // we use lastpit+2 here.
3313 DocIterator it = par_iterator_begin();
3314 DocIterator outerScope = it;
3315 outerScope.pit() = outerScope.lastpit() + 2;
3316 d->updateMacros(it, outerScope);
3320 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3322 InsetIterator it = inset_iterator_begin(inset());
3323 InsetIterator const end = inset_iterator_end(inset());
3324 for (; it != end; ++it) {
3325 if (it->lyxCode() == BRANCH_CODE) {
3326 InsetBranch & br = static_cast<InsetBranch &>(*it);
3327 docstring const name = br.branch();
3328 if (!from_master && !params().branchlist().find(name))
3329 result.push_back(name);
3330 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3331 result.push_back(name);
3334 if (it->lyxCode() == INCLUDE_CODE) {
3335 // get buffer of external file
3336 InsetInclude const & ins =
3337 static_cast<InsetInclude const &>(*it);
3338 Buffer * child = ins.getChildBuffer();
3341 child->getUsedBranches(result, true);
3344 // remove duplicates
3349 void Buffer::updateMacroInstances(UpdateType utype) const
3351 LYXERR(Debug::MACROS, "updateMacroInstances for "
3352 << d->filename.onlyFileName());
3353 DocIterator it = doc_iterator_begin(this);
3355 DocIterator const end = doc_iterator_end(this);
3356 for (; it != end; it.forwardInset()) {
3357 // look for MathData cells in InsetMathNest insets
3358 InsetMath * minset = it.nextInset()->asInsetMath();
3362 // update macro in all cells of the InsetMathNest
3363 DocIterator::idx_type n = minset->nargs();
3364 MacroContext mc = MacroContext(this, it);
3365 for (DocIterator::idx_type i = 0; i < n; ++i) {
3366 MathData & data = minset->cell(i);
3367 data.updateMacros(0, mc, utype);
3373 void Buffer::listMacroNames(MacroNameSet & macros) const
3378 d->macro_lock = true;
3380 // loop over macro names
3381 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3382 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3383 for (; nameIt != nameEnd; ++nameIt)
3384 macros.insert(nameIt->first);
3386 // loop over children
3387 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3388 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3389 for (; it != end; ++it)
3390 it->first->listMacroNames(macros);
3393 Buffer const * const pbuf = d->parent();
3395 pbuf->listMacroNames(macros);
3397 d->macro_lock = false;
3401 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3403 Buffer const * const pbuf = d->parent();
3408 pbuf->listMacroNames(names);
3411 MacroNameSet::iterator it = names.begin();
3412 MacroNameSet::iterator end = names.end();
3413 for (; it != end; ++it) {
3415 MacroData const * data =
3416 pbuf->getMacro(*it, *this, false);
3418 macros.insert(data);
3420 // we cannot access the original MathMacroTemplate anymore
3421 // here to calls validate method. So we do its work here manually.
3422 // FIXME: somehow make the template accessible here.
3423 if (data->optionals() > 0)
3424 features.require("xargs");
3430 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3433 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3435 RefCache::iterator it = d->ref_cache_.find(label);
3436 if (it != d->ref_cache_.end())
3437 return it->second.second;
3439 static InsetLabel const * dummy_il = 0;
3440 static References const dummy_refs;
3441 it = d->ref_cache_.insert(
3442 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3443 return it->second.second;
3447 Buffer::References const & Buffer::references(docstring const & label) const
3449 return const_cast<Buffer *>(this)->getReferenceCache(label);
3453 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3455 References & refs = getReferenceCache(label);
3456 refs.push_back(make_pair(inset, it));
3460 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3462 masterBuffer()->d->ref_cache_[label].first = il;
3466 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3468 return masterBuffer()->d->ref_cache_[label].first;
3472 void Buffer::clearReferenceCache() const
3475 d->ref_cache_.clear();
3479 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3481 //FIXME: This does not work for child documents yet.
3482 reloadBibInfoCache();
3484 // Check if the label 'from' appears more than once
3485 BiblioInfo const & keys = masterBibInfo();
3486 BiblioInfo::const_iterator bit = keys.begin();
3487 BiblioInfo::const_iterator bend = keys.end();
3488 vector<docstring> labels;
3490 for (; bit != bend; ++bit)
3492 labels.push_back(bit->first);
3494 if (count(labels.begin(), labels.end(), from) > 1)
3497 string const paramName = "key";
3498 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3499 if (it->lyxCode() != CITE_CODE)
3501 InsetCommand * inset = it->asInsetCommand();
3502 docstring const oldValue = inset->getParam(paramName);
3503 if (oldValue == from)
3504 inset->setParam(paramName, to);
3509 void Buffer::getSourceCode(odocstream & os, string const format,
3510 pit_type par_begin, pit_type par_end,
3511 OutputWhat output, bool master) const
3513 OutputParams runparams(¶ms().encoding());
3514 runparams.nice = true;
3515 runparams.flavor = params().getOutputFlavor(format);
3516 runparams.linelen = lyxrc.plaintext_linelen;
3517 // No side effect of file copying and image conversion
3518 runparams.dryrun = true;
3520 if (output == CurrentParagraph) {
3521 runparams.par_begin = par_begin;
3522 runparams.par_end = par_end;
3523 if (par_begin + 1 == par_end) {
3525 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3529 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3530 convert<docstring>(par_begin),
3531 convert<docstring>(par_end - 1))
3534 // output paragraphs
3535 if (runparams.flavor == OutputParams::LYX) {
3536 Paragraph const & par = text().paragraphs()[par_begin];
3538 depth_type dt = par.getDepth();
3539 par.write(ods, params(), dt);
3540 os << from_utf8(ods.str());
3541 } else if (runparams.flavor == OutputParams::HTML) {
3543 setMathFlavor(runparams);
3544 xhtmlParagraphs(text(), *this, xs, runparams);
3545 } else if (runparams.flavor == OutputParams::TEXT) {
3547 // FIXME Handles only one paragraph, unlike the others.
3548 // Probably should have some routine with a signature like them.
3549 writePlaintextParagraph(*this,
3550 text().paragraphs()[par_begin], os, runparams, dummy);
3551 } else if (params().isDocBook()) {
3552 docbookParagraphs(text(), *this, os, runparams);
3554 // If we are previewing a paragraph, even if this is the
3555 // child of some other buffer, let's cut the link here,
3556 // so that no concurring settings from the master
3557 // (e.g. branch state) interfere (see #8101).
3559 d->ignore_parent = true;
3560 // We need to validate the Buffer params' features here
3561 // in order to know if we should output polyglossia
3562 // macros (instead of babel macros)
3563 LaTeXFeatures features(*this, params(), runparams);
3564 params().validate(features);
3565 runparams.use_polyglossia = features.usePolyglossia();
3570 // latex or literate
3571 otexstream ots(os, texrow);
3574 latexParagraphs(*this, text(), ots, runparams);
3576 // Restore the parenthood
3578 d->ignore_parent = false;
3582 if (output == FullSource)
3583 os << _("Preview source code");
3584 else if (output == OnlyPreamble)
3585 os << _("Preview preamble");
3586 else if (output == OnlyBody)
3587 os << _("Preview body");
3589 if (runparams.flavor == OutputParams::LYX) {
3591 if (output == FullSource)
3593 else if (output == OnlyPreamble)
3594 params().writeFile(ods);
3595 else if (output == OnlyBody)
3597 os << from_utf8(ods.str());
3598 } else if (runparams.flavor == OutputParams::HTML) {
3599 writeLyXHTMLSource(os, runparams, output);
3600 } else if (runparams.flavor == OutputParams::TEXT) {
3601 if (output == OnlyPreamble) {
3602 os << "% "<< _("Plain text does not have a preamble.");
3604 writePlaintextFile(*this, os, runparams);
3605 } else if (params().isDocBook()) {
3606 writeDocBookSource(os, absFileName(), runparams, output);
3608 // latex or literate
3610 d->texrow.newline();
3611 d->texrow.newline();
3612 otexstream ots(os, d->texrow);
3614 runparams.is_child = true;
3615 writeLaTeXSource(ots, string(), runparams, output);
3621 ErrorList & Buffer::errorList(string const & type) const
3623 return d->errorLists[type];
3627 void Buffer::updateTocItem(std::string const & type,
3628 DocIterator const & dit) const
3631 d->gui_->updateTocItem(type, dit);
3635 void Buffer::structureChanged() const
3638 d->gui_->structureChanged();
3642 void Buffer::errors(string const & err, bool from_master) const
3645 d->gui_->errors(err, from_master);
3649 void Buffer::message(docstring const & msg) const
3652 d->gui_->message(msg);
3656 void Buffer::setBusy(bool on) const
3659 d->gui_->setBusy(on);
3663 void Buffer::updateTitles() const
3666 d->wa_->updateTitles();
3670 void Buffer::resetAutosaveTimers() const
3673 d->gui_->resetAutosaveTimers();
3677 bool Buffer::hasGuiDelegate() const
3683 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3692 class AutoSaveBuffer : public ForkedProcess {
3695 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3696 : buffer_(buffer), fname_(fname) {}
3698 virtual shared_ptr<ForkedProcess> clone() const
3700 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3705 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3706 from_utf8(fname_.absFileName())));
3707 return run(DontWait);
3711 virtual int generateChild();
3713 Buffer const & buffer_;
3718 int AutoSaveBuffer::generateChild()
3720 #if defined(__APPLE__)
3721 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3722 * We should use something else like threads.
3724 * Since I do not know how to determine at run time what is the OS X
3725 * version, I just disable forking altogether for now (JMarc)
3727 pid_t const pid = -1;
3729 // tmp_ret will be located (usually) in /tmp
3730 // will that be a problem?
3731 // Note that this calls ForkedCalls::fork(), so it's
3732 // ok cross-platform.
3733 pid_t const pid = fork();
3734 // If you want to debug the autosave
3735 // you should set pid to -1, and comment out the fork.
3736 if (pid != 0 && pid != -1)
3740 // pid = -1 signifies that lyx was unable
3741 // to fork. But we will do the save
3743 bool failed = false;
3744 FileName const tmp_ret = FileName::tempName("lyxauto");
3745 if (!tmp_ret.empty()) {
3746 buffer_.writeFile(tmp_ret);
3747 // assume successful write of tmp_ret
3748 if (!tmp_ret.moveTo(fname_))
3754 // failed to write/rename tmp_ret so try writing direct
3755 if (!buffer_.writeFile(fname_)) {
3756 // It is dangerous to do this in the child,
3757 // but safe in the parent, so...
3758 if (pid == -1) // emit message signal.
3759 buffer_.message(_("Autosave failed!"));
3763 if (pid == 0) // we are the child so...
3772 FileName Buffer::getEmergencyFileName() const
3774 return FileName(d->filename.absFileName() + ".emergency");
3778 FileName Buffer::getAutosaveFileName() const
3780 // if the document is unnamed try to save in the backup dir, else
3781 // in the default document path, and as a last try in the filePath,
3782 // which will most often be the temporary directory
3785 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3786 : lyxrc.backupdir_path;
3787 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3790 string const fname = "#" + d->filename.onlyFileName() + "#";
3792 return makeAbsPath(fname, fpath);
3796 void Buffer::removeAutosaveFile() const
3798 FileName const f = getAutosaveFileName();
3804 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3806 FileName const newauto = getAutosaveFileName();
3808 if (newauto != oldauto && oldauto.exists())
3809 if (!oldauto.moveTo(newauto))
3810 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3814 bool Buffer::autoSave() const
3816 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3817 if (buf->d->bak_clean || isReadonly())
3820 message(_("Autosaving current document..."));
3821 buf->d->bak_clean = true;
3823 FileName const fname = getAutosaveFileName();
3824 LASSERT(d->cloned_buffer_, return false);
3826 // If this buffer is cloned, we assume that
3827 // we are running in a separate thread already.
3828 FileName const tmp_ret = FileName::tempName("lyxauto");
3829 if (!tmp_ret.empty()) {
3831 // assume successful write of tmp_ret
3832 if (tmp_ret.moveTo(fname))
3835 // failed to write/rename tmp_ret so try writing direct
3836 return writeFile(fname);
3840 void Buffer::setExportStatus(bool e) const
3842 d->doing_export = e;
3843 ListOfBuffers clist = getDescendents();
3844 ListOfBuffers::const_iterator cit = clist.begin();
3845 ListOfBuffers::const_iterator const cen = clist.end();
3846 for (; cit != cen; ++cit)
3847 (*cit)->d->doing_export = e;
3851 bool Buffer::isExporting() const
3853 return d->doing_export;
3857 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3861 return doExport(target, put_in_tempdir, result_file);
3864 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3865 string & result_file) const
3867 bool const update_unincluded =
3868 params().maintain_unincluded_children
3869 && !params().getIncludedChildren().empty();
3871 // (1) export with all included children (omit \includeonly)
3872 if (update_unincluded) {
3873 ExportStatus const status =
3874 doExport(target, put_in_tempdir, true, result_file);
3875 if (status != ExportSuccess)
3878 // (2) export with included children only
3879 return doExport(target, put_in_tempdir, false, result_file);
3883 void Buffer::setMathFlavor(OutputParams & op) const
3885 switch (params().html_math_output) {
3886 case BufferParams::MathML:
3887 op.math_flavor = OutputParams::MathAsMathML;
3889 case BufferParams::HTML:
3890 op.math_flavor = OutputParams::MathAsHTML;
3892 case BufferParams::Images:
3893 op.math_flavor = OutputParams::MathAsImages;
3895 case BufferParams::LaTeX:
3896 op.math_flavor = OutputParams::MathAsLaTeX;
3902 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3903 bool includeall, string & result_file) const
3905 LYXERR(Debug::FILES, "target=" << target);
3906 OutputParams runparams(¶ms().encoding());
3907 string format = target;
3908 string dest_filename;
3909 size_t pos = target.find(' ');
3910 if (pos != string::npos) {
3911 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3912 format = target.substr(0, pos);
3913 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3914 FileName(dest_filename).onlyPath().createPath();
3915 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3917 MarkAsExporting exporting(this);
3918 string backend_format;
3919 runparams.flavor = OutputParams::LATEX;
3920 runparams.linelen = lyxrc.plaintext_linelen;
3921 runparams.includeall = includeall;
3922 vector<string> backs = params().backends();
3923 Converters converters = theConverters();
3924 bool need_nice_file = false;
3925 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3926 // Get shortest path to format
3927 converters.buildGraph();
3928 Graph::EdgePath path;
3929 for (vector<string>::const_iterator it = backs.begin();
3930 it != backs.end(); ++it) {
3931 Graph::EdgePath p = converters.getPath(*it, format);
3932 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3933 backend_format = *it;
3938 if (!put_in_tempdir) {
3939 // Only show this alert if this is an export to a non-temporary
3940 // file (not for previewing).
3941 Alert::error(_("Couldn't export file"), bformat(
3942 _("No information for exporting the format %1$s."),
3943 formats.prettyName(format)));
3945 return ExportNoPathToFormat;
3947 runparams.flavor = converters.getFlavor(path, this);
3948 Graph::EdgePath::const_iterator it = path.begin();
3949 Graph::EdgePath::const_iterator en = path.end();
3950 for (; it != en; ++it)
3951 if (theConverters().get(*it).nice) {
3952 need_nice_file = true;
3957 backend_format = format;
3958 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3959 // FIXME: Don't hardcode format names here, but use a flag
3960 if (backend_format == "pdflatex")
3961 runparams.flavor = OutputParams::PDFLATEX;
3962 else if (backend_format == "luatex")
3963 runparams.flavor = OutputParams::LUATEX;
3964 else if (backend_format == "dviluatex")
3965 runparams.flavor = OutputParams::DVILUATEX;
3966 else if (backend_format == "xetex")
3967 runparams.flavor = OutputParams::XETEX;
3970 string filename = latexName(false);
3971 filename = addName(temppath(), filename);
3972 filename = changeExtension(filename,
3973 formats.extension(backend_format));
3974 LYXERR(Debug::FILES, "filename=" << filename);
3976 // Plain text backend
3977 if (backend_format == "text") {
3978 runparams.flavor = OutputParams::TEXT;
3979 writePlaintextFile(*this, FileName(filename), runparams);
3982 else if (backend_format == "xhtml") {
3983 runparams.flavor = OutputParams::HTML;
3984 setMathFlavor(runparams);
3985 makeLyXHTMLFile(FileName(filename), runparams);
3986 } else if (backend_format == "lyx")
3987 writeFile(FileName(filename));
3989 else if (params().isDocBook()) {
3990 runparams.nice = !put_in_tempdir;
3991 makeDocBookFile(FileName(filename), runparams);
3994 else if (backend_format == format || need_nice_file) {
3995 runparams.nice = true;
3996 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3997 if (d->cloned_buffer_)
3998 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4001 } else if (!lyxrc.tex_allows_spaces
4002 && contains(filePath(), ' ')) {
4003 Alert::error(_("File name error"),
4004 _("The directory path to the document cannot contain spaces."));
4005 return ExportTexPathHasSpaces;
4007 runparams.nice = false;
4008 bool const success = makeLaTeXFile(
4009 FileName(filename), filePath(), runparams);
4010 if (d->cloned_buffer_)
4011 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4016 string const error_type = (format == "program")
4017 ? "Build" : params().bufferFormat();
4018 ErrorList & error_list = d->errorLists[error_type];
4019 string const ext = formats.extension(format);
4020 FileName const tmp_result_file(changeExtension(filename, ext));
4021 bool const success = converters.convert(this, FileName(filename),
4022 tmp_result_file, FileName(absFileName()), backend_format, format,
4025 // Emit the signal to show the error list or copy it back to the
4026 // cloned Buffer so that it can be emitted afterwards.
4027 if (format != backend_format) {
4028 if (runparams.silent)
4030 else if (d->cloned_buffer_)
4031 d->cloned_buffer_->d->errorLists[error_type] =
4032 d->errorLists[error_type];
4035 // also to the children, in case of master-buffer-view
4036 ListOfBuffers clist = getDescendents();
4037 ListOfBuffers::const_iterator cit = clist.begin();
4038 ListOfBuffers::const_iterator const cen = clist.end();
4039 for (; cit != cen; ++cit) {
4040 if (runparams.silent)
4041 (*cit)->d->errorLists[error_type].clear();
4042 else if (d->cloned_buffer_) {
4043 // Enable reverse search by copying back the
4044 // texrow object to the cloned buffer.
4045 // FIXME: this is not thread safe.
4046 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4047 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4048 (*cit)->d->errorLists[error_type];
4050 (*cit)->errors(error_type, true);
4054 if (d->cloned_buffer_) {
4055 // Enable reverse dvi or pdf to work by copying back the texrow
4056 // object to the cloned buffer.
4057 // FIXME: There is a possibility of concurrent access to texrow
4058 // here from the main GUI thread that should be securized.
4059 d->cloned_buffer_->d->texrow = d->texrow;
4060 string const error_type = params().bufferFormat();
4061 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4065 return ExportConverterError;
4067 if (put_in_tempdir) {
4068 result_file = tmp_result_file.absFileName();
4069 return ExportSuccess;
4072 if (dest_filename.empty())
4073 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4075 result_file = dest_filename;
4076 // We need to copy referenced files (e. g. included graphics
4077 // if format == "dvi") to the result dir.
4078 vector<ExportedFile> const files =
4079 runparams.exportdata->externalFiles(format);
4080 string const dest = runparams.export_folder.empty() ?
4081 onlyPath(result_file) : runparams.export_folder;
4082 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4083 : force_overwrite == ALL_FILES;
4084 CopyStatus status = use_force ? FORCE : SUCCESS;
4086 vector<ExportedFile>::const_iterator it = files.begin();
4087 vector<ExportedFile>::const_iterator const en = files.end();
4088 for (; it != en && status != CANCEL; ++it) {
4089 string const fmt = formats.getFormatFromFile(it->sourceName);
4090 string fixedName = it->exportName;
4091 if (!runparams.export_folder.empty()) {
4092 // Relative pathnames starting with ../ will be sanitized
4093 // if exporting to a different folder
4094 while (fixedName.substr(0, 3) == "../")
4095 fixedName = fixedName.substr(3, fixedName.length() - 3);
4097 FileName fixedFileName = makeAbsPath(fixedName, dest);
4098 fixedFileName.onlyPath().createPath();
4099 status = copyFile(fmt, it->sourceName,
4101 it->exportName, status == FORCE,
4102 runparams.export_folder.empty());
4105 if (status == CANCEL) {
4106 message(_("Document export cancelled."));
4107 return ExportCancel;
4110 if (tmp_result_file.exists()) {
4111 // Finally copy the main file
4112 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4113 : force_overwrite != NO_FILES;
4114 if (status == SUCCESS && use_force)
4116 status = copyFile(format, tmp_result_file,
4117 FileName(result_file), result_file,
4119 if (status == CANCEL) {
4120 message(_("Document export cancelled."));
4121 return ExportCancel;
4123 message(bformat(_("Document exported as %1$s "
4125 formats.prettyName(format),
4126 makeDisplayPath(result_file)));
4129 // This must be a dummy converter like fax (bug 1888)
4130 message(bformat(_("Document exported as %1$s"),
4131 formats.prettyName(format)));
4134 return ExportSuccess;
4138 Buffer::ExportStatus Buffer::preview(string const & format) const
4140 bool const update_unincluded =
4141 params().maintain_unincluded_children
4142 && !params().getIncludedChildren().empty();
4143 return preview(format, update_unincluded);
4146 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4148 MarkAsExporting exporting(this);
4150 // (1) export with all included children (omit \includeonly)
4152 ExportStatus const status = doExport(format, true, true, result_file);
4153 if (status != ExportSuccess)
4156 // (2) export with included children only
4157 ExportStatus const status = doExport(format, true, false, result_file);
4158 if (status != ExportSuccess)
4160 if (!formats.view(*this, FileName(result_file), format))
4161 return PreviewError;
4162 return PreviewSuccess;
4166 Buffer::ReadStatus Buffer::extractFromVC()
4168 bool const found = LyXVC::file_not_found_hook(d->filename);
4170 return ReadFileNotFound;
4171 if (!d->filename.isReadableFile())
4177 Buffer::ReadStatus Buffer::loadEmergency()
4179 FileName const emergencyFile = getEmergencyFileName();
4180 if (!emergencyFile.exists()
4181 || emergencyFile.lastModified() <= d->filename.lastModified())
4182 return ReadFileNotFound;
4184 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4185 docstring const text = bformat(_("An emergency save of the document "
4186 "%1$s exists.\n\nRecover emergency save?"), file);
4188 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4189 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4195 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4196 bool const success = (ret_llf == ReadSuccess);
4199 Alert::warning(_("File is read-only"),
4200 bformat(_("An emergency file is successfully loaded, "
4201 "but the original file %1$s is marked read-only. "
4202 "Please make sure to save the document as a different "
4203 "file."), from_utf8(d->filename.absFileName())));
4206 lyxvc().file_found_hook(d->filename);
4207 str = _("Document was successfully recovered.");
4209 str = _("Document was NOT successfully recovered.");
4210 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4211 makeDisplayPath(emergencyFile.absFileName()));
4213 int const del_emerg =
4214 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4215 _("&Remove"), _("&Keep"));
4216 if (del_emerg == 0) {
4217 emergencyFile.removeFile();
4219 Alert::warning(_("Emergency file deleted"),
4220 _("Do not forget to save your file now!"), true);
4222 return success ? ReadSuccess : ReadEmergencyFailure;
4225 int const del_emerg =
4226 Alert::prompt(_("Delete emergency file?"),
4227 _("Remove emergency file now?"), 1, 1,
4228 _("&Remove"), _("&Keep"));
4230 emergencyFile.removeFile();
4231 return ReadOriginal;
4241 Buffer::ReadStatus Buffer::loadAutosave()
4243 // Now check if autosave file is newer.
4244 FileName const autosaveFile = getAutosaveFileName();
4245 if (!autosaveFile.exists()
4246 || autosaveFile.lastModified() <= d->filename.lastModified())
4247 return ReadFileNotFound;
4249 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4250 docstring const text = bformat(_("The backup of the document %1$s "
4251 "is newer.\n\nLoad the backup instead?"), file);
4252 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4253 _("&Load backup"), _("Load &original"), _("&Cancel"));
4258 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4259 // the file is not saved if we load the autosave file.
4260 if (ret_llf == ReadSuccess) {
4262 Alert::warning(_("File is read-only"),
4263 bformat(_("A backup file is successfully loaded, "
4264 "but the original file %1$s is marked read-only. "
4265 "Please make sure to save the document as a "
4267 from_utf8(d->filename.absFileName())));
4270 lyxvc().file_found_hook(d->filename);
4273 return ReadAutosaveFailure;
4276 // Here we delete the autosave
4277 autosaveFile.removeFile();
4278 return ReadOriginal;
4286 Buffer::ReadStatus Buffer::loadLyXFile()
4288 if (!d->filename.isReadableFile()) {
4289 ReadStatus const ret_rvc = extractFromVC();
4290 if (ret_rvc != ReadSuccess)
4294 ReadStatus const ret_re = loadEmergency();
4295 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4298 ReadStatus const ret_ra = loadAutosave();
4299 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4302 return loadThisLyXFile(d->filename);
4306 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4308 return readFile(fn);
4312 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4314 TeXErrors::Errors::const_iterator it = terr.begin();
4315 TeXErrors::Errors::const_iterator end = terr.end();
4316 ListOfBuffers clist = getDescendents();
4317 ListOfBuffers::const_iterator cen = clist.end();
4319 for (; it != end; ++it) {
4322 int errorRow = it->error_in_line;
4323 Buffer const * buf = 0;
4325 if (it->child_name.empty())
4326 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4328 // The error occurred in a child
4329 ListOfBuffers::const_iterator cit = clist.begin();
4330 for (; cit != cen; ++cit) {
4331 string const child_name =
4332 DocFileName(changeExtension(
4333 (*cit)->absFileName(), "tex")).
4335 if (it->child_name != child_name)
4337 (*cit)->d->texrow.getIdFromRow(errorRow,
4338 id_start, pos_start);
4339 if (id_start != -1) {
4340 buf = d->cloned_buffer_
4341 ? (*cit)->d->cloned_buffer_->d->owner_
4342 : (*cit)->d->owner_;
4353 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4354 } while (found && id_start == id_end && pos_start == pos_end);
4356 if (id_start != id_end) {
4357 // Next registered position is outside the inset where
4358 // the error occurred, so signal end-of-paragraph
4362 errorList.push_back(ErrorItem(it->error_desc,
4363 it->error_text, id_start, pos_start, pos_end, buf));
4368 void Buffer::setBuffersForInsets() const
4370 inset().setBuffer(const_cast<Buffer &>(*this));
4374 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4376 LBUFERR(!text().paragraphs().empty());
4378 // Use the master text class also for child documents
4379 Buffer const * const master = masterBuffer();
4380 DocumentClass const & textclass = master->params().documentClass();
4382 // do this only if we are the top-level Buffer
4383 if (master == this) {
4384 textclass.counters().reset(from_ascii("bibitem"));
4385 reloadBibInfoCache();
4388 // keep the buffers to be children in this set. If the call from the
4389 // master comes back we can see which of them were actually seen (i.e.
4390 // via an InsetInclude). The remaining ones in the set need still be updated.
4391 static std::set<Buffer const *> bufToUpdate;
4392 if (scope == UpdateMaster) {
4393 // If this is a child document start with the master
4394 if (master != this) {
4395 bufToUpdate.insert(this);
4396 master->updateBuffer(UpdateMaster, utype);
4397 // If the master buffer has no gui associated with it, then the TocModel is
4398 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4399 // (bug 5699). The same happens if the master buffer is open in a different
4400 // window. This test catches both possibilities.
4401 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4402 // There remains a problem here: If there is another child open in yet a third
4403 // window, that TOC is not updated. So some more general solution is needed at
4405 if (master->d->gui_ != d->gui_)
4408 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4409 if (bufToUpdate.find(this) == bufToUpdate.end())
4413 // start over the counters in the master
4414 textclass.counters().reset();
4417 // update will be done below for this buffer
4418 bufToUpdate.erase(this);
4420 // update all caches
4421 clearReferenceCache();
4424 Buffer & cbuf = const_cast<Buffer &>(*this);
4427 ParIterator parit = cbuf.par_iterator_begin();
4428 updateBuffer(parit, utype);
4431 // TocBackend update will be done later.
4434 d->bibinfo_cache_valid_ = true;
4435 d->cite_labels_valid_ = true;
4436 cbuf.tocBackend().update(utype == OutputUpdate);
4437 if (scope == UpdateMaster)
4438 cbuf.structureChanged();
4442 static depth_type getDepth(DocIterator const & it)
4444 depth_type depth = 0;
4445 for (size_t i = 0 ; i < it.depth() ; ++i)
4446 if (!it[i].inset().inMathed())
4447 depth += it[i].paragraph().getDepth() + 1;
4448 // remove 1 since the outer inset does not count
4452 static depth_type getItemDepth(ParIterator const & it)
4454 Paragraph const & par = *it;
4455 LabelType const labeltype = par.layout().labeltype;
4457 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4460 // this will hold the lowest depth encountered up to now.
4461 depth_type min_depth = getDepth(it);
4462 ParIterator prev_it = it;
4465 --prev_it.top().pit();
4467 // start of nested inset: go to outer par
4469 if (prev_it.empty()) {
4470 // start of document: nothing to do
4475 // We search for the first paragraph with same label
4476 // that is not more deeply nested.
4477 Paragraph & prev_par = *prev_it;
4478 depth_type const prev_depth = getDepth(prev_it);
4479 if (labeltype == prev_par.layout().labeltype) {
4480 if (prev_depth < min_depth)
4481 return prev_par.itemdepth + 1;
4482 if (prev_depth == min_depth)
4483 return prev_par.itemdepth;
4485 min_depth = min(min_depth, prev_depth);
4486 // small optimization: if we are at depth 0, we won't
4487 // find anything else
4488 if (prev_depth == 0)
4494 static bool needEnumCounterReset(ParIterator const & it)
4496 Paragraph const & par = *it;
4497 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4498 depth_type const cur_depth = par.getDepth();
4499 ParIterator prev_it = it;
4500 while (prev_it.pit()) {
4501 --prev_it.top().pit();
4502 Paragraph const & prev_par = *prev_it;
4503 if (prev_par.getDepth() <= cur_depth)
4504 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4506 // start of nested inset: reset
4511 // set the label of a paragraph. This includes the counters.
4512 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4514 BufferParams const & bp = owner_->masterBuffer()->params();
4515 DocumentClass const & textclass = bp.documentClass();
4516 Paragraph & par = it.paragraph();
4517 Layout const & layout = par.layout();
4518 Counters & counters = textclass.counters();
4520 if (par.params().startOfAppendix()) {
4521 // We want to reset the counter corresponding to toplevel sectioning
4522 Layout const & lay = textclass.getTOCLayout();
4523 docstring const cnt = lay.counter;
4525 counters.reset(cnt);
4526 counters.appendix(true);
4528 par.params().appendix(counters.appendix());
4530 // Compute the item depth of the paragraph
4531 par.itemdepth = getItemDepth(it);
4533 if (layout.margintype == MARGIN_MANUAL) {
4534 if (par.params().labelWidthString().empty())
4535 par.params().labelWidthString(par.expandLabel(layout, bp));
4536 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4537 // we do not need to do anything here, since the empty case is
4538 // handled during export.
4540 par.params().labelWidthString(docstring());
4543 switch(layout.labeltype) {
4544 case LABEL_ITEMIZE: {
4545 // At some point of time we should do something more
4546 // clever here, like:
4547 // par.params().labelString(
4548 // bp.user_defined_bullet(par.itemdepth).getText());
4549 // for now, use a simple hardcoded label
4550 docstring itemlabel;
4551 switch (par.itemdepth) {
4553 itemlabel = char_type(0x2022);
4556 itemlabel = char_type(0x2013);
4559 itemlabel = char_type(0x2217);
4562 itemlabel = char_type(0x2219); // or 0x00b7
4565 par.params().labelString(itemlabel);
4569 case LABEL_ENUMERATE: {
4570 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4572 switch (par.itemdepth) {
4581 enumcounter += "iv";
4584 // not a valid enumdepth...
4588 // Maybe we have to reset the enumeration counter.
4589 if (needEnumCounterReset(it))
4590 counters.reset(enumcounter);
4591 counters.step(enumcounter, utype);
4593 string const & lang = par.getParLanguage(bp)->code();
4594 par.params().labelString(counters.theCounter(enumcounter, lang));
4599 case LABEL_SENSITIVE: {
4600 string const & type = counters.current_float();
4601 docstring full_label;
4603 full_label = owner_->B_("Senseless!!! ");
4605 docstring name = owner_->B_(textclass.floats().getType(type).name());
4606 if (counters.hasCounter(from_utf8(type))) {
4607 string const & lang = par.getParLanguage(bp)->code();
4608 counters.step(from_utf8(type), utype);
4609 full_label = bformat(from_ascii("%1$s %2$s:"),
4611 counters.theCounter(from_utf8(type), lang));
4613 full_label = bformat(from_ascii("%1$s #:"), name);
4615 par.params().labelString(full_label);
4619 case LABEL_NO_LABEL:
4620 par.params().labelString(docstring());
4624 case LABEL_CENTERED:
4625 case LABEL_STATIC: {
4626 docstring const & lcounter = layout.counter;
4627 if (!lcounter.empty()) {
4628 if (layout.toclevel <= bp.secnumdepth
4629 && (layout.latextype != LATEX_ENVIRONMENT
4630 || it.text()->isFirstInSequence(it.pit()))) {
4631 if (counters.hasCounter(lcounter))
4632 counters.step(lcounter, utype);
4633 par.params().labelString(par.expandLabel(layout, bp));
4635 par.params().labelString(docstring());
4637 par.params().labelString(par.expandLabel(layout, bp));
4643 par.params().labelString(par.expandLabel(layout, bp));
4648 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4650 // LASSERT: Is it safe to continue here, or should we just return?
4651 LASSERT(parit.pit() == 0, /**/);
4653 // Set the position of the text in the buffer to be able
4654 // to resolve macros in it.
4655 parit.text()->setMacrocontextPosition(parit);
4657 depth_type maxdepth = 0;
4658 pit_type const lastpit = parit.lastpit();
4659 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4660 // reduce depth if necessary
4661 if (parit->params().depth() > maxdepth) {
4662 /** FIXME: this function is const, but
4663 * nevertheless it modifies the buffer. To be
4664 * cleaner, one should modify the buffer in
4665 * another function, which is actually
4666 * non-const. This would however be costly in
4667 * terms of code duplication.
4669 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4670 parit->params().depth(maxdepth);
4672 maxdepth = parit->getMaxDepthAfter();
4674 if (utype == OutputUpdate) {
4675 // track the active counters
4676 // we have to do this for the master buffer, since the local
4677 // buffer isn't tracking anything.
4678 masterBuffer()->params().documentClass().counters().
4679 setActiveLayout(parit->layout());
4682 // set the counter for this paragraph
4683 d->setLabel(parit, utype);
4686 InsetList::const_iterator iit = parit->insetList().begin();
4687 InsetList::const_iterator end = parit->insetList().end();
4688 for (; iit != end; ++iit) {
4689 parit.pos() = iit->pos;
4690 iit->inset->updateBuffer(parit, utype);
4696 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4697 WordLangTuple & word_lang, docstring_list & suggestions) const
4701 suggestions.clear();
4702 word_lang = WordLangTuple();
4703 bool const to_end = to.empty();
4704 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4705 // OK, we start from here.
4706 for (; from != end; from.forwardPos()) {
4707 // We are only interested in text so remove the math CursorSlice.
4708 while (from.inMathed()) {
4712 // If from is at the end of the document (which is possible
4713 // when leaving the mathed) LyX will crash later otherwise.
4714 if (from.atEnd() || (!to_end && from >= end))
4717 from.paragraph().spellCheck();
4718 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4719 if (SpellChecker::misspelled(res)) {
4724 // Do not increase progress when from == to, otherwise the word
4725 // count will be wrong.
4735 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4737 bool inword = false;
4742 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4743 if (!dit.inTexted()) {
4748 Paragraph const & par = dit.paragraph();
4749 pos_type const pos = dit.pos();
4751 // Copied and adapted from isWordSeparator() in Paragraph
4752 if (pos == dit.lastpos()) {
4755 Inset const * ins = par.getInset(pos);
4756 if (ins && skipNoOutput && !ins->producesOutput()) {
4759 // stop if end of range was skipped
4760 if (!to.atEnd() && dit >= to)
4763 } else if (!par.isDeleted(pos)) {
4764 if (par.isWordSeparator(pos))
4770 if (ins && ins->isLetter())
4772 else if (ins && ins->isSpace())
4775 char_type const c = par.getChar(pos);
4776 if (isPrintableNonspace(c))
4778 else if (isSpace(c))
4788 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4790 d->updateStatistics(from, to, skipNoOutput);
4794 int Buffer::wordCount() const
4796 return d->wordCount();
4800 int Buffer::charCount(bool with_blanks) const
4802 return d->charCount(with_blanks);
4806 Buffer::ReadStatus Buffer::reload()
4809 // c.f. bug http://www.lyx.org/trac/ticket/6587
4810 removeAutosaveFile();
4811 // e.g., read-only status could have changed due to version control
4812 d->filename.refresh();
4813 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4815 // clear parent. this will get reset if need be.
4817 ReadStatus const status = loadLyXFile();
4818 if (status == ReadSuccess) {
4823 message(bformat(_("Document %1$s reloaded."), disp_fn));
4826 message(bformat(_("Could not reload document %1$s."), disp_fn));
4836 bool Buffer::saveAs(FileName const & fn)
4838 FileName const old_name = fileName();
4839 FileName const old_auto = getAutosaveFileName();
4840 bool const old_unnamed = isUnnamed();
4847 // bring the autosave file with us, just in case.
4848 moveAutosaveFile(old_auto);
4849 // validate version control data and
4850 // correct buffer title
4851 lyxvc().file_found_hook(fileName());
4853 // the file has now been saved to the new location.
4854 // we need to check that the locations of child buffers
4856 checkChildBuffers();
4857 checkMasterBuffer();
4861 // reset the old filename and unnamed state
4862 setFileName(old_name);
4863 setUnnamed(old_unnamed);
4869 // FIXME We could do better here, but it is complicated. What would be
4870 // nice is to offer either (a) to save the child buffer to an appropriate
4871 // location, so that it would "move with the master", or else (b) to update
4872 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4873 // complicated, because the code for this lives in GuiView.
4874 void Buffer::checkChildBuffers()
4876 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4877 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4878 for (; it != en; ++it) {
4879 DocIterator dit = it->second;
4880 Buffer * cbuf = const_cast<Buffer *>(it->first);
4881 if (!cbuf || !theBufferList().isLoaded(cbuf))
4883 Inset * inset = dit.nextInset();
4884 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4885 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4886 docstring const & incfile = inset_inc->getParam("filename");
4887 string oldloc = cbuf->absFileName();
4888 string newloc = makeAbsPath(to_utf8(incfile),
4889 onlyPath(absFileName())).absFileName();
4890 if (oldloc == newloc)
4892 // the location of the child file is incorrect.
4893 Alert::warning(_("Included File Invalid"),
4894 bformat(_("Saving this document to a new location has made the file:\n"
4896 "inaccessible. You will need to update the included filename."),
4897 from_utf8(oldloc)));
4899 inset_inc->setChildBuffer(0);
4901 // invalidate cache of children
4902 d->children_positions.clear();
4903 d->position_to_children.clear();
4907 // If a child has been saved under a different name/path, it might have been
4908 // orphaned. Therefore the master needs to be reset (bug 8161).
4909 void Buffer::checkMasterBuffer()
4911 Buffer const * const master = masterBuffer();
4915 // necessary to re-register the child (bug 5873)
4916 // FIXME: clean up updateMacros (here, only
4917 // child registering is needed).
4918 master->updateMacros();
4919 // (re)set master as master buffer, but only
4920 // if we are a real child
4921 if (master->isChild(this))