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/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
121 using namespace lyx::support;
122 using namespace lyx::graphics;
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
136 void showPrintError(string const & name)
138 docstring str = bformat(_("Could not print the document %1$s.\n"
139 "Check that your printer is set up correctly."),
140 makeDisplayPath(name, 50));
141 Alert::error(_("Print document failed"), str);
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
154 Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
158 delete preview_loader_;
166 /// search for macro in local (buffer) table or in children
167 MacroData const * getBufferMacro(docstring const & name,
168 DocIterator const & pos) const;
170 /// Update macro table starting with position of it \param it in some
172 void updateMacros(DocIterator & it, DocIterator & scope);
174 void setLabel(ParIterator & it, UpdateType utype) const;
176 /** If we have branches that use the file suffix
177 feature, return the file name with suffix appended.
179 support::FileName exportFileName() const;
186 mutable TexRow texrow;
188 /// need to regenerate .tex?
192 mutable bool lyx_clean;
194 /// is autosave needed?
195 mutable bool bak_clean;
197 /// is this an unnamed file (New...)?
200 /// is this an internal bufffer?
201 bool internal_buffer;
206 /// name of the file the buffer is associated with.
209 /** Set to true only when the file is fully loaded.
210 * Used to prevent the premature generation of previews
211 * and by the citation inset.
213 bool file_fully_loaded;
215 /// Ignore the parent (e.g. when exporting a child standalone)?
219 mutable TocBackend toc_backend;
224 ScopeMacro(DocIterator const & s, MacroData const & m)
225 : scope(s), macro(m) {}
229 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231 /// map from the macro name to the position map,
232 /// which maps the macro definition position to the scope and the MacroData.
233 NamePositionScopeMacroMap macros;
234 /// This seem to change the way Buffer::getMacro() works
235 mutable bool macro_lock;
237 /// positions of child buffers in the buffer
238 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
241 ScopeBuffer(DocIterator const & s,Buffer const * b)
242 : scope(s), buffer(b) {}
244 Buffer const * buffer;
246 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247 /// position of children buffers in this buffer
248 BufferPositionMap children_positions;
249 /// map from children inclusion positions to their scope and their buffer
250 PositionScopeBufferMap position_to_children;
252 /// Contains the old buffer filePath() while saving-as, or the
253 /// directory where the document was last saved while loading.
256 /** Keeps track of the path of local layout files.
257 * If possible, it is always relative to the buffer path.
258 * Empty for layouts in system or user directory.
260 string layout_position;
262 /// Container for all sort of Buffer dependant errors.
263 map<string, ErrorList> errorLists;
265 /// timestamp and checksum used to test if the file has been externally
266 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
268 unsigned long checksum_;
271 frontend::WorkAreaManager * wa_;
273 frontend::GuiBufferDelegate * gui_;
278 /// A cache for the bibfiles (including bibfiles of loaded child
279 /// documents), needed for appropriate update of natbib labels.
280 mutable support::FileNameList bibfiles_cache_;
282 // FIXME The caching mechanism could be improved. At present, we have a
283 // cache for each Buffer, that caches all the bibliography info for that
284 // Buffer. A more efficient solution would be to have a global cache per
285 // file, and then to construct the Buffer's bibinfo from that.
286 /// A cache for bibliography info
287 mutable BiblioInfo bibinfo_;
288 /// whether the bibinfo cache is valid
289 mutable bool bibinfo_cache_valid_;
290 /// whether the bibfile cache is valid
291 mutable bool bibfile_cache_valid_;
292 /// Cache of timestamps of .bib files
293 map<FileName, time_t> bibfile_status_;
294 /// Indicates whether the bibinfo has changed since the last time
295 /// we ran updateBuffer(), i.e., whether citation labels may need
297 mutable bool cite_labels_valid_;
299 /// These two hold the file name and format, written to by
300 /// Buffer::preview and read from by LFUN_BUFFER_VIEW_CACHE.
301 FileName preview_file_;
302 string preview_format_;
303 /// If there was an error when previewing, on the next preview we do
304 /// a fresh compile (e.g. in case the user installed a package that
308 mutable RefCache ref_cache_;
310 /// our Text that should be wrapped in an InsetText
314 PreviewLoader * preview_loader_;
316 /// This is here to force the test to be done whenever parent_buffer
318 Buffer const * parent() const
320 // ignore_parent temporarily "orphans" a buffer
321 // (e.g. if a child is compiled standalone)
324 // if parent_buffer is not loaded, then it has been unloaded,
325 // which means that parent_buffer is an invalid pointer. So we
326 // set it to null in that case.
327 // however, the BufferList doesn't know about cloned buffers, so
328 // they will always be regarded as unloaded. in that case, we hope
330 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
332 return parent_buffer;
336 void setParent(Buffer const * pb)
338 if (parent_buffer == pb)
341 if (!cloned_buffer_ && parent_buffer && pb)
342 LYXERR0("Warning: a buffer should not have two parents!");
344 if (!cloned_buffer_ && parent_buffer) {
345 parent_buffer->invalidateBibfileCache();
346 parent_buffer->invalidateBibinfoCache();
350 /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
351 /// This one is useful for preview detached in a thread.
352 Buffer const * cloned_buffer_;
354 CloneList * clone_list_;
355 /// are we in the process of exporting this buffer?
356 mutable bool doing_export;
358 /// compute statistics
359 /// \p from initial position
360 /// \p to points to the end position
361 void updateStatistics(DocIterator & from, DocIterator & to,
362 bool skipNoOutput = true);
363 /// statistics accessor functions
364 int wordCount() const
368 int charCount(bool with_blanks) const
371 + (with_blanks ? blank_count_ : 0);
375 /// So we can force access via the accessors.
376 mutable Buffer const * parent_buffer;
385 /// Creates the per buffer temporary directory
386 static FileName createBufferTmpDir()
388 // FIXME This would be the ideal application for a TempDir class (like
389 // TempFile but for directories)
394 Mutex::Locker locker(&mutex);
395 counter = convert<string>(count++);
397 // We are in our own directory. Why bother to mangle name?
398 // In fact I wrote this code to circumvent a problematic behaviour
399 // (bug?) of EMX mkstemp().
400 FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
403 if (!tmpfl.createDirectory(0777)) {
404 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
405 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
406 from_utf8(tmpfl.absFileName())));
412 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
413 Buffer const * cloned_buffer)
414 : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
415 internal_buffer(false), read_only(readonly_), filename(file),
416 file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
417 macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
418 undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
419 cite_labels_valid_(false), inset(0), preview_loader_(0),
420 cloned_buffer_(cloned_buffer), clone_list_(0),
421 doing_export(false), parent_buffer(0),
422 word_count_(0), char_count_(0), blank_count_(0)
424 if (!cloned_buffer_) {
425 temppath = createBufferTmpDir();
426 lyxvc.setBuffer(owner_);
428 wa_ = new frontend::WorkAreaManager;
431 temppath = cloned_buffer_->d->temppath;
432 file_fully_loaded = true;
433 params = cloned_buffer_->d->params;
434 bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
435 bibinfo_ = cloned_buffer_->d->bibinfo_;
436 bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
437 bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
438 bibfile_status_ = cloned_buffer_->d->bibfile_status_;
439 cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
440 unnamed = cloned_buffer_->d->unnamed;
441 internal_buffer = cloned_buffer_->d->internal_buffer;
442 layout_position = cloned_buffer_->d->layout_position;
443 preview_file_ = cloned_buffer_->d->preview_file_;
444 preview_format_ = cloned_buffer_->d->preview_format_;
445 preview_error_ = cloned_buffer_->d->preview_error_;
449 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
450 : d(new Impl(this, FileName(file), readonly, cloned_buffer))
452 LYXERR(Debug::INFO, "Buffer::Buffer()");
454 d->inset = new InsetText(*cloned_buffer->d->inset);
455 d->inset->setBuffer(*this);
456 // FIXME: optimize this loop somewhat, maybe by creating a new
457 // general recursive Inset::setId().
458 DocIterator it = doc_iterator_begin(this);
459 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
460 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
461 it.paragraph().setId(cloned_it.paragraph().id());
463 d->inset = new InsetText(this);
464 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
470 LYXERR(Debug::INFO, "Buffer::~Buffer()");
471 // here the buffer should take care that it is
472 // saved properly, before it goes into the void.
474 // GuiView already destroyed
478 // No need to do additional cleanups for internal buffer.
484 // this is in case of recursive includes: we won't try to delete
485 // ourselves as a child.
486 d->clone_list_->erase(this);
487 // loop over children
488 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
489 Impl::BufferPositionMap::iterator end = d->children_positions.end();
490 for (; it != end; ++it) {
491 Buffer * child = const_cast<Buffer *>(it->first);
492 if (d->clone_list_->erase(child))
495 // if we're the master buffer, then we should get rid of the list
498 // If this is not empty, we have leaked something. Worse, one of the
499 // children still has a reference to this list. But we will try to
500 // continue, rather than shut down.
501 LATTEST(d->clone_list_->empty());
502 list<CloneList *>::iterator it =
503 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
504 if (it == cloned_buffers.end()) {
505 // We will leak in this case, but it is safe to continue.
508 cloned_buffers.erase(it);
509 delete d->clone_list_;
511 // FIXME Do we really need to do this right before we delete d?
512 // clear references to children in macro tables
513 d->children_positions.clear();
514 d->position_to_children.clear();
516 // loop over children
517 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
518 Impl::BufferPositionMap::iterator end = d->children_positions.end();
519 for (; it != end; ++it) {
520 Buffer * child = const_cast<Buffer *>(it->first);
521 if (theBufferList().isLoaded(child))
522 theBufferList().releaseChild(this, child);
526 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
527 msg += emergencyWrite();
528 Alert::warning(_("Attempting to close changed document!"), msg);
531 // FIXME Do we really need to do this right before we delete d?
532 // clear references to children in macro tables
533 d->children_positions.clear();
534 d->position_to_children.clear();
536 if (!d->temppath.destroyDirectory()) {
537 Alert::warning(_("Could not remove temporary directory"),
538 bformat(_("Could not remove the temporary directory %1$s"),
539 from_utf8(d->temppath.absFileName())));
548 Buffer * Buffer::cloneFromMaster() const
551 cloned_buffers.push_back(new CloneList);
552 CloneList * clones = cloned_buffers.back();
554 masterBuffer()->cloneWithChildren(bufmap, clones);
556 // make sure we got cloned
557 BufferMap::const_iterator bit = bufmap.find(this);
558 LASSERT(bit != bufmap.end(), return 0);
559 Buffer * cloned_buffer = bit->second;
561 return cloned_buffer;
565 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
567 // have we already been cloned?
568 if (bufmap.find(this) != bufmap.end())
571 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
573 // The clone needs its own DocumentClass, since running updateBuffer() will
574 // modify it, and we would otherwise be sharing it with the original Buffer.
575 buffer_clone->params().makeDocumentClass(true);
577 cap::switchBetweenClasses(
578 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
579 static_cast<InsetText &>(buffer_clone->inset()), el);
581 bufmap[this] = buffer_clone;
582 clones->insert(buffer_clone);
583 buffer_clone->d->clone_list_ = clones;
584 buffer_clone->d->macro_lock = true;
585 buffer_clone->d->children_positions.clear();
587 // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
588 // math macro caches need to be rethought and simplified.
589 // I am not sure wether we should handle Buffer cloning here or in BufferList.
590 // Right now BufferList knows nothing about buffer clones.
591 Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
592 Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
593 for (; it != end; ++it) {
594 DocIterator dit = it->first.clone(buffer_clone);
595 dit.setBuffer(buffer_clone);
596 Buffer * child = const_cast<Buffer *>(it->second.buffer);
598 child->cloneWithChildren(bufmap, clones);
599 BufferMap::iterator const bit = bufmap.find(child);
600 LASSERT(bit != bufmap.end(), continue);
601 Buffer * child_clone = bit->second;
603 Inset * inset = dit.nextInset();
604 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
605 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
606 inset_inc->setChildBuffer(child_clone);
607 child_clone->d->setParent(buffer_clone);
608 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
609 buffer_clone->setChild(dit, child_clone);
611 buffer_clone->d->macro_lock = false;
616 Buffer * Buffer::cloneBufferOnly() const {
617 cloned_buffers.push_back(new CloneList);
618 CloneList * clones = cloned_buffers.back();
619 Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
621 // The clone needs its own DocumentClass, since running updateBuffer() will
622 // modify it, and we would otherwise be sharing it with the original Buffer.
623 buffer_clone->params().makeDocumentClass(true);
625 cap::switchBetweenClasses(
626 params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
627 static_cast<InsetText &>(buffer_clone->inset()), el);
629 clones->insert(buffer_clone);
630 buffer_clone->d->clone_list_ = clones;
632 // we won't be cloning the children
633 buffer_clone->d->children_positions.clear();
638 bool Buffer::isClone() const
640 return d->cloned_buffer_;
644 void Buffer::changed(bool update_metrics) const
647 d->wa_->redrawAll(update_metrics);
651 frontend::WorkAreaManager & Buffer::workAreaManager() const
658 Text & Buffer::text() const
660 return d->inset->text();
664 Inset & Buffer::inset() const
670 BufferParams & Buffer::params()
676 BufferParams const & Buffer::params() const
682 BufferParams const & Buffer::masterParams() const
684 if (masterBuffer() == this)
687 BufferParams & mparams = const_cast<Buffer *>(masterBuffer())->params();
688 // Copy child authors to the params. We need those pointers.
689 AuthorList const & child_authors = params().authors();
690 AuthorList::Authors::const_iterator it = child_authors.begin();
691 for (; it != child_authors.end(); ++it)
692 mparams.authors().record(*it);
697 double Buffer::fontScalingFactor() const
699 return isExporting() ? 75.0 * params().html_math_img_scale
700 : 0.01 * lyxrc.dpi * lyxrc.zoom * lyxrc.preview_scale_factor * params().display_pixel_ratio;
704 ParagraphList & Buffer::paragraphs()
706 return text().paragraphs();
710 ParagraphList const & Buffer::paragraphs() const
712 return text().paragraphs();
716 LyXVC & Buffer::lyxvc()
722 LyXVC const & Buffer::lyxvc() const
728 string const Buffer::temppath() const
730 return d->temppath.absFileName();
734 TexRow & Buffer::texrow()
740 TexRow const & Buffer::texrow() const
746 TocBackend & Buffer::tocBackend() const
748 return d->toc_backend;
752 Undo & Buffer::undo()
758 void Buffer::setChild(DocIterator const & dit, Buffer * child)
760 d->children_positions[child] = dit;
764 string Buffer::latexName(bool const no_path) const
766 FileName latex_name =
767 makeLatexName(d->exportFileName());
768 return no_path ? latex_name.onlyFileName()
769 : latex_name.absFileName();
773 FileName Buffer::Impl::exportFileName() const
775 docstring const branch_suffix =
776 params.branchlist().getFileNameSuffix();
777 if (branch_suffix.empty())
780 string const name = filename.onlyFileNameWithoutExt()
781 + to_utf8(branch_suffix);
782 FileName res(filename.onlyPath().absFileName() + "/" + name);
783 res.changeExtension(filename.extension());
789 string Buffer::logName(LogType * type) const
791 string const filename = latexName(false);
793 if (filename.empty()) {
799 string const path = temppath();
801 FileName const fname(addName(temppath(),
802 onlyFileName(changeExtension(filename,
805 // FIXME: how do we know this is the name of the build log?
806 FileName const bname(
807 addName(path, onlyFileName(
808 changeExtension(filename,
809 formats.extension(params().bufferFormat()) + ".out"))));
811 // Also consider the master buffer log file
812 FileName masterfname = fname;
813 LogType mtype = latexlog;
814 if (masterBuffer() != this) {
815 string const mlogfile = masterBuffer()->logName(&mtype);
816 masterfname = FileName(mlogfile);
819 // If no Latex log or Build log is newer, show Build log
820 if (bname.exists() &&
821 ((!fname.exists() && !masterfname.exists())
822 || (fname.lastModified() < bname.lastModified()
823 && masterfname.lastModified() < bname.lastModified()))) {
824 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
827 return bname.absFileName();
828 // If we have a newer master file log or only a master log, show this
829 } else if (fname != masterfname
830 && (!fname.exists() && (masterfname.exists()
831 || fname.lastModified() < masterfname.lastModified()))) {
832 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
835 return masterfname.absFileName();
837 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
840 return fname.absFileName();
844 void Buffer::setReadonly(bool const flag)
846 if (d->read_only != flag) {
853 void Buffer::setFileName(FileName const & fname)
855 bool const changed = fname != d->filename;
858 lyxvc().file_found_hook(fname);
859 setReadonly(d->filename.isReadOnly());
865 int Buffer::readHeader(Lexer & lex)
867 int unknown_tokens = 0;
869 int begin_header_line = -1;
871 // Initialize parameters that may be/go lacking in header:
872 params().branchlist().clear();
873 params().preamble.erase();
874 params().options.erase();
875 params().master.erase();
876 params().float_placement.erase();
877 params().paperwidth.erase();
878 params().paperheight.erase();
879 params().leftmargin.erase();
880 params().rightmargin.erase();
881 params().topmargin.erase();
882 params().bottommargin.erase();
883 params().headheight.erase();
884 params().headsep.erase();
885 params().footskip.erase();
886 params().columnsep.erase();
887 params().fonts_cjk.erase();
888 params().listings_params.clear();
889 params().clearLayoutModules();
890 params().clearRemovedModules();
891 params().clearIncludedChildren();
892 params().pdfoptions().clear();
893 params().indiceslist().clear();
894 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
895 params().isbackgroundcolor = false;
896 params().fontcolor = RGBColor(0, 0, 0);
897 params().isfontcolor = false;
898 params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
899 params().boxbgcolor = RGBColor(0xFF, 0, 0);
900 params().html_latex_start.clear();
901 params().html_latex_end.clear();
902 params().html_math_img_scale = 1.0;
903 params().output_sync_macro.erase();
904 params().setLocalLayout(string(), false);
905 params().setLocalLayout(string(), true);
907 for (int i = 0; i < 4; ++i) {
908 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
909 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
912 ErrorList & errorList = d->errorLists["Parse"];
921 if (token == "\\end_header")
925 if (token == "\\begin_header") {
926 begin_header_line = line;
930 LYXERR(Debug::PARSER, "Handling document header token: `"
933 string const result =
934 params().readToken(lex, token, d->filename.onlyPath());
935 if (!result.empty()) {
936 if (token == "\\textclass") {
937 d->layout_position = result;
940 docstring const s = bformat(_("Unknown token: "
944 errorList.push_back(ErrorItem(_("Document header error"),
949 if (begin_header_line) {
950 docstring const s = _("\\begin_header is missing");
951 errorList.push_back(ErrorItem(_("Document header error"),
955 params().makeDocumentClass();
957 return unknown_tokens;
962 // changed to be public and have one parameter
963 // Returns true if "\end_document" is not read (Asger)
964 bool Buffer::readDocument(Lexer & lex)
966 ErrorList & errorList = d->errorLists["Parse"];
969 // remove dummy empty par
970 paragraphs().clear();
972 if (!lex.checkFor("\\begin_document")) {
973 docstring const s = _("\\begin_document is missing");
974 errorList.push_back(ErrorItem(_("Document header error"),
980 if (params().output_changes) {
981 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
982 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
983 LaTeXFeatures::isAvailable("xcolor");
985 if (!dvipost && !xcolorulem) {
986 Alert::warning(_("Changes not shown in LaTeX output"),
987 _("Changes will not be highlighted in LaTeX output, "
988 "because neither dvipost nor xcolor/ulem are installed.\n"
989 "Please install these packages or redefine "
990 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
991 } else if (!xcolorulem) {
992 Alert::warning(_("Changes not shown in LaTeX output"),
993 _("Changes will not be highlighted in LaTeX output "
994 "when using pdflatex, because xcolor and ulem are not installed.\n"
995 "Please install both packages or redefine "
996 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
1000 if (!parent() && !params().master.empty()) {
1001 FileName const master_file = makeAbsPath(params().master,
1002 onlyPath(absFileName()));
1003 if (isLyXFileName(master_file.absFileName())) {
1005 checkAndLoadLyXFile(master_file, true);
1007 // necessary e.g. after a reload
1008 // to re-register the child (bug 5873)
1009 // FIXME: clean up updateMacros (here, only
1010 // child registering is needed).
1011 master->updateMacros();
1012 // set master as master buffer, but only
1013 // if we are a real child
1014 if (master->isChild(this))
1016 // if the master is not fully loaded
1017 // it is probably just loading this
1018 // child. No warning needed then.
1019 else if (master->isFullyLoaded())
1020 LYXERR0("The master '"
1022 << "' assigned to this document ("
1024 << ") does not include "
1025 "this document. Ignoring the master assignment.");
1030 // assure we have a default index
1031 params().indiceslist().addDefault(B_("Index"));
1034 d->old_position = originFilePath();
1035 bool const res = text().read(lex, errorList, d->inset);
1036 d->old_position.clear();
1038 // inform parent buffer about local macros
1040 Buffer const * pbuf = parent();
1041 UserMacroSet::const_iterator cit = usermacros.begin();
1042 UserMacroSet::const_iterator end = usermacros.end();
1043 for (; cit != end; ++cit)
1044 pbuf->usermacros.insert(*cit);
1048 updateMacroInstances(InternalUpdate);
1053 bool Buffer::importString(string const & format, docstring const & contents, ErrorList & errorList)
1055 Format const * fmt = formats.getFormat(format);
1058 // It is important to use the correct extension here, since some
1059 // converters create a wrong output file otherwise (e.g. html2latex)
1060 TempFile const tempfile("Buffer_importStringXXXXXX." + fmt->extension());
1061 FileName const name(tempfile.name());
1062 ofdocstream os(name.toFilesystemEncoding().c_str());
1063 // Do not convert os implicitly to bool, since that is forbidden in C++11.
1064 bool const success = !(os << contents).fail();
1067 bool converted = false;
1069 params().compressed = false;
1071 // remove dummy empty par
1072 paragraphs().clear();
1074 converted = importFile(format, name, errorList);
1083 bool Buffer::importFile(string const & format, FileName const & name, ErrorList & errorList)
1085 if (!theConverters().isReachable(format, "lyx"))
1088 TempFile const tempfile("Buffer_importFileXXXXXX.lyx");
1089 FileName const lyx(tempfile.name());
1090 if (theConverters().convert(0, name, lyx, name, format, "lyx", errorList))
1091 return readFile(lyx) == ReadSuccess;
1097 bool Buffer::readString(string const & s)
1099 params().compressed = false;
1102 istringstream is(s);
1104 TempFile tempfile("Buffer_readStringXXXXXX.lyx");
1105 FileName const fn = tempfile.name();
1108 bool success = parseLyXFormat(lex, fn, file_format) == ReadSuccess;
1110 if (success && file_format != LYX_FORMAT) {
1111 // We need to call lyx2lyx, so write the input to a file
1112 ofstream os(fn.toFilesystemEncoding().c_str());
1115 // lyxvc in readFile
1116 if (readFile(fn) != ReadSuccess)
1120 if (readDocument(lex))
1126 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1130 if (!lex.setFile(fname)) {
1131 Alert::error(_("File Not Found"),
1132 bformat(_("Unable to open file `%1$s'."),
1133 from_utf8(fn.absFileName())));
1134 return ReadFileNotFound;
1138 ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1139 if (ret_plf != ReadSuccess)
1142 if (file_format != LYX_FORMAT) {
1144 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1145 if (ret_clf != ReadSuccess)
1147 return readFile(tmpFile);
1150 // FIXME: InsetInfo needs to know whether the file is under VCS
1151 // during the parse process, so this has to be done before.
1152 lyxvc().file_found_hook(d->filename);
1154 if (readDocument(lex)) {
1155 Alert::error(_("Document format failure"),
1156 bformat(_("%1$s ended unexpectedly, which means"
1157 " that it is probably corrupted."),
1158 from_utf8(fn.absFileName())));
1159 return ReadDocumentFailure;
1162 d->file_fully_loaded = true;
1163 d->read_only = !d->filename.isWritable();
1164 params().compressed = formats.isZippedFile(d->filename);
1170 bool Buffer::isFullyLoaded() const
1172 return d->file_fully_loaded;
1176 void Buffer::setFullyLoaded(bool value)
1178 d->file_fully_loaded = value;
1182 bool Buffer::lastPreviewError() const
1184 return d->preview_error_;
1188 PreviewLoader * Buffer::loader() const
1190 if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1192 if (!d->preview_loader_)
1193 d->preview_loader_ = new PreviewLoader(*this);
1194 return d->preview_loader_;
1198 void Buffer::removePreviews() const
1200 delete d->preview_loader_;
1201 d->preview_loader_ = 0;
1205 void Buffer::updatePreviews() const
1207 PreviewLoader * ploader = loader();
1211 InsetIterator it = inset_iterator_begin(*d->inset);
1212 InsetIterator const end = inset_iterator_end(*d->inset);
1213 for (; it != end; ++it)
1214 it->addPreview(it, *ploader);
1216 ploader->startLoading();
1220 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1221 FileName const & fn, int & file_format) const
1223 if(!lex.checkFor("\\lyxformat")) {
1224 Alert::error(_("Document format failure"),
1225 bformat(_("%1$s is not a readable LyX document."),
1226 from_utf8(fn.absFileName())));
1227 return ReadNoLyXFormat;
1233 // LyX formats 217 and earlier were written as 2.17. This corresponds
1234 // to files from LyX versions < 1.1.6.3. We just remove the dot in
1235 // these cases. See also: www.lyx.org/trac/changeset/1313.
1236 size_t dot = tmp_format.find_first_of(".,");
1237 if (dot != string::npos)
1238 tmp_format.erase(dot, 1);
1240 file_format = convert<int>(tmp_format);
1245 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1246 FileName & tmpfile, int from_format)
1248 TempFile tempfile("Buffer_convertLyXFormatXXXXXX.lyx");
1249 tempfile.setAutoRemove(false);
1250 tmpfile = tempfile.name();
1251 if(tmpfile.empty()) {
1252 Alert::error(_("Conversion failed"),
1253 bformat(_("%1$s is from a different"
1254 " version of LyX, but a temporary"
1255 " file for converting it could"
1256 " not be created."),
1257 from_utf8(fn.absFileName())));
1258 return LyX2LyXNoTempFile;
1261 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1262 if (lyx2lyx.empty()) {
1263 Alert::error(_("Conversion script not found"),
1264 bformat(_("%1$s is from a different"
1265 " version of LyX, but the"
1266 " conversion script lyx2lyx"
1267 " could not be found."),
1268 from_utf8(fn.absFileName())));
1269 return LyX2LyXNotFound;
1273 // $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1274 ostringstream command;
1275 command << os::python()
1276 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1277 << " -t " << convert<string>(LYX_FORMAT)
1278 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1279 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1280 string const command_str = command.str();
1282 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1284 cmd_ret const ret = runCommand(command_str);
1285 if (ret.first != 0) {
1286 if (from_format < LYX_FORMAT) {
1287 Alert::error(_("Conversion script failed"),
1288 bformat(_("%1$s is from an older version"
1289 " of LyX and the lyx2lyx script"
1290 " failed to convert it."),
1291 from_utf8(fn.absFileName())));
1292 return LyX2LyXOlderFormat;
1294 Alert::error(_("Conversion script failed"),
1295 bformat(_("%1$s is from a newer version"
1296 " of LyX and the lyx2lyx script"
1297 " failed to convert it."),
1298 from_utf8(fn.absFileName())));
1299 return LyX2LyXNewerFormat;
1306 // Should probably be moved to somewhere else: BufferView? GuiView?
1307 bool Buffer::save() const
1309 docstring const file = makeDisplayPath(absFileName(), 20);
1310 d->filename.refresh();
1312 // check the read-only status before moving the file as a backup
1313 if (d->filename.exists()) {
1314 bool const read_only = !d->filename.isWritable();
1316 Alert::warning(_("File is read-only"),
1317 bformat(_("The file %1$s cannot be written because it "
1318 "is marked as read-only."), file));
1323 // ask if the disk file has been externally modified (use checksum method)
1324 if (fileName().exists() && isExternallyModified(checksum_method)) {
1326 bformat(_("Document %1$s has been externally modified. "
1327 "Are you sure you want to overwrite this file?"), file);
1328 int const ret = Alert::prompt(_("Overwrite modified file?"),
1329 text, 1, 1, _("&Overwrite"), _("&Cancel"));
1334 // We don't need autosaves in the immediate future. (Asger)
1335 resetAutosaveTimers();
1337 // if the file does not yet exist, none of the backup activity
1338 // that follows is necessary
1339 if (!fileName().exists()) {
1340 if (!writeFile(fileName()))
1346 // we first write the file to a new name, then move it to its
1347 // proper location once that has been done successfully. that
1348 // way we preserve the original file if something goes wrong.
1349 string const justname = fileName().onlyFileNameWithoutExt();
1350 boost::scoped_ptr<TempFile>
1351 tempfile(new TempFile(fileName().onlyPath(),
1352 justname + "-XXXXXX.lyx"));
1353 bool const symlink = fileName().isSymLink();
1355 tempfile->setAutoRemove(false);
1357 FileName savefile(tempfile->name());
1358 LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1359 if (!writeFile(savefile))
1362 // we will set this to false if we fail
1363 bool made_backup = true;
1365 FileName backupName(absFileName() + '~');
1366 if (lyxrc.make_backup) {
1367 if (!lyxrc.backupdir_path.empty()) {
1368 string const mangledName =
1369 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1370 backupName = FileName(addName(lyxrc.backupdir_path,
1374 LYXERR(Debug::FILES, "Backing up original file to " <<
1375 backupName.absFileName());
1376 // Except file is symlink do not copy because of #6587.
1377 // Hard links have bad luck.
1378 made_backup = symlink ?
1379 fileName().copyTo(backupName):
1380 fileName().moveTo(backupName);
1383 Alert::error(_("Backup failure"),
1384 bformat(_("Cannot create backup file %1$s.\n"
1385 "Please check whether the directory exists and is writable."),
1386 from_utf8(backupName.absFileName())));
1387 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1391 // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1392 // Only do this if tempfile is not in autoremove mode
1395 // If we have no symlink, we can simply rename the temp file.
1396 // Otherwise, we need to copy it so the symlink stays intact.
1397 if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1398 savefile.moveTo(fileName()))
1400 // saveCheckSum() was already called by writeFile(), but the
1401 // time stamp is invalidated by copying/moving
1406 // else we saved the file, but failed to move it to the right location.
1408 if (lyxrc.make_backup && made_backup && !symlink) {
1409 // the original file was moved to filename.lyx~, so it will look
1410 // to the user as if it was deleted. (see bug #9234.) we could try
1411 // to restore it, but that would basically mean trying to do again
1412 // what we just failed to do. better to leave things as they are.
1413 Alert::error(_("Write failure"),
1414 bformat(_("The file has successfully been saved as:\n %1$s.\n"
1415 "But LyX could not move it to:\n %2$s.\n"
1416 "Your original file has been backed up to:\n %3$s"),
1417 from_utf8(savefile.absFileName()),
1418 from_utf8(fileName().absFileName()),
1419 from_utf8(backupName.absFileName())));
1421 // either we did not try to make a backup, or else we tried and failed,
1422 // or else the original file was a symlink, in which case it was copied,
1423 // not moved. so the original file is intact.
1424 Alert::error(_("Write failure"),
1425 bformat(_("Cannot move saved file to:\n %1$s.\n"
1426 "But the file has successfully been saved as:\n %2$s."),
1427 from_utf8(fileName().absFileName()),
1428 from_utf8(savefile.absFileName())));
1434 bool Buffer::writeFile(FileName const & fname) const
1436 if (d->read_only && fname == d->filename)
1439 bool retval = false;
1441 docstring const str = bformat(_("Saving document %1$s..."),
1442 makeDisplayPath(fname.absFileName()));
1445 string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1447 if (params().compressed) {
1448 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1449 retval = ofs && write(ofs);
1451 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1452 retval = ofs && write(ofs);
1456 message(str + _(" could not write file!"));
1461 // removeAutosaveFile();
1464 message(str + _(" done."));
1470 docstring Buffer::emergencyWrite()
1472 // No need to save if the buffer has not changed.
1476 string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1478 docstring user_message = bformat(
1479 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1481 // We try to save three places:
1482 // 1) Same place as document. Unless it is an unnamed doc.
1484 string s = absFileName();
1487 if (writeFile(FileName(s))) {
1489 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1490 return user_message;
1492 user_message += " " + _("Save failed! Trying again...\n");
1496 // 2) In HOME directory.
1497 string s = addName(Package::get_home_dir().absFileName(), absFileName());
1499 lyxerr << ' ' << s << endl;
1500 if (writeFile(FileName(s))) {
1502 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1503 return user_message;
1506 user_message += " " + _("Save failed! Trying yet again...\n");
1508 // 3) In "/tmp" directory.
1509 // MakeAbsPath to prepend the current
1510 // drive letter on OS/2
1511 s = addName(package().temp_dir().absFileName(), absFileName());
1513 lyxerr << ' ' << s << endl;
1514 if (writeFile(FileName(s))) {
1516 user_message += " " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1517 return user_message;
1520 user_message += " " + _("Save failed! Bummer. Document is lost.");
1523 return user_message;
1527 bool Buffer::write(ostream & ofs) const
1530 // Use the standard "C" locale for file output.
1531 ofs.imbue(locale::classic());
1534 // The top of the file should not be written by params().
1536 // write out a comment in the top of the file
1537 // Important: Keep the version formatting in sync with lyx2lyx and
1538 // tex2lyx (bug 7951)
1539 ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1540 << " created this file. For more info see http://www.lyx.org/\n"
1541 << "\\lyxformat " << LYX_FORMAT << "\n"
1542 << "\\begin_document\n";
1544 /// For each author, set 'used' to true if there is a change
1545 /// by this author in the document; otherwise set it to 'false'.
1546 AuthorList::Authors::const_iterator a_it = params().authors().begin();
1547 AuthorList::Authors::const_iterator a_end = params().authors().end();
1548 for (; a_it != a_end; ++a_it)
1549 a_it->setUsed(false);
1551 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1552 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1553 for ( ; it != end; ++it)
1554 it->checkAuthors(params().authors());
1556 // now write out the buffer parameters.
1557 ofs << "\\begin_header\n";
1558 params().writeFile(ofs, this);
1559 ofs << "\\end_header\n";
1562 ofs << "\n\\begin_body\n";
1564 ofs << "\n\\end_body\n";
1566 // Write marker that shows file is complete
1567 ofs << "\\end_document" << endl;
1569 // Shouldn't really be needed....
1572 // how to check if close went ok?
1573 // Following is an attempt... (BE 20001011)
1575 // good() returns false if any error occurred, including some
1576 // formatting error.
1577 // bad() returns true if something bad happened in the buffer,
1578 // which should include file system full errors.
1583 lyxerr << "File was not closed properly." << endl;
1590 bool Buffer::makeLaTeXFile(FileName const & fname,
1591 string const & original_path,
1592 OutputParams const & runparams_in,
1593 OutputWhat output) const
1595 OutputParams runparams = runparams_in;
1597 // This is necessary for LuaTeX/XeTeX with tex fonts.
1598 // See FIXME in BufferParams::encoding()
1599 if (runparams.isFullUnicode())
1600 runparams.encoding = encodings.fromLyXName("utf8-plain");
1602 string const encoding = runparams.encoding->iconvName();
1603 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1606 try { ofs.reset(encoding); }
1607 catch (iconv_codecvt_facet_exception const & e) {
1608 lyxerr << "Caught iconv exception: " << e.what() << endl;
1609 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1610 "verify that the support software for your encoding (%1$s) is "
1611 "properly installed"), from_ascii(encoding)));
1614 if (!openFileWrite(ofs, fname))
1617 ErrorList & errorList = d->errorLists["Export"];
1619 bool failed_export = false;
1620 otexstream os(ofs, d->texrow);
1622 // make sure we are ready to export
1623 // this needs to be done before we validate
1624 // FIXME Do we need to do this all the time? I.e., in children
1625 // of a master we are exporting?
1627 updateMacroInstances(OutputUpdate);
1630 os.texrow().reset();
1631 writeLaTeXSource(os, original_path, runparams, output);
1633 catch (EncodingException const & e) {
1634 docstring const failed(1, e.failed_char);
1636 oss << "0x" << hex << e.failed_char << dec;
1637 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1638 " (code point %2$s)"),
1639 failed, from_utf8(oss.str()));
1640 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1641 "representable in the chosen encoding.\n"
1642 "Changing the document encoding to utf8 could help."),
1643 e.par_id, e.pos, e.pos + 1));
1644 failed_export = true;
1646 catch (iconv_codecvt_facet_exception const & e) {
1647 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1648 _(e.what()), -1, 0, 0));
1649 failed_export = true;
1651 catch (exception const & e) {
1652 errorList.push_back(ErrorItem(_("conversion failed"),
1653 _(e.what()), -1, 0, 0));
1654 failed_export = true;
1657 lyxerr << "Caught some really weird exception..." << endl;
1663 failed_export = true;
1664 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1667 if (runparams_in.silent)
1671 return !failed_export;
1675 void Buffer::writeLaTeXSource(otexstream & os,
1676 string const & original_path,
1677 OutputParams const & runparams_in,
1678 OutputWhat output) const
1680 // The child documents, if any, shall be already loaded at this point.
1682 OutputParams runparams = runparams_in;
1684 // This is necessary for LuaTeX/XeTeX with tex fonts.
1685 // See FIXME in BufferParams::encoding()
1686 if (runparams.isFullUnicode())
1687 runparams.encoding = encodings.fromLyXName("utf8-plain");
1689 // If we are compiling a file standalone, even if this is the
1690 // child of some other buffer, let's cut the link here, so the
1691 // file is really independent and no concurring settings from
1692 // the master (e.g. branch state) interfere (see #8100).
1693 if (!runparams.is_child)
1694 d->ignore_parent = true;
1696 // Classify the unicode characters appearing in math insets
1697 BufferEncodings::initUnicodeMath(*this);
1699 // validate the buffer.
1700 LYXERR(Debug::LATEX, " Validating buffer...");
1701 LaTeXFeatures features(*this, params(), runparams);
1703 // This is only set once per document (in master)
1704 if (!runparams.is_child)
1705 runparams.use_polyglossia = features.usePolyglossia();
1706 LYXERR(Debug::LATEX, " Buffer validation done.");
1708 bool const output_preamble =
1709 output == FullSource || output == OnlyPreamble;
1710 bool const output_body =
1711 output == FullSource || output == OnlyBody;
1713 // The starting paragraph of the coming rows is the
1714 // first paragraph of the document. (Asger)
1715 if (output_preamble && runparams.nice) {
1716 os << "%% LyX " << lyx_version << " created this file. "
1717 "For more info, see http://www.lyx.org/.\n"
1718 "%% Do not edit unless you really know what "
1721 LYXERR(Debug::INFO, "lyx document header finished");
1723 // There are a few differences between nice LaTeX and usual files:
1724 // usual files have \batchmode and special input@path to allow
1725 // inclusion of figures specified by an explicitly relative path
1726 // (i.e., a path starting with './' or '../') with either \input or
1727 // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1728 // input@path is set when the actual parameter original_path is set.
1729 // This is done for usual tex-file, but not for nice-latex-file.
1730 // (Matthias 250696)
1731 // Note that input@path is only needed for something the user does
1732 // in the preamble, included .tex files or ERT, files included by
1733 // LyX work without it.
1734 if (output_preamble) {
1735 if (!runparams.nice) {
1736 // code for usual, NOT nice-latex-file
1737 os << "\\batchmode\n"; // changed from \nonstopmode
1739 if (!original_path.empty()) {
1741 // We don't know the encoding of inputpath
1742 docstring const inputpath = from_utf8(original_path);
1743 docstring uncodable_glyphs;
1744 Encoding const * const enc = runparams.encoding;
1746 for (size_t n = 0; n < inputpath.size(); ++n) {
1747 if (!enc->encodable(inputpath[n])) {
1748 docstring const glyph(1, inputpath[n]);
1749 LYXERR0("Uncodable character '"
1751 << "' in input path!");
1752 uncodable_glyphs += glyph;
1757 // warn user if we found uncodable glyphs.
1758 if (!uncodable_glyphs.empty()) {
1759 frontend::Alert::warning(
1760 _("Uncodable character in file path"),
1762 _("The path of your document\n"
1764 "contains glyphs that are unknown "
1765 "in the current document encoding "
1766 "(namely %2$s). This may result in "
1767 "incomplete output, unless "
1768 "TEXINPUTS contains the document "
1769 "directory and you don't use "
1770 "explicitly relative paths (i.e., "
1771 "paths starting with './' or "
1772 "'../') in the preamble or in ERT."
1773 "\n\nIn case of problems, choose "
1774 "an appropriate document encoding\n"
1775 "(such as utf8) or change the "
1777 inputpath, uncodable_glyphs));
1780 support::latex_path(original_path);
1781 if (contains(docdir, '#')) {
1782 docdir = subst(docdir, "#", "\\#");
1783 os << "\\catcode`\\#=11"
1784 "\\def\\#{#}\\catcode`\\#=6\n";
1786 if (contains(docdir, '%')) {
1787 docdir = subst(docdir, "%", "\\%");
1788 os << "\\catcode`\\%=11"
1789 "\\def\\%{%}\\catcode`\\%=14\n";
1791 os << "\\makeatletter\n"
1792 << "\\def\\input@path{{"
1793 << docdir << "/}}\n"
1794 << "\\makeatother\n";
1798 // get parent macros (if this buffer has a parent) which will be
1799 // written at the document begin further down.
1800 MacroSet parentMacros;
1801 listParentMacros(parentMacros, features);
1803 // Write the preamble
1804 runparams.use_babel = params().writeLaTeX(os, features,
1805 d->filename.onlyPath());
1807 // Japanese might be required only in some children of a document,
1808 // but once required, we must keep use_japanese true.
1809 runparams.use_japanese |= features.isRequired("japanese");
1812 // Restore the parenthood if needed
1813 if (!runparams.is_child)
1814 d->ignore_parent = false;
1819 os << "\\begin{document}\n";
1821 // output the parent macros
1822 MacroSet::iterator it = parentMacros.begin();
1823 MacroSet::iterator end = parentMacros.end();
1824 for (; it != end; ++it) {
1825 int num_lines = (*it)->write(os.os(), true);
1826 os.texrow().newlines(num_lines);
1829 } // output_preamble
1831 os.texrow().start(paragraphs().begin()->id(), 0);
1833 LYXERR(Debug::INFO, "preamble finished, now the body.");
1836 latexParagraphs(*this, text(), os, runparams);
1838 // Restore the parenthood if needed
1839 if (!runparams.is_child)
1840 d->ignore_parent = false;
1842 // add this just in case after all the paragraphs
1845 if (output_preamble) {
1846 os << "\\end{document}\n";
1847 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1849 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1851 runparams_in.encoding = runparams.encoding;
1853 // Just to be sure. (Asger)
1854 os.texrow().newline();
1856 //for (int i = 0; i<d->texrow.rows(); i++) {
1858 // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1859 // lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1862 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1863 LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1867 void Buffer::makeDocBookFile(FileName const & fname,
1868 OutputParams const & runparams,
1869 OutputWhat output) const
1871 LYXERR(Debug::LATEX, "makeDocBookFile...");
1874 if (!openFileWrite(ofs, fname))
1877 // make sure we are ready to export
1878 // this needs to be done before we validate
1880 updateMacroInstances(OutputUpdate);
1882 writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1886 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1890 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1891 OutputParams const & runparams,
1892 OutputWhat output) const
1894 LaTeXFeatures features(*this, params(), runparams);
1899 DocumentClass const & tclass = params().documentClass();
1900 string const & top_element = tclass.latexname();
1902 bool const output_preamble =
1903 output == FullSource || output == OnlyPreamble;
1904 bool const output_body =
1905 output == FullSource || output == OnlyBody;
1907 if (output_preamble) {
1908 if (runparams.flavor == OutputParams::XML)
1909 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1912 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1915 if (! tclass.class_header().empty())
1916 os << from_ascii(tclass.class_header());
1917 else if (runparams.flavor == OutputParams::XML)
1918 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1919 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1921 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1923 docstring preamble = from_utf8(params().preamble);
1924 if (runparams.flavor != OutputParams::XML ) {
1925 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1926 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1927 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1928 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1931 string const name = runparams.nice
1932 ? changeExtension(absFileName(), ".sgml") : fname;
1933 preamble += features.getIncludedFiles(name);
1934 preamble += features.getLyXSGMLEntities();
1936 if (!preamble.empty()) {
1937 os << "\n [ " << preamble << " ]";
1943 string top = top_element;
1945 if (runparams.flavor == OutputParams::XML)
1946 top += params().language->code();
1948 top += params().language->code().substr(0, 2);
1951 if (!params().options.empty()) {
1953 top += params().options;
1956 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1957 << " file was created by LyX " << lyx_version
1958 << "\n See http://www.lyx.org/ for more information -->\n";
1960 params().documentClass().counters().reset();
1962 sgml::openTag(os, top);
1964 docbookParagraphs(text(), *this, os, runparams);
1965 sgml::closeTag(os, top_element);
1970 void Buffer::makeLyXHTMLFile(FileName const & fname,
1971 OutputParams const & runparams) const
1973 LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1976 if (!openFileWrite(ofs, fname))
1979 // make sure we are ready to export
1980 // this has to be done before we validate
1981 updateBuffer(UpdateMaster, OutputUpdate);
1982 updateMacroInstances(OutputUpdate);
1984 writeLyXHTMLSource(ofs, runparams, FullSource);
1988 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1992 void Buffer::writeLyXHTMLSource(odocstream & os,
1993 OutputParams const & runparams,
1994 OutputWhat output) const
1996 LaTeXFeatures features(*this, params(), runparams);
1998 d->bibinfo_.makeCitationLabels(*this);
2000 bool const output_preamble =
2001 output == FullSource || output == OnlyPreamble;
2002 bool const output_body =
2003 output == FullSource || output == OnlyBody || output == IncludedFile;
2005 if (output_preamble) {
2006 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2007 << "<!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"
2008 // FIXME Language should be set properly.
2009 << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2011 << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2012 // FIXME Presumably need to set this right
2013 << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2015 docstring const & doctitle = features.htmlTitle();
2017 << (doctitle.empty() ?
2018 from_ascii("LyX Document") :
2019 html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2022 docstring styles = features.getTClassHTMLPreamble();
2023 if (!styles.empty())
2024 os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2026 styles = from_utf8(features.getPreambleSnippets());
2027 if (!styles.empty())
2028 os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2030 // we will collect CSS information in a stream, and then output it
2031 // either here, as part of the header, or else in a separate file.
2032 odocstringstream css;
2033 styles = from_utf8(features.getCSSSnippets());
2034 if (!styles.empty())
2035 css << "/* LyX Provided Styles */\n" << styles << '\n';
2037 styles = features.getTClassHTMLStyles();
2038 if (!styles.empty())
2039 css << "/* Layout-provided Styles */\n" << styles << '\n';
2041 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2042 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2043 if (needfg || needbg) {
2044 css << "\nbody {\n";
2047 << from_ascii(X11hexname(params().fontcolor))
2050 css << " background-color: "
2051 << from_ascii(X11hexname(params().backgroundcolor))
2056 docstring const dstyles = css.str();
2057 if (!dstyles.empty()) {
2058 bool written = false;
2059 if (params().html_css_as_file) {
2060 // open a file for CSS info
2062 string const fcssname = addName(temppath(), "docstyle.css");
2063 FileName const fcssfile = FileName(fcssname);
2064 if (openFileWrite(ocss, fcssfile)) {
2068 // write link to header
2069 os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2071 runparams.exportdata->addExternalFile("xhtml", fcssfile);
2074 // we are here if the CSS is supposed to be written to the header
2075 // or if we failed to write it to an external file.
2077 os << "<style type='text/css'>\n"
2086 bool const output_body_tag = (output != IncludedFile);
2087 if (output_body_tag)
2090 if (output != IncludedFile)
2091 // if we're an included file, the counters are in the master.
2092 params().documentClass().counters().reset();
2093 xhtmlParagraphs(text(), *this, xs, runparams);
2094 if (output_body_tag)
2098 if (output_preamble)
2103 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2104 // Other flags: -wall -v0 -x
2105 int Buffer::runChktex()
2109 // get LaTeX-Filename
2110 FileName const path(temppath());
2111 string const name = addName(path.absFileName(), latexName());
2112 string const org_path = filePath();
2114 PathChanger p(path); // path to LaTeX file
2115 message(_("Running chktex..."));
2117 // Generate the LaTeX file if neccessary
2118 OutputParams runparams(¶ms().encoding());
2119 runparams.flavor = OutputParams::LATEX;
2120 runparams.nice = false;
2121 runparams.linelen = lyxrc.plaintext_linelen;
2122 makeLaTeXFile(FileName(name), org_path, runparams);
2125 Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2126 int const res = chktex.run(terr); // run chktex
2129 Alert::error(_("chktex failure"),
2130 _("Could not run chktex successfully."));
2132 ErrorList & errlist = d->errorLists["ChkTeX"];
2134 bufferErrors(terr, errlist);
2139 if (runparams.silent)
2140 d->errorLists["ChkTeX"].clear();
2148 void Buffer::validate(LaTeXFeatures & features) const
2150 // Validate the buffer params, but not for included
2151 // files, since they also use the parent buffer's
2153 if (!features.runparams().is_child)
2154 params().validate(features);
2156 for_each(paragraphs().begin(), paragraphs().end(),
2157 bind(&Paragraph::validate, _1, ref(features)));
2159 if (lyxerr.debugging(Debug::LATEX)) {
2160 features.showStruct();
2165 void Buffer::getLabelList(vector<docstring> & list) const
2167 // If this is a child document, use the master's list instead.
2169 masterBuffer()->getLabelList(list);
2174 Toc & toc = d->toc_backend.toc("label");
2175 TocIterator toc_it = toc.begin();
2176 TocIterator end = toc.end();
2177 for (; toc_it != end; ++toc_it) {
2178 if (toc_it->depth() == 0)
2179 list.push_back(toc_it->str());
2184 void Buffer::updateBibfilesCache(UpdateScope scope) const
2186 // FIXME This is probably unnecssary, given where we call this.
2187 // If this is a child document, use the parent's cache instead.
2188 if (parent() && scope != UpdateChildOnly) {
2189 masterBuffer()->updateBibfilesCache();
2193 d->bibfiles_cache_.clear();
2194 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2195 if (it->lyxCode() == BIBTEX_CODE) {
2196 InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2197 support::FileNameList const bibfiles = inset.getBibFiles();
2198 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2201 } else if (it->lyxCode() == INCLUDE_CODE) {
2202 InsetInclude & inset = static_cast<InsetInclude &>(*it);
2203 Buffer const * const incbuf = inset.getChildBuffer();
2206 support::FileNameList const & bibfiles =
2207 incbuf->getBibfilesCache(UpdateChildOnly);
2208 if (!bibfiles.empty()) {
2209 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2215 d->bibfile_cache_valid_ = true;
2216 d->bibinfo_cache_valid_ = false;
2217 d->cite_labels_valid_ = false;
2221 void Buffer::invalidateBibinfoCache() const
2223 d->bibinfo_cache_valid_ = false;
2224 d->cite_labels_valid_ = false;
2225 // also invalidate the cache for the parent buffer
2226 Buffer const * const pbuf = d->parent();
2228 pbuf->invalidateBibinfoCache();
2232 void Buffer::invalidateBibfileCache() const
2234 d->bibfile_cache_valid_ = false;
2235 d->bibinfo_cache_valid_ = false;
2236 d->cite_labels_valid_ = false;
2237 // also invalidate the cache for the parent buffer
2238 Buffer const * const pbuf = d->parent();
2240 pbuf->invalidateBibfileCache();
2244 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2246 // FIXME This is probably unnecessary, given where we call this.
2247 // If this is a child document, use the master's cache instead.
2248 Buffer const * const pbuf = masterBuffer();
2249 if (pbuf != this && scope != UpdateChildOnly)
2250 return pbuf->getBibfilesCache();
2252 if (!d->bibfile_cache_valid_)
2253 this->updateBibfilesCache(scope);
2255 return d->bibfiles_cache_;
2259 BiblioInfo const & Buffer::masterBibInfo() const
2261 Buffer const * const tmp = masterBuffer();
2263 return tmp->masterBibInfo();
2268 void Buffer::checkIfBibInfoCacheIsValid() const
2270 // use the master's cache
2271 Buffer const * const tmp = masterBuffer();
2273 tmp->checkIfBibInfoCacheIsValid();
2277 // compare the cached timestamps with the actual ones.
2278 FileNameList const & bibfiles_cache = getBibfilesCache();
2279 FileNameList::const_iterator ei = bibfiles_cache.begin();
2280 FileNameList::const_iterator en = bibfiles_cache.end();
2281 for (; ei != en; ++ ei) {
2282 time_t lastw = ei->lastModified();
2283 time_t prevw = d->bibfile_status_[*ei];
2284 if (lastw != prevw) {
2285 d->bibinfo_cache_valid_ = false;
2286 d->cite_labels_valid_ = false;
2287 d->bibfile_status_[*ei] = lastw;
2293 void Buffer::reloadBibInfoCache() const
2295 // use the master's cache
2296 Buffer const * const tmp = masterBuffer();
2298 tmp->reloadBibInfoCache();
2302 checkIfBibInfoCacheIsValid();
2303 if (d->bibinfo_cache_valid_)
2306 d->bibinfo_.clear();
2308 d->bibinfo_cache_valid_ = true;
2312 void Buffer::collectBibKeys() const
2314 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2315 it->collectBibKeys(it);
2319 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2321 Buffer const * tmp = masterBuffer();
2322 BiblioInfo & masterbi = (tmp == this) ?
2323 d->bibinfo_ : tmp->d->bibinfo_;
2324 masterbi.mergeBiblioInfo(bi);
2328 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2330 Buffer const * tmp = masterBuffer();
2331 BiblioInfo & masterbi = (tmp == this) ?
2332 d->bibinfo_ : tmp->d->bibinfo_;
2337 void Buffer::makeCitationLabels() const
2339 Buffer const * const master = masterBuffer();
2340 return d->bibinfo_.makeCitationLabels(*master);
2344 bool Buffer::citeLabelsValid() const
2346 return masterBuffer()->d->cite_labels_valid_;
2350 void Buffer::removeBiblioTempFiles() const
2352 // We remove files that contain LaTeX commands specific to the
2353 // particular bibliographic style being used, in order to avoid
2354 // LaTeX errors when we switch style.
2355 FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2356 FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2357 LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2358 aux_file.removeFile();
2359 LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2360 bbl_file.removeFile();
2361 // Also for the parent buffer
2362 Buffer const * const pbuf = parent();
2364 pbuf->removeBiblioTempFiles();
2368 bool Buffer::isDepClean(string const & name) const
2370 DepClean::const_iterator const it = d->dep_clean.find(name);
2371 if (it == d->dep_clean.end())
2377 void Buffer::markDepClean(string const & name)
2379 d->dep_clean[name] = true;
2383 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2386 // FIXME? if there is an Buffer LFUN that can be dispatched even
2387 // if internal, put a switch '(cmd.action)' here.
2393 switch (cmd.action()) {
2395 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2396 flag.setOnOff(isReadonly());
2399 // FIXME: There is need for a command-line import.
2400 //case LFUN_BUFFER_IMPORT:
2402 case LFUN_BUFFER_AUTO_SAVE:
2405 case LFUN_BUFFER_EXPORT_CUSTOM:
2406 // FIXME: Nothing to check here?
2409 case LFUN_BUFFER_EXPORT: {
2410 docstring const arg = cmd.argument();
2411 if (arg == "custom") {
2415 string format = to_utf8(arg);
2416 size_t pos = format.find(' ');
2417 if (pos != string::npos)
2418 format = format.substr(0, pos);
2419 enable = params().isExportable(format);
2421 flag.message(bformat(
2422 _("Don't know how to export to format: %1$s"), arg));
2426 case LFUN_BUFFER_CHKTEX:
2427 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2430 case LFUN_BUILD_PROGRAM:
2431 enable = params().isExportable("program");
2434 case LFUN_BRANCH_ACTIVATE:
2435 case LFUN_BRANCH_DEACTIVATE:
2436 case LFUN_BRANCH_MASTER_ACTIVATE:
2437 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2438 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2439 || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2440 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2441 : params().branchlist();
2442 docstring const branchName = cmd.argument();
2443 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2447 case LFUN_BRANCH_ADD:
2448 case LFUN_BRANCHES_RENAME:
2449 // if no Buffer is present, then of course we won't be called!
2452 case LFUN_BUFFER_LANGUAGE:
2453 enable = !isReadonly();
2456 case LFUN_BUFFER_VIEW_CACHE:
2457 enable = (d->preview_file_).exists();
2463 flag.setEnabled(enable);
2468 void Buffer::dispatch(string const & command, DispatchResult & result)
2470 return dispatch(lyxaction.lookupFunc(command), result);
2474 // NOTE We can end up here even if we have no GUI, because we are called
2475 // by LyX::exec to handled command-line requests. So we may need to check
2476 // whether we have a GUI or not. The boolean use_gui holds this information.
2477 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2480 // FIXME? if there is an Buffer LFUN that can be dispatched even
2481 // if internal, put a switch '(cmd.action())' here.
2482 dr.dispatched(false);
2485 string const argument = to_utf8(func.argument());
2486 // We'll set this back to false if need be.
2487 bool dispatched = true;
2488 undo().beginUndoGroup();
2490 switch (func.action()) {
2491 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2492 if (lyxvc().inUse()) {
2493 string log = lyxvc().toggleReadOnly();
2498 setReadonly(!isReadonly());
2501 case LFUN_BUFFER_EXPORT: {
2502 ExportStatus const status = doExport(argument, false);
2503 dr.setError(status != ExportSuccess);
2504 if (status != ExportSuccess)
2505 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2510 case LFUN_BUILD_PROGRAM: {
2511 ExportStatus const status = doExport("program", true);
2512 dr.setError(status != ExportSuccess);
2513 if (status != ExportSuccess)
2514 dr.setMessage(_("Error generating literate programming code."));
2518 case LFUN_BUFFER_CHKTEX:
2522 case LFUN_BUFFER_EXPORT_CUSTOM: {
2524 string command = split(argument, format_name, ' ');
2525 Format const * format = formats.getFormat(format_name);
2527 lyxerr << "Format \"" << format_name
2528 << "\" not recognized!"
2533 // The name of the file created by the conversion process
2536 // Output to filename
2537 if (format->name() == "lyx") {
2538 string const latexname = latexName(false);
2539 filename = changeExtension(latexname,
2540 format->extension());
2541 filename = addName(temppath(), filename);
2543 if (!writeFile(FileName(filename)))
2547 doExport(format_name, true, filename);
2550 // Substitute $$FName for filename
2551 if (!contains(command, "$$FName"))
2552 command = "( " + command + " ) < $$FName";
2553 command = subst(command, "$$FName", filename);
2555 // Execute the command in the background
2557 call.startscript(Systemcall::DontWait, command,
2558 filePath(), layoutPos());
2562 // FIXME: There is need for a command-line import.
2564 case LFUN_BUFFER_IMPORT:
2569 case LFUN_BUFFER_AUTO_SAVE:
2571 resetAutosaveTimers();
2574 case LFUN_BRANCH_ACTIVATE:
2575 case LFUN_BRANCH_DEACTIVATE:
2576 case LFUN_BRANCH_MASTER_ACTIVATE:
2577 case LFUN_BRANCH_MASTER_DEACTIVATE: {
2578 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2579 || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2580 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2583 docstring const branch_name = func.argument();
2584 // the case without a branch name is handled elsewhere
2585 if (branch_name.empty()) {
2589 Branch * branch = buf->params().branchlist().find(branch_name);
2591 LYXERR0("Branch " << branch_name << " does not exist.");
2593 docstring const msg =
2594 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2598 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2599 || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2600 if (branch->isSelected() != activate) {
2601 buf->undo().recordUndoBufferParams(CursorData());
2602 branch->setSelected(activate);
2604 dr.screenUpdate(Update::Force);
2605 dr.forceBufferUpdate();
2610 case LFUN_BRANCH_ADD: {
2611 docstring branch_name = func.argument();
2612 if (branch_name.empty()) {
2616 BranchList & branch_list = params().branchlist();
2617 vector<docstring> const branches =
2618 getVectorFromString(branch_name, branch_list.separator());
2620 for (vector<docstring>::const_iterator it = branches.begin();
2621 it != branches.end(); ++it) {
2623 Branch * branch = branch_list.find(branch_name);
2625 LYXERR0("Branch " << branch_name << " already exists.");
2629 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2631 undo().recordUndoBufferParams(CursorData());
2632 branch_list.add(branch_name);
2633 branch = branch_list.find(branch_name);
2634 string const x11hexname = X11hexname(branch->color());
2635 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2636 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2638 dr.screenUpdate(Update::Force);
2646 case LFUN_BRANCHES_RENAME: {
2647 if (func.argument().empty())
2650 docstring const oldname = from_utf8(func.getArg(0));
2651 docstring const newname = from_utf8(func.getArg(1));
2652 InsetIterator it = inset_iterator_begin(inset());
2653 InsetIterator const end = inset_iterator_end(inset());
2654 bool success = false;
2655 for (; it != end; ++it) {
2656 if (it->lyxCode() == BRANCH_CODE) {
2657 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2658 if (ins.branch() == oldname) {
2659 undo().recordUndo(CursorData(it));
2660 ins.rename(newname);
2665 if (it->lyxCode() == INCLUDE_CODE) {
2666 // get buffer of external file
2667 InsetInclude const & ins =
2668 static_cast<InsetInclude const &>(*it);
2669 Buffer * child = ins.getChildBuffer();
2672 child->dispatch(func, dr);
2677 dr.screenUpdate(Update::Force);
2678 dr.forceBufferUpdate();
2683 case LFUN_BUFFER_VIEW_CACHE:
2684 if (!formats.view(*this, d->preview_file_,
2685 d->preview_format_))
2686 dr.setMessage(_("Error viewing the output file."));
2693 dr.dispatched(dispatched);
2694 undo().endUndoGroup();
2698 void Buffer::changeLanguage(Language const * from, Language const * to)
2700 LASSERT(from, return);
2701 LASSERT(to, return);
2703 for_each(par_iterator_begin(),
2705 bind(&Paragraph::changeLanguage, _1, params(), from, to));
2709 bool Buffer::isMultiLingual() const
2711 ParConstIterator end = par_iterator_end();
2712 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2713 if (it->isMultiLingual(params()))
2720 std::set<Language const *> Buffer::getLanguages() const
2722 std::set<Language const *> languages;
2723 getLanguages(languages);
2728 void Buffer::getLanguages(std::set<Language const *> & languages) const
2730 ParConstIterator end = par_iterator_end();
2731 // add the buffer language, even if it's not actively used
2732 languages.insert(language());
2733 // iterate over the paragraphs
2734 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2735 it->getLanguages(languages);
2737 ListOfBuffers clist = getDescendents();
2738 ListOfBuffers::const_iterator cit = clist.begin();
2739 ListOfBuffers::const_iterator const cen = clist.end();
2740 for (; cit != cen; ++cit)
2741 (*cit)->getLanguages(languages);
2745 DocIterator Buffer::getParFromID(int const id) const
2747 Buffer * buf = const_cast<Buffer *>(this);
2749 // John says this is called with id == -1 from undo
2750 lyxerr << "getParFromID(), id: " << id << endl;
2751 return doc_iterator_end(buf);
2754 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2755 if (it.paragraph().id() == id)
2758 return doc_iterator_end(buf);
2762 bool Buffer::hasParWithID(int const id) const
2764 return !getParFromID(id).atEnd();
2768 ParIterator Buffer::par_iterator_begin()
2770 return ParIterator(doc_iterator_begin(this));
2774 ParIterator Buffer::par_iterator_end()
2776 return ParIterator(doc_iterator_end(this));
2780 ParConstIterator Buffer::par_iterator_begin() const
2782 return ParConstIterator(doc_iterator_begin(this));
2786 ParConstIterator Buffer::par_iterator_end() const
2788 return ParConstIterator(doc_iterator_end(this));
2792 Language const * Buffer::language() const
2794 return params().language;
2798 docstring const Buffer::B_(string const & l10n) const
2800 return params().B_(l10n);
2804 bool Buffer::isClean() const
2806 return d->lyx_clean;
2810 bool Buffer::isExternallyModified(CheckMethod method) const
2812 LASSERT(d->filename.exists(), return false);
2813 // if method == timestamp, check timestamp before checksum
2814 return (method == checksum_method
2815 || d->timestamp_ != d->filename.lastModified())
2816 && d->checksum_ != d->filename.checksum();
2820 void Buffer::saveCheckSum() const
2822 FileName const & file = d->filename;
2825 if (file.exists()) {
2826 d->timestamp_ = file.lastModified();
2827 d->checksum_ = file.checksum();
2829 // in the case of save to a new file.
2836 void Buffer::markClean() const
2838 if (!d->lyx_clean) {
2839 d->lyx_clean = true;
2842 // if the .lyx file has been saved, we don't need an
2844 d->bak_clean = true;
2845 d->undo_.markDirty();
2849 void Buffer::setUnnamed(bool flag)
2855 bool Buffer::isUnnamed() const
2862 /// Don't check unnamed, here: isInternal() is used in
2863 /// newBuffer(), where the unnamed flag has not been set by anyone
2864 /// yet. Also, for an internal buffer, there should be no need for
2865 /// retrieving fileName() nor for checking if it is unnamed or not.
2866 bool Buffer::isInternal() const
2868 return d->internal_buffer;
2872 void Buffer::setInternal(bool flag)
2874 d->internal_buffer = flag;
2878 void Buffer::markDirty()
2881 d->lyx_clean = false;
2884 d->bak_clean = false;
2886 DepClean::iterator it = d->dep_clean.begin();
2887 DepClean::const_iterator const end = d->dep_clean.end();
2889 for (; it != end; ++it)
2894 FileName Buffer::fileName() const
2900 string Buffer::absFileName() const
2902 return d->filename.absFileName();
2906 string Buffer::filePath() const
2908 string const abs = d->filename.onlyPath().absFileName();
2911 int last = abs.length() - 1;
2913 return abs[last] == '/' ? abs : abs + '/';
2917 string Buffer::originFilePath() const
2919 if (FileName::isAbsolute(params().origin))
2920 return params().origin;
2926 string Buffer::layoutPos() const
2928 return d->layout_position;
2932 void Buffer::setLayoutPos(string const & path)
2935 d->layout_position.clear();
2939 LATTEST(FileName::isAbsolute(path));
2941 d->layout_position =
2942 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
2944 if (d->layout_position.empty())
2945 d->layout_position = ".";
2949 bool Buffer::isReadonly() const
2951 return d->read_only;
2955 void Buffer::setParent(Buffer const * buffer)
2957 // Avoids recursive include.
2958 d->setParent(buffer == this ? 0 : buffer);
2963 Buffer const * Buffer::parent() const
2969 ListOfBuffers Buffer::allRelatives() const
2971 ListOfBuffers lb = masterBuffer()->getDescendents();
2972 lb.push_front(const_cast<Buffer *>(masterBuffer()));
2977 Buffer const * Buffer::masterBuffer() const
2979 // FIXME Should be make sure we are not in some kind
2980 // of recursive include? A -> B -> A will crash this.
2981 Buffer const * const pbuf = d->parent();
2985 return pbuf->masterBuffer();
2989 bool Buffer::isChild(Buffer * child) const
2991 return d->children_positions.find(child) != d->children_positions.end();
2995 DocIterator Buffer::firstChildPosition(Buffer const * child)
2997 Impl::BufferPositionMap::iterator it;
2998 it = d->children_positions.find(child);
2999 if (it == d->children_positions.end())
3000 return DocIterator(this);
3005 bool Buffer::hasChildren() const
3007 return !d->children_positions.empty();
3011 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3013 // loop over children
3014 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3015 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3016 for (; it != end; ++it) {
3017 Buffer * child = const_cast<Buffer *>(it->first);
3019 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3020 if (bit != clist.end())
3022 clist.push_back(child);
3024 // there might be grandchildren
3025 child->collectChildren(clist, true);
3030 ListOfBuffers Buffer::getChildren() const
3033 collectChildren(v, false);
3034 // Make sure we have not included ourselves.
3035 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3036 if (bit != v.end()) {
3037 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3044 ListOfBuffers Buffer::getDescendents() const
3047 collectChildren(v, true);
3048 // Make sure we have not included ourselves.
3049 ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3050 if (bit != v.end()) {
3051 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3058 template<typename M>
3059 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3064 typename M::const_iterator it = m.lower_bound(x);
3065 if (it == m.begin())
3073 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3074 DocIterator const & pos) const
3076 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3078 // if paragraphs have no macro context set, pos will be empty
3082 // we haven't found anything yet
3083 DocIterator bestPos = owner_->par_iterator_begin();
3084 MacroData const * bestData = 0;
3086 // find macro definitions for name
3087 NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3088 if (nameIt != macros.end()) {
3089 // find last definition in front of pos or at pos itself
3090 PositionScopeMacroMap::const_iterator it
3091 = greatest_below(nameIt->second, pos);
3092 if (it != nameIt->second.end()) {
3094 // scope ends behind pos?
3095 if (pos < it->second.scope) {
3096 // Looks good, remember this. If there
3097 // is no external macro behind this,
3098 // we found the right one already.
3099 bestPos = it->first;
3100 bestData = &it->second.macro;
3104 // try previous macro if there is one
3105 if (it == nameIt->second.begin())
3112 // find macros in included files
3113 PositionScopeBufferMap::const_iterator it
3114 = greatest_below(position_to_children, pos);
3115 if (it == position_to_children.end())
3116 // no children before
3120 // do we know something better (i.e. later) already?
3121 if (it->first < bestPos )
3124 // scope ends behind pos?
3125 if (pos < it->second.scope
3126 && (cloned_buffer_ ||
3127 theBufferList().isLoaded(it->second.buffer))) {
3128 // look for macro in external file
3130 MacroData const * data
3131 = it->second.buffer->getMacro(name, false);
3134 bestPos = it->first;
3140 // try previous file if there is one
3141 if (it == position_to_children.begin())
3146 // return the best macro we have found
3151 MacroData const * Buffer::getMacro(docstring const & name,
3152 DocIterator const & pos, bool global) const
3157 // query buffer macros
3158 MacroData const * data = d->getBufferMacro(name, pos);
3162 // If there is a master buffer, query that
3163 Buffer const * const pbuf = d->parent();
3165 d->macro_lock = true;
3166 MacroData const * macro = pbuf->getMacro(
3167 name, *this, false);
3168 d->macro_lock = false;
3174 data = MacroTable::globalMacros().get(name);
3183 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3185 // set scope end behind the last paragraph
3186 DocIterator scope = par_iterator_begin();
3187 scope.pit() = scope.lastpit() + 1;
3189 return getMacro(name, scope, global);
3193 MacroData const * Buffer::getMacro(docstring const & name,
3194 Buffer const & child, bool global) const
3196 // look where the child buffer is included first
3197 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3198 if (it == d->children_positions.end())
3201 // check for macros at the inclusion position
3202 return getMacro(name, it->second, global);
3206 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3208 pit_type const lastpit = it.lastpit();
3210 // look for macros in each paragraph
3211 while (it.pit() <= lastpit) {
3212 Paragraph & par = it.paragraph();
3214 // iterate over the insets of the current paragraph
3215 InsetList const & insets = par.insetList();
3216 InsetList::const_iterator iit = insets.begin();
3217 InsetList::const_iterator end = insets.end();
3218 for (; iit != end; ++iit) {
3219 it.pos() = iit->pos;
3221 // is it a nested text inset?
3222 if (iit->inset->asInsetText()) {
3223 // Inset needs its own scope?
3224 InsetText const * itext = iit->inset->asInsetText();
3225 bool newScope = itext->isMacroScope();
3227 // scope which ends just behind the inset
3228 DocIterator insetScope = it;
3231 // collect macros in inset
3232 it.push_back(CursorSlice(*iit->inset));
3233 updateMacros(it, newScope ? insetScope : scope);
3238 if (iit->inset->asInsetTabular()) {
3239 CursorSlice slice(*iit->inset);
3240 size_t const numcells = slice.nargs();
3241 for (; slice.idx() < numcells; slice.forwardIdx()) {
3242 it.push_back(slice);
3243 updateMacros(it, scope);
3249 // is it an external file?
3250 if (iit->inset->lyxCode() == INCLUDE_CODE) {
3251 // get buffer of external file
3252 InsetInclude const & inset =
3253 static_cast<InsetInclude const &>(*iit->inset);
3255 Buffer * child = inset.getChildBuffer();
3260 // register its position, but only when it is
3261 // included first in the buffer
3262 if (children_positions.find(child) ==
3263 children_positions.end())
3264 children_positions[child] = it;
3266 // register child with its scope
3267 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3271 InsetMath * im = iit->inset->asInsetMath();
3272 if (doing_export && im) {
3273 InsetMathHull * hull = im->asHullInset();
3275 hull->recordLocation(it);
3278 if (iit->inset->lyxCode() != MATHMACRO_CODE)
3282 MathMacroTemplate & macroTemplate =
3283 *iit->inset->asInsetMath()->asMacroTemplate();
3284 MacroContext mc(owner_, it);
3285 macroTemplate.updateToContext(mc);
3288 bool valid = macroTemplate.validMacro();
3289 // FIXME: Should be fixNameAndCheckIfValid() in fact,
3290 // then the BufferView's cursor will be invalid in
3291 // some cases which leads to crashes.
3296 // FIXME (Abdel), I don't understand why we pass 'it' here
3297 // instead of 'macroTemplate' defined above... is this correct?
3298 macros[macroTemplate.name()][it] =
3299 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3309 void Buffer::updateMacros() const
3314 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3316 // start with empty table
3318 d->children_positions.clear();
3319 d->position_to_children.clear();
3321 // Iterate over buffer, starting with first paragraph
3322 // The scope must be bigger than any lookup DocIterator
3323 // later. For the global lookup, lastpit+1 is used, hence
3324 // we use lastpit+2 here.
3325 DocIterator it = par_iterator_begin();
3326 DocIterator outerScope = it;
3327 outerScope.pit() = outerScope.lastpit() + 2;
3328 d->updateMacros(it, outerScope);
3332 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3334 InsetIterator it = inset_iterator_begin(inset());
3335 InsetIterator const end = inset_iterator_end(inset());
3336 for (; it != end; ++it) {
3337 if (it->lyxCode() == BRANCH_CODE) {
3338 InsetBranch & br = static_cast<InsetBranch &>(*it);
3339 docstring const name = br.branch();
3340 if (!from_master && !params().branchlist().find(name))
3341 result.push_back(name);
3342 else if (from_master && !masterBuffer()->params().branchlist().find(name))
3343 result.push_back(name);
3346 if (it->lyxCode() == INCLUDE_CODE) {
3347 // get buffer of external file
3348 InsetInclude const & ins =
3349 static_cast<InsetInclude const &>(*it);
3350 Buffer * child = ins.getChildBuffer();
3353 child->getUsedBranches(result, true);
3356 // remove duplicates
3361 void Buffer::updateMacroInstances(UpdateType utype) const
3363 LYXERR(Debug::MACROS, "updateMacroInstances for "
3364 << d->filename.onlyFileName());
3365 DocIterator it = doc_iterator_begin(this);
3367 DocIterator const end = doc_iterator_end(this);
3368 for (; it != end; it.forwardInset()) {
3369 // look for MathData cells in InsetMathNest insets
3370 InsetMath * minset = it.nextInset()->asInsetMath();
3374 // update macro in all cells of the InsetMathNest
3375 DocIterator::idx_type n = minset->nargs();
3376 MacroContext mc = MacroContext(this, it);
3377 for (DocIterator::idx_type i = 0; i < n; ++i) {
3378 MathData & data = minset->cell(i);
3379 data.updateMacros(0, mc, utype);
3385 void Buffer::listMacroNames(MacroNameSet & macros) const
3390 d->macro_lock = true;
3392 // loop over macro names
3393 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3394 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3395 for (; nameIt != nameEnd; ++nameIt)
3396 macros.insert(nameIt->first);
3398 // loop over children
3399 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3400 Impl::BufferPositionMap::iterator end = d->children_positions.end();
3401 for (; it != end; ++it)
3402 it->first->listMacroNames(macros);
3405 Buffer const * const pbuf = d->parent();
3407 pbuf->listMacroNames(macros);
3409 d->macro_lock = false;
3413 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3415 Buffer const * const pbuf = d->parent();
3420 pbuf->listMacroNames(names);
3423 MacroNameSet::iterator it = names.begin();
3424 MacroNameSet::iterator end = names.end();
3425 for (; it != end; ++it) {
3427 MacroData const * data =
3428 pbuf->getMacro(*it, *this, false);
3430 macros.insert(data);
3432 // we cannot access the original MathMacroTemplate anymore
3433 // here to calls validate method. So we do its work here manually.
3434 // FIXME: somehow make the template accessible here.
3435 if (data->optionals() > 0)
3436 features.require("xargs");
3442 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3445 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3447 RefCache::iterator it = d->ref_cache_.find(label);
3448 if (it != d->ref_cache_.end())
3449 return it->second.second;
3451 static InsetLabel const * dummy_il = 0;
3452 static References const dummy_refs;
3453 it = d->ref_cache_.insert(
3454 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3455 return it->second.second;
3459 Buffer::References const & Buffer::references(docstring const & label) const
3461 return const_cast<Buffer *>(this)->getReferenceCache(label);
3465 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3467 References & refs = getReferenceCache(label);
3468 refs.push_back(make_pair(inset, it));
3472 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3474 masterBuffer()->d->ref_cache_[label].first = il;
3478 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3480 return masterBuffer()->d->ref_cache_[label].first;
3484 void Buffer::clearReferenceCache() const
3487 d->ref_cache_.clear();
3491 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3493 //FIXME: This does not work for child documents yet.
3494 reloadBibInfoCache();
3496 // Check if the label 'from' appears more than once
3497 BiblioInfo const & keys = masterBibInfo();
3498 BiblioInfo::const_iterator bit = keys.begin();
3499 BiblioInfo::const_iterator bend = keys.end();
3500 vector<docstring> labels;
3502 for (; bit != bend; ++bit)
3504 labels.push_back(bit->first);
3506 if (count(labels.begin(), labels.end(), from) > 1)
3509 string const paramName = "key";
3510 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3511 if (it->lyxCode() != CITE_CODE)
3513 InsetCommand * inset = it->asInsetCommand();
3514 docstring const oldValue = inset->getParam(paramName);
3515 if (oldValue == from)
3516 inset->setParam(paramName, to);
3521 void Buffer::getSourceCode(odocstream & os, string const & format,
3522 pit_type par_begin, pit_type par_end,
3523 OutputWhat output, bool master) const
3525 OutputParams runparams(¶ms().encoding());
3526 runparams.nice = true;
3527 runparams.flavor = params().getOutputFlavor(format);
3528 runparams.linelen = lyxrc.plaintext_linelen;
3529 // No side effect of file copying and image conversion
3530 runparams.dryrun = true;
3532 if (output == CurrentParagraph) {
3533 runparams.par_begin = par_begin;
3534 runparams.par_end = par_end;
3535 if (par_begin + 1 == par_end) {
3537 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3541 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3542 convert<docstring>(par_begin),
3543 convert<docstring>(par_end - 1))
3546 // output paragraphs
3547 if (runparams.flavor == OutputParams::LYX) {
3548 Paragraph const & par = text().paragraphs()[par_begin];
3550 depth_type dt = par.getDepth();
3551 par.write(ods, params(), dt);
3552 os << from_utf8(ods.str());
3553 } else if (runparams.flavor == OutputParams::HTML) {
3555 setMathFlavor(runparams);
3556 xhtmlParagraphs(text(), *this, xs, runparams);
3557 } else if (runparams.flavor == OutputParams::TEXT) {
3559 // FIXME Handles only one paragraph, unlike the others.
3560 // Probably should have some routine with a signature like them.
3561 writePlaintextParagraph(*this,
3562 text().paragraphs()[par_begin], os, runparams, dummy);
3563 } else if (params().isDocBook()) {
3564 docbookParagraphs(text(), *this, os, runparams);
3566 // If we are previewing a paragraph, even if this is the
3567 // child of some other buffer, let's cut the link here,
3568 // so that no concurring settings from the master
3569 // (e.g. branch state) interfere (see #8101).
3571 d->ignore_parent = true;
3572 // We need to validate the Buffer params' features here
3573 // in order to know if we should output polyglossia
3574 // macros (instead of babel macros)
3575 LaTeXFeatures features(*this, params(), runparams);
3576 params().validate(features);
3577 runparams.use_polyglossia = features.usePolyglossia();
3582 // latex or literate
3583 otexstream ots(os, texrow);
3586 latexParagraphs(*this, text(), ots, runparams);
3588 // Restore the parenthood
3590 d->ignore_parent = false;
3594 if (output == FullSource)
3595 os << _("Preview source code");
3596 else if (output == OnlyPreamble)
3597 os << _("Preview preamble");
3598 else if (output == OnlyBody)
3599 os << _("Preview body");
3601 if (runparams.flavor == OutputParams::LYX) {
3603 if (output == FullSource)
3605 else if (output == OnlyPreamble)
3606 params().writeFile(ods, this);
3607 else if (output == OnlyBody)
3609 os << from_utf8(ods.str());
3610 } else if (runparams.flavor == OutputParams::HTML) {
3611 writeLyXHTMLSource(os, runparams, output);
3612 } else if (runparams.flavor == OutputParams::TEXT) {
3613 if (output == OnlyPreamble) {
3614 os << "% "<< _("Plain text does not have a preamble.");
3616 writePlaintextFile(*this, os, runparams);
3617 } else if (params().isDocBook()) {
3618 writeDocBookSource(os, absFileName(), runparams, output);
3620 // latex or literate
3622 d->texrow.newline();
3623 d->texrow.newline();
3624 otexstream ots(os, d->texrow);
3626 runparams.is_child = true;
3627 writeLaTeXSource(ots, string(), runparams, output);
3633 ErrorList & Buffer::errorList(string const & type) const
3635 return d->errorLists[type];
3639 void Buffer::updateTocItem(std::string const & type,
3640 DocIterator const & dit) const
3643 d->gui_->updateTocItem(type, dit);
3647 void Buffer::structureChanged() const
3650 d->gui_->structureChanged();
3654 void Buffer::errors(string const & err, bool from_master) const
3657 d->gui_->errors(err, from_master);
3661 void Buffer::message(docstring const & msg) const
3664 d->gui_->message(msg);
3668 void Buffer::setBusy(bool on) const
3671 d->gui_->setBusy(on);
3675 void Buffer::updateTitles() const
3678 d->wa_->updateTitles();
3682 void Buffer::resetAutosaveTimers() const
3685 d->gui_->resetAutosaveTimers();
3689 bool Buffer::hasGuiDelegate() const
3695 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3704 class AutoSaveBuffer : public ForkedProcess {
3707 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3708 : buffer_(buffer), fname_(fname) {}
3710 virtual shared_ptr<ForkedProcess> clone() const
3712 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3717 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3718 from_utf8(fname_.absFileName())));
3719 return run(DontWait);
3723 virtual int generateChild();
3725 Buffer const & buffer_;
3730 int AutoSaveBuffer::generateChild()
3732 #if defined(__APPLE__)
3733 /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3734 * We should use something else like threads.
3736 * Since I do not know how to determine at run time what is the OS X
3737 * version, I just disable forking altogether for now (JMarc)
3739 pid_t const pid = -1;
3741 // tmp_ret will be located (usually) in /tmp
3742 // will that be a problem?
3743 // Note that this calls ForkedCalls::fork(), so it's
3744 // ok cross-platform.
3745 pid_t const pid = fork();
3746 // If you want to debug the autosave
3747 // you should set pid to -1, and comment out the fork.
3748 if (pid != 0 && pid != -1)
3752 // pid = -1 signifies that lyx was unable
3753 // to fork. But we will do the save
3755 bool failed = false;
3756 TempFile tempfile("lyxautoXXXXXX.lyx");
3757 tempfile.setAutoRemove(false);
3758 FileName const tmp_ret = tempfile.name();
3759 if (!tmp_ret.empty()) {
3760 if (!buffer_.writeFile(tmp_ret))
3762 else if (!tmp_ret.moveTo(fname_))
3768 // failed to write/rename tmp_ret so try writing direct
3769 if (!buffer_.writeFile(fname_)) {
3770 // It is dangerous to do this in the child,
3771 // but safe in the parent, so...
3772 if (pid == -1) // emit message signal.
3773 buffer_.message(_("Autosave failed!"));
3777 if (pid == 0) // we are the child so...
3786 FileName Buffer::getEmergencyFileName() const
3788 return FileName(d->filename.absFileName() + ".emergency");
3792 FileName Buffer::getAutosaveFileName() const
3794 // if the document is unnamed try to save in the backup dir, else
3795 // in the default document path, and as a last try in the filePath,
3796 // which will most often be the temporary directory
3799 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3800 : lyxrc.backupdir_path;
3801 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3804 string const fname = "#" + d->filename.onlyFileName() + "#";
3806 return makeAbsPath(fname, fpath);
3810 void Buffer::removeAutosaveFile() const
3812 FileName const f = getAutosaveFileName();
3818 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3820 FileName const newauto = getAutosaveFileName();
3822 if (newauto != oldauto && oldauto.exists())
3823 if (!oldauto.moveTo(newauto))
3824 LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3828 bool Buffer::autoSave() const
3830 Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3831 if (buf->d->bak_clean || isReadonly())
3834 message(_("Autosaving current document..."));
3835 buf->d->bak_clean = true;
3837 FileName const fname = getAutosaveFileName();
3838 LASSERT(d->cloned_buffer_, return false);
3840 // If this buffer is cloned, we assume that
3841 // we are running in a separate thread already.
3842 TempFile tempfile("lyxautoXXXXXX.lyx");
3843 tempfile.setAutoRemove(false);
3844 FileName const tmp_ret = tempfile.name();
3845 if (!tmp_ret.empty()) {
3847 // assume successful write of tmp_ret
3848 if (tmp_ret.moveTo(fname))
3851 // failed to write/rename tmp_ret so try writing direct
3852 return writeFile(fname);
3856 void Buffer::setExportStatus(bool e) const
3858 d->doing_export = e;
3859 ListOfBuffers clist = getDescendents();
3860 ListOfBuffers::const_iterator cit = clist.begin();
3861 ListOfBuffers::const_iterator const cen = clist.end();
3862 for (; cit != cen; ++cit)
3863 (*cit)->d->doing_export = e;
3867 bool Buffer::isExporting() const
3869 return d->doing_export;
3873 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3877 return doExport(target, put_in_tempdir, result_file);
3880 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3881 string & result_file) const
3883 bool const update_unincluded =
3884 params().maintain_unincluded_children
3885 && !params().getIncludedChildren().empty();
3887 // (1) export with all included children (omit \includeonly)
3888 if (update_unincluded) {
3889 ExportStatus const status =
3890 doExport(target, put_in_tempdir, true, result_file);
3891 if (status != ExportSuccess)
3894 // (2) export with included children only
3895 return doExport(target, put_in_tempdir, false, result_file);
3899 void Buffer::setMathFlavor(OutputParams & op) const
3901 switch (params().html_math_output) {
3902 case BufferParams::MathML:
3903 op.math_flavor = OutputParams::MathAsMathML;
3905 case BufferParams::HTML:
3906 op.math_flavor = OutputParams::MathAsHTML;
3908 case BufferParams::Images:
3909 op.math_flavor = OutputParams::MathAsImages;
3911 case BufferParams::LaTeX:
3912 op.math_flavor = OutputParams::MathAsLaTeX;
3918 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3919 bool includeall, string & result_file) const
3921 LYXERR(Debug::FILES, "target=" << target);
3922 OutputParams runparams(¶ms().encoding());
3923 string format = target;
3924 string dest_filename;
3925 size_t pos = target.find(' ');
3926 if (pos != string::npos) {
3927 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3928 format = target.substr(0, pos);
3929 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3930 FileName(dest_filename).onlyPath().createPath();
3931 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3933 MarkAsExporting exporting(this);
3934 string backend_format;
3935 runparams.flavor = OutputParams::LATEX;
3936 runparams.linelen = lyxrc.plaintext_linelen;
3937 runparams.includeall = includeall;
3938 vector<string> backs = params().backends();
3939 Converters converters = theConverters();
3940 bool need_nice_file = false;
3941 if (find(backs.begin(), backs.end(), format) == backs.end()) {
3942 // Get shortest path to format
3943 converters.buildGraph();
3944 Graph::EdgePath path;
3945 for (vector<string>::const_iterator it = backs.begin();
3946 it != backs.end(); ++it) {
3947 Graph::EdgePath p = converters.getPath(*it, format);
3948 if (!p.empty() && (path.empty() || p.size() < path.size())) {
3949 backend_format = *it;
3954 if (!put_in_tempdir) {
3955 // Only show this alert if this is an export to a non-temporary
3956 // file (not for previewing).
3957 Alert::error(_("Couldn't export file"), bformat(
3958 _("No information for exporting the format %1$s."),
3959 formats.prettyName(format)));
3961 return ExportNoPathToFormat;
3963 runparams.flavor = converters.getFlavor(path, this);
3964 Graph::EdgePath::const_iterator it = path.begin();
3965 Graph::EdgePath::const_iterator en = path.end();
3966 for (; it != en; ++it)
3967 if (theConverters().get(*it).nice()) {
3968 need_nice_file = true;
3973 backend_format = format;
3974 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3975 // FIXME: Don't hardcode format names here, but use a flag
3976 if (backend_format == "pdflatex")
3977 runparams.flavor = OutputParams::PDFLATEX;
3978 else if (backend_format == "luatex")
3979 runparams.flavor = OutputParams::LUATEX;
3980 else if (backend_format == "dviluatex")
3981 runparams.flavor = OutputParams::DVILUATEX;
3982 else if (backend_format == "xetex")
3983 runparams.flavor = OutputParams::XETEX;
3986 string filename = latexName(false);
3987 filename = addName(temppath(), filename);
3988 filename = changeExtension(filename,
3989 formats.extension(backend_format));
3990 LYXERR(Debug::FILES, "filename=" << filename);
3992 // Plain text backend
3993 if (backend_format == "text") {
3994 runparams.flavor = OutputParams::TEXT;
3995 writePlaintextFile(*this, FileName(filename), runparams);
3998 else if (backend_format == "xhtml") {
3999 runparams.flavor = OutputParams::HTML;
4000 setMathFlavor(runparams);
4001 makeLyXHTMLFile(FileName(filename), runparams);
4002 } else if (backend_format == "lyx")
4003 writeFile(FileName(filename));
4005 else if (params().isDocBook()) {
4006 runparams.nice = !put_in_tempdir;
4007 makeDocBookFile(FileName(filename), runparams);
4010 else if (backend_format == format || need_nice_file) {
4011 runparams.nice = true;
4012 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4013 if (d->cloned_buffer_)
4014 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4017 } else if (!lyxrc.tex_allows_spaces
4018 && contains(filePath(), ' ')) {
4019 Alert::error(_("File name error"),
4020 _("The directory path to the document cannot contain spaces."));
4021 return ExportTexPathHasSpaces;
4023 runparams.nice = false;
4024 bool const success = makeLaTeXFile(
4025 FileName(filename), filePath(), runparams);
4026 if (d->cloned_buffer_)
4027 d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4032 string const error_type = (format == "program")
4033 ? "Build" : params().bufferFormat();
4034 ErrorList & error_list = d->errorLists[error_type];
4035 string const ext = formats.extension(format);
4036 FileName const tmp_result_file(changeExtension(filename, ext));
4037 bool const success = converters.convert(this, FileName(filename),
4038 tmp_result_file, FileName(absFileName()), backend_format, format,
4041 // Emit the signal to show the error list or copy it back to the
4042 // cloned Buffer so that it can be emitted afterwards.
4043 if (format != backend_format) {
4044 if (runparams.silent)
4046 else if (d->cloned_buffer_)
4047 d->cloned_buffer_->d->errorLists[error_type] =
4048 d->errorLists[error_type];
4051 // also to the children, in case of master-buffer-view
4052 ListOfBuffers clist = getDescendents();
4053 ListOfBuffers::const_iterator cit = clist.begin();
4054 ListOfBuffers::const_iterator const cen = clist.end();
4055 for (; cit != cen; ++cit) {
4056 if (runparams.silent)
4057 (*cit)->d->errorLists[error_type].clear();
4058 else if (d->cloned_buffer_) {
4059 // Enable reverse search by copying back the
4060 // texrow object to the cloned buffer.
4061 // FIXME: this is not thread safe.
4062 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4063 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4064 (*cit)->d->errorLists[error_type];
4066 (*cit)->errors(error_type, true);
4070 if (d->cloned_buffer_) {
4071 // Enable reverse dvi or pdf to work by copying back the texrow
4072 // object to the cloned buffer.
4073 // FIXME: There is a possibility of concurrent access to texrow
4074 // here from the main GUI thread that should be securized.
4075 d->cloned_buffer_->d->texrow = d->texrow;
4076 string const error_type = params().bufferFormat();
4077 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4081 if (put_in_tempdir) {
4082 result_file = tmp_result_file.absFileName();
4083 return success ? ExportSuccess : ExportConverterError;
4086 if (dest_filename.empty())
4087 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4089 result_file = dest_filename;
4090 // We need to copy referenced files (e. g. included graphics
4091 // if format == "dvi") to the result dir.
4092 vector<ExportedFile> const files =
4093 runparams.exportdata->externalFiles(format);
4094 string const dest = runparams.export_folder.empty() ?
4095 onlyPath(result_file) : runparams.export_folder;
4096 bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4097 : force_overwrite == ALL_FILES;
4098 CopyStatus status = use_force ? FORCE : SUCCESS;
4100 vector<ExportedFile>::const_iterator it = files.begin();
4101 vector<ExportedFile>::const_iterator const en = files.end();
4102 for (; it != en && status != CANCEL; ++it) {
4103 string const fmt = formats.getFormatFromFile(it->sourceName);
4104 string fixedName = it->exportName;
4105 if (!runparams.export_folder.empty()) {
4106 // Relative pathnames starting with ../ will be sanitized
4107 // if exporting to a different folder
4108 while (fixedName.substr(0, 3) == "../")
4109 fixedName = fixedName.substr(3, fixedName.length() - 3);
4111 FileName fixedFileName = makeAbsPath(fixedName, dest);
4112 fixedFileName.onlyPath().createPath();
4113 status = copyFile(fmt, it->sourceName,
4115 it->exportName, status == FORCE,
4116 runparams.export_folder.empty());
4119 if (status == CANCEL) {
4120 message(_("Document export cancelled."));
4121 return ExportCancel;
4124 if (tmp_result_file.exists()) {
4125 // Finally copy the main file
4126 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4127 : force_overwrite != NO_FILES;
4128 if (status == SUCCESS && use_force)
4130 status = copyFile(format, tmp_result_file,
4131 FileName(result_file), result_file,
4133 if (status == CANCEL) {
4134 message(_("Document export cancelled."));
4135 return ExportCancel;
4137 message(bformat(_("Document exported as %1$s "
4139 formats.prettyName(format),
4140 makeDisplayPath(result_file)));
4143 // This must be a dummy converter like fax (bug 1888)
4144 message(bformat(_("Document exported as %1$s"),
4145 formats.prettyName(format)));
4148 return success ? ExportSuccess : ExportConverterError;
4152 Buffer::ExportStatus Buffer::preview(string const & format) const
4154 bool const update_unincluded =
4155 params().maintain_unincluded_children
4156 && !params().getIncludedChildren().empty();
4157 return preview(format, update_unincluded);
4161 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4163 MarkAsExporting exporting(this);
4165 // (1) export with all included children (omit \includeonly)
4167 ExportStatus const status = doExport(format, true, true, result_file);
4168 if (status != ExportSuccess)
4171 // (2) export with included children only
4172 ExportStatus const status = doExport(format, true, false, result_file);
4173 FileName const previewFile(result_file);
4175 LATTEST (isClone());
4176 d->cloned_buffer_->d->preview_file_ = previewFile;
4177 d->cloned_buffer_->d->preview_format_ = format;
4178 d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4180 if (status != ExportSuccess)
4182 if (previewFile.exists()) {
4183 if (!formats.view(*this, previewFile, format))
4184 return PreviewError;
4186 return PreviewSuccess;
4189 // Successful export but no output file?
4190 // Probably a bug in error detection.
4191 LATTEST (status != ExportSuccess);
4198 Buffer::ReadStatus Buffer::extractFromVC()
4200 bool const found = LyXVC::file_not_found_hook(d->filename);
4202 return ReadFileNotFound;
4203 if (!d->filename.isReadableFile())
4209 Buffer::ReadStatus Buffer::loadEmergency()
4211 FileName const emergencyFile = getEmergencyFileName();
4212 if (!emergencyFile.exists()
4213 || emergencyFile.lastModified() <= d->filename.lastModified())
4214 return ReadFileNotFound;
4216 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4217 docstring const text = bformat(_("An emergency save of the document "
4218 "%1$s exists.\n\nRecover emergency save?"), file);
4220 int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4221 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4227 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4228 bool const success = (ret_llf == ReadSuccess);
4231 Alert::warning(_("File is read-only"),
4232 bformat(_("An emergency file is successfully loaded, "
4233 "but the original file %1$s is marked read-only. "
4234 "Please make sure to save the document as a different "
4235 "file."), from_utf8(d->filename.absFileName())));
4238 lyxvc().file_found_hook(d->filename);
4239 str = _("Document was successfully recovered.");
4241 str = _("Document was NOT successfully recovered.");
4242 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4243 makeDisplayPath(emergencyFile.absFileName()));
4245 int const del_emerg =
4246 Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4247 _("&Remove"), _("&Keep"));
4248 if (del_emerg == 0) {
4249 emergencyFile.removeFile();
4251 Alert::warning(_("Emergency file deleted"),
4252 _("Do not forget to save your file now!"), true);
4254 return success ? ReadSuccess : ReadEmergencyFailure;
4257 int const del_emerg =
4258 Alert::prompt(_("Delete emergency file?"),
4259 _("Remove emergency file now?"), 1, 1,
4260 _("&Remove"), _("&Keep"));
4262 emergencyFile.removeFile();
4263 return ReadOriginal;
4273 Buffer::ReadStatus Buffer::loadAutosave()
4275 // Now check if autosave file is newer.
4276 FileName const autosaveFile = getAutosaveFileName();
4277 if (!autosaveFile.exists()
4278 || autosaveFile.lastModified() <= d->filename.lastModified())
4279 return ReadFileNotFound;
4281 docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4282 docstring const text = bformat(_("The backup of the document %1$s "
4283 "is newer.\n\nLoad the backup instead?"), file);
4284 int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4285 _("&Load backup"), _("Load &original"), _("&Cancel"));
4290 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4291 // the file is not saved if we load the autosave file.
4292 if (ret_llf == ReadSuccess) {
4294 Alert::warning(_("File is read-only"),
4295 bformat(_("A backup file is successfully loaded, "
4296 "but the original file %1$s is marked read-only. "
4297 "Please make sure to save the document as a "
4299 from_utf8(d->filename.absFileName())));
4302 lyxvc().file_found_hook(d->filename);
4305 return ReadAutosaveFailure;
4308 // Here we delete the autosave
4309 autosaveFile.removeFile();
4310 return ReadOriginal;
4318 Buffer::ReadStatus Buffer::loadLyXFile()
4320 if (!d->filename.isReadableFile()) {
4321 ReadStatus const ret_rvc = extractFromVC();
4322 if (ret_rvc != ReadSuccess)
4326 ReadStatus const ret_re = loadEmergency();
4327 if (ret_re == ReadSuccess || ret_re == ReadCancel)
4330 ReadStatus const ret_ra = loadAutosave();
4331 if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4334 return loadThisLyXFile(d->filename);
4338 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4340 return readFile(fn);
4344 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4346 TeXErrors::Errors::const_iterator it = terr.begin();
4347 TeXErrors::Errors::const_iterator end = terr.end();
4348 ListOfBuffers clist = getDescendents();
4349 ListOfBuffers::const_iterator cen = clist.end();
4351 for (; it != end; ++it) {
4354 int errorRow = it->error_in_line;
4355 Buffer const * buf = 0;
4357 if (it->child_name.empty())
4358 p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4360 // The error occurred in a child
4361 ListOfBuffers::const_iterator cit = clist.begin();
4362 for (; cit != cen; ++cit) {
4363 string const child_name =
4364 DocFileName(changeExtension(
4365 (*cit)->absFileName(), "tex")).
4367 if (it->child_name != child_name)
4369 (*cit)->d->texrow.getIdFromRow(errorRow,
4370 id_start, pos_start);
4371 if (id_start != -1) {
4372 buf = d->cloned_buffer_
4373 ? (*cit)->d->cloned_buffer_->d->owner_
4374 : (*cit)->d->owner_;
4385 found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4386 } while (found && id_start == id_end && pos_start == pos_end);
4388 if (id_start != id_end) {
4389 // Next registered position is outside the inset where
4390 // the error occurred, so signal end-of-paragraph
4394 errorList.push_back(ErrorItem(it->error_desc,
4395 it->error_text, id_start, pos_start, pos_end, buf));
4400 void Buffer::setBuffersForInsets() const
4402 inset().setBuffer(const_cast<Buffer &>(*this));
4406 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4408 LBUFERR(!text().paragraphs().empty());
4410 // Use the master text class also for child documents
4411 Buffer const * const master = masterBuffer();
4412 DocumentClass const & textclass = master->params().documentClass();
4414 // do this only if we are the top-level Buffer
4415 if (master == this) {
4416 textclass.counters().reset(from_ascii("bibitem"));
4417 reloadBibInfoCache();
4420 // keep the buffers to be children in this set. If the call from the
4421 // master comes back we can see which of them were actually seen (i.e.
4422 // via an InsetInclude). The remaining ones in the set need still be updated.
4423 static std::set<Buffer const *> bufToUpdate;
4424 if (scope == UpdateMaster) {
4425 // If this is a child document start with the master
4426 if (master != this) {
4427 bufToUpdate.insert(this);
4428 master->updateBuffer(UpdateMaster, utype);
4429 // If the master buffer has no gui associated with it, then the TocModel is
4430 // not updated during the updateBuffer call and TocModel::toc_ is invalid
4431 // (bug 5699). The same happens if the master buffer is open in a different
4432 // window. This test catches both possibilities.
4433 // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4434 // There remains a problem here: If there is another child open in yet a third
4435 // window, that TOC is not updated. So some more general solution is needed at
4437 if (master->d->gui_ != d->gui_)
4440 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4441 if (bufToUpdate.find(this) == bufToUpdate.end())
4445 // start over the counters in the master
4446 textclass.counters().reset();
4449 // update will be done below for this buffer
4450 bufToUpdate.erase(this);
4452 // update all caches
4453 clearReferenceCache();
4456 Buffer & cbuf = const_cast<Buffer &>(*this);
4459 ParIterator parit = cbuf.par_iterator_begin();
4460 updateBuffer(parit, utype);
4463 // TocBackend update will be done later.
4466 d->bibinfo_cache_valid_ = true;
4467 d->cite_labels_valid_ = true;
4468 cbuf.tocBackend().update(utype == OutputUpdate);
4469 if (scope == UpdateMaster)
4470 cbuf.structureChanged();
4474 static depth_type getDepth(DocIterator const & it)
4476 depth_type depth = 0;
4477 for (size_t i = 0 ; i < it.depth() ; ++i)
4478 if (!it[i].inset().inMathed())
4479 depth += it[i].paragraph().getDepth() + 1;
4480 // remove 1 since the outer inset does not count
4484 static depth_type getItemDepth(ParIterator const & it)
4486 Paragraph const & par = *it;
4487 LabelType const labeltype = par.layout().labeltype;
4489 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4492 // this will hold the lowest depth encountered up to now.
4493 depth_type min_depth = getDepth(it);
4494 ParIterator prev_it = it;
4497 --prev_it.top().pit();
4499 // start of nested inset: go to outer par
4501 if (prev_it.empty()) {
4502 // start of document: nothing to do
4507 // We search for the first paragraph with same label
4508 // that is not more deeply nested.
4509 Paragraph & prev_par = *prev_it;
4510 depth_type const prev_depth = getDepth(prev_it);
4511 if (labeltype == prev_par.layout().labeltype) {
4512 if (prev_depth < min_depth)
4513 return prev_par.itemdepth + 1;
4514 if (prev_depth == min_depth)
4515 return prev_par.itemdepth;
4517 min_depth = min(min_depth, prev_depth);
4518 // small optimization: if we are at depth 0, we won't
4519 // find anything else
4520 if (prev_depth == 0)
4526 static bool needEnumCounterReset(ParIterator const & it)
4528 Paragraph const & par = *it;
4529 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4530 depth_type const cur_depth = par.getDepth();
4531 ParIterator prev_it = it;
4532 while (prev_it.pit()) {
4533 --prev_it.top().pit();
4534 Paragraph const & prev_par = *prev_it;
4535 if (prev_par.getDepth() <= cur_depth)
4536 return prev_par.layout().labeltype != LABEL_ENUMERATE;
4538 // start of nested inset: reset
4543 // set the label of a paragraph. This includes the counters.
4544 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4546 BufferParams const & bp = owner_->masterBuffer()->params();
4547 DocumentClass const & textclass = bp.documentClass();
4548 Paragraph & par = it.paragraph();
4549 Layout const & layout = par.layout();
4550 Counters & counters = textclass.counters();
4552 if (par.params().startOfAppendix()) {
4553 // We want to reset the counter corresponding to toplevel sectioning
4554 Layout const & lay = textclass.getTOCLayout();
4555 docstring const cnt = lay.counter;
4557 counters.reset(cnt);
4558 counters.appendix(true);
4560 par.params().appendix(counters.appendix());
4562 // Compute the item depth of the paragraph
4563 par.itemdepth = getItemDepth(it);
4565 if (layout.margintype == MARGIN_MANUAL) {
4566 if (par.params().labelWidthString().empty())
4567 par.params().labelWidthString(par.expandLabel(layout, bp));
4568 } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4569 // we do not need to do anything here, since the empty case is
4570 // handled during export.
4572 par.params().labelWidthString(docstring());
4575 switch(layout.labeltype) {
4576 case LABEL_ITEMIZE: {
4577 // At some point of time we should do something more
4578 // clever here, like:
4579 // par.params().labelString(
4580 // bp.user_defined_bullet(par.itemdepth).getText());
4581 // for now, use a simple hardcoded label
4582 docstring itemlabel;
4583 switch (par.itemdepth) {
4585 itemlabel = char_type(0x2022);
4588 itemlabel = char_type(0x2013);
4591 itemlabel = char_type(0x2217);
4594 itemlabel = char_type(0x2219); // or 0x00b7
4597 par.params().labelString(itemlabel);
4601 case LABEL_ENUMERATE: {
4602 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4604 switch (par.itemdepth) {
4613 enumcounter += "iv";
4616 // not a valid enumdepth...
4620 // Maybe we have to reset the enumeration counter.
4621 if (needEnumCounterReset(it))
4622 counters.reset(enumcounter);
4623 counters.step(enumcounter, utype);
4625 string const & lang = par.getParLanguage(bp)->code();
4626 par.params().labelString(counters.theCounter(enumcounter, lang));
4631 case LABEL_SENSITIVE: {
4632 string const & type = counters.current_float();
4633 docstring full_label;
4635 full_label = owner_->B_("Senseless!!! ");
4637 docstring name = owner_->B_(textclass.floats().getType(type).name());
4638 if (counters.hasCounter(from_utf8(type))) {
4639 string const & lang = par.getParLanguage(bp)->code();
4640 counters.step(from_utf8(type), utype);
4641 full_label = bformat(from_ascii("%1$s %2$s:"),
4643 counters.theCounter(from_utf8(type), lang));
4645 full_label = bformat(from_ascii("%1$s #:"), name);
4647 par.params().labelString(full_label);
4651 case LABEL_NO_LABEL:
4652 par.params().labelString(docstring());
4656 case LABEL_CENTERED:
4657 case LABEL_STATIC: {
4658 docstring const & lcounter = layout.counter;
4659 if (!lcounter.empty()) {
4660 if (layout.toclevel <= bp.secnumdepth
4661 && (layout.latextype != LATEX_ENVIRONMENT
4662 || it.text()->isFirstInSequence(it.pit()))) {
4663 if (counters.hasCounter(lcounter))
4664 counters.step(lcounter, utype);
4665 par.params().labelString(par.expandLabel(layout, bp));
4667 par.params().labelString(docstring());
4669 par.params().labelString(par.expandLabel(layout, bp));
4675 par.params().labelString(par.expandLabel(layout, bp));
4680 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4682 // LASSERT: Is it safe to continue here, or should we just return?
4683 LASSERT(parit.pit() == 0, /**/);
4685 // Set the position of the text in the buffer to be able
4686 // to resolve macros in it.
4687 parit.text()->setMacrocontextPosition(parit);
4689 depth_type maxdepth = 0;
4690 pit_type const lastpit = parit.lastpit();
4691 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4692 // reduce depth if necessary
4693 if (parit->params().depth() > maxdepth) {
4694 /** FIXME: this function is const, but
4695 * nevertheless it modifies the buffer. To be
4696 * cleaner, one should modify the buffer in
4697 * another function, which is actually
4698 * non-const. This would however be costly in
4699 * terms of code duplication.
4701 const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4702 parit->params().depth(maxdepth);
4704 maxdepth = parit->getMaxDepthAfter();
4706 if (utype == OutputUpdate) {
4707 // track the active counters
4708 // we have to do this for the master buffer, since the local
4709 // buffer isn't tracking anything.
4710 masterBuffer()->params().documentClass().counters().
4711 setActiveLayout(parit->layout());
4714 // set the counter for this paragraph
4715 d->setLabel(parit, utype);
4718 InsetList::const_iterator iit = parit->insetList().begin();
4719 InsetList::const_iterator end = parit->insetList().end();
4720 for (; iit != end; ++iit) {
4721 parit.pos() = iit->pos;
4722 iit->inset->updateBuffer(parit, utype);
4728 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4729 WordLangTuple & word_lang, docstring_list & suggestions) const
4733 suggestions.clear();
4734 word_lang = WordLangTuple();
4735 bool const to_end = to.empty();
4736 DocIterator const end = to_end ? doc_iterator_end(this) : to;
4737 // OK, we start from here.
4738 for (; from != end; from.forwardPos()) {
4739 // This skips all insets with spell check disabled.
4740 while (!from.allowSpellCheck()) {
4744 // If from is at the end of the document (which is possible
4745 // when "from" was changed above) LyX will crash later otherwise.
4746 if (from.atEnd() || (!to_end && from >= end))
4749 from.paragraph().spellCheck();
4750 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4751 if (SpellChecker::misspelled(res)) {
4755 // Do not increase progress when from == to, otherwise the word
4756 // count will be wrong.
4766 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4768 bool inword = false;
4773 for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4774 if (!dit.inTexted()) {
4779 Paragraph const & par = dit.paragraph();
4780 pos_type const pos = dit.pos();
4782 // Copied and adapted from isWordSeparator() in Paragraph
4783 if (pos == dit.lastpos()) {
4786 Inset const * ins = par.getInset(pos);
4787 if (ins && skipNoOutput && !ins->producesOutput()) {
4790 // stop if end of range was skipped
4791 if (!to.atEnd() && dit >= to)
4794 } else if (!par.isDeleted(pos)) {
4795 if (par.isWordSeparator(pos))
4801 if (ins && ins->isLetter())
4803 else if (ins && ins->isSpace())
4806 char_type const c = par.getChar(pos);
4807 if (isPrintableNonspace(c))
4809 else if (isSpace(c))
4819 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4821 d->updateStatistics(from, to, skipNoOutput);
4825 int Buffer::wordCount() const
4827 return d->wordCount();
4831 int Buffer::charCount(bool with_blanks) const
4833 return d->charCount(with_blanks);
4837 Buffer::ReadStatus Buffer::reload()
4840 // c.f. bug http://www.lyx.org/trac/ticket/6587
4841 removeAutosaveFile();
4842 // e.g., read-only status could have changed due to version control
4843 d->filename.refresh();
4844 docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4846 // clear parent. this will get reset if need be.
4848 ReadStatus const status = loadLyXFile();
4849 if (status == ReadSuccess) {
4854 message(bformat(_("Document %1$s reloaded."), disp_fn));
4857 message(bformat(_("Could not reload document %1$s."), disp_fn));
4867 bool Buffer::saveAs(FileName const & fn)
4869 FileName const old_name = fileName();
4870 FileName const old_auto = getAutosaveFileName();
4871 bool const old_unnamed = isUnnamed();
4872 bool success = true;
4873 d->old_position = filePath();
4880 // bring the autosave file with us, just in case.
4881 moveAutosaveFile(old_auto);
4882 // validate version control data and
4883 // correct buffer title
4884 lyxvc().file_found_hook(fileName());
4886 // the file has now been saved to the new location.
4887 // we need to check that the locations of child buffers
4889 checkChildBuffers();
4890 checkMasterBuffer();
4893 // reset the old filename and unnamed state
4894 setFileName(old_name);
4895 setUnnamed(old_unnamed);
4899 d->old_position.clear();
4904 void Buffer::checkChildBuffers()
4906 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4907 Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4908 for (; it != en; ++it) {
4909 DocIterator dit = it->second;
4910 Buffer * cbuf = const_cast<Buffer *>(it->first);
4911 if (!cbuf || !theBufferList().isLoaded(cbuf))
4913 Inset * inset = dit.nextInset();
4914 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4915 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4916 docstring const & incfile = inset_inc->getParam("filename");
4917 string oldloc = cbuf->absFileName();
4918 string newloc = makeAbsPath(to_utf8(incfile),
4919 onlyPath(absFileName())).absFileName();
4920 if (oldloc == newloc)
4922 // the location of the child file is incorrect.
4924 inset_inc->setChildBuffer(0);
4926 // invalidate cache of children
4927 d->children_positions.clear();
4928 d->position_to_children.clear();
4932 // If a child has been saved under a different name/path, it might have been
4933 // orphaned. Therefore the master needs to be reset (bug 8161).
4934 void Buffer::checkMasterBuffer()
4936 Buffer const * const master = masterBuffer();
4940 // necessary to re-register the child (bug 5873)
4941 // FIXME: clean up updateMacros (here, only
4942 // child registering is needed).
4943 master->updateMacros();
4944 // (re)set master as master buffer, but only
4945 // if we are a real child
4946 if (master->isChild(this))
4953 string Buffer::includedFilePath(string const & name, string const & ext) const
4955 bool isabsolute = FileName::isAbsolute(name);
4956 // old_position already contains a trailing path separator
4957 string const absname = isabsolute ? name : d->old_position + name;
4959 if (d->old_position.empty() || d->old_position == filePath()
4960 || !FileName(addExtension(absname, ext)).exists())
4964 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
4966 return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
4967 from_utf8(filePath())));