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"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
30 #include "ErrorList.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
39 #include "LaTeXFeatures.h"
43 #include "LyXAction.h"
47 #include "output_docbook.h"
49 #include "output_latex.h"
50 #include "output_xhtml.h"
51 #include "output_plaintext.h"
52 #include "paragraph_funcs.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
60 #include "TexStream.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
65 #include "VCBackend.h"
67 #include "WordLangTuple.h"
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetText.h"
75 #include "mathed/MacroTable.h"
76 #include "mathed/MathMacroTemplate.h"
77 #include "mathed/MathSupport.h"
79 #include "frontends/alert.h"
80 #include "frontends/Delegates.h"
81 #include "frontends/WorkAreaManager.h"
83 #include "graphics/Previews.h"
85 #include "support/lassert.h"
86 #include "support/convert.h"
87 #include "support/debug.h"
88 #include "support/docstring_list.h"
89 #include "support/ExceptionMessage.h"
90 #include "support/FileName.h"
91 #include "support/FileNameList.h"
92 #include "support/filetools.h"
93 #include "support/ForkedCalls.h"
94 #include "support/gettext.h"
95 #include "support/gzstream.h"
96 #include "support/lstrings.h"
97 #include "support/lyxalgo.h"
98 #include "support/os.h"
99 #include "support/Package.h"
100 #include "support/Path.h"
101 #include "support/Systemcall.h"
102 #include "support/textutils.h"
103 #include "support/types.h"
105 #include <boost/bind.hpp>
106 #include <boost/shared_ptr.hpp>
118 using namespace lyx::support;
122 namespace Alert = frontend::Alert;
123 namespace os = support::os;
127 // Do not remove the comment below, so we get merge conflict in
128 // independent branches. Instead add your own.
129 int const LYX_FORMAT = 362; // jspitzm: support applemac encoding
131 typedef map<string, bool> DepClean;
132 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134 void showPrintError(string const & name)
136 docstring str = bformat(_("Could not print the document %1$s.\n"
137 "Check that your printer is set up correctly."),
138 makeDisplayPath(name, 50));
139 Alert::error(_("Print document failed"), str);
144 class BufferSet : public std::set<Buffer const *> {};
149 Impl(Buffer & parent, FileName const & file, bool readonly);
163 mutable TexRow texrow;
165 /// need to regenerate .tex?
169 mutable bool lyx_clean;
171 /// is autosave needed?
172 mutable bool bak_clean;
174 /// is this a unnamed file (New...)?
180 /// name of the file the buffer is associated with.
183 /** Set to true only when the file is fully loaded.
184 * Used to prevent the premature generation of previews
185 * and by the citation inset.
187 bool file_fully_loaded;
190 mutable TocBackend toc_backend;
193 typedef pair<DocIterator, MacroData> ScopeMacro;
194 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
195 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
196 /// map from the macro name to the position map,
197 /// which maps the macro definition position to the scope and the MacroData.
198 NamePositionScopeMacroMap macros;
201 /// positions of child buffers in the buffer
202 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
203 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
204 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
205 /// position of children buffers in this buffer
206 BufferPositionMap children_positions;
207 /// map from children inclusion positions to their scope and their buffer
208 PositionScopeBufferMap position_to_children;
210 /// Container for all sort of Buffer dependant errors.
211 map<string, ErrorList> errorLists;
213 /// timestamp and checksum used to test if the file has been externally
214 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
216 unsigned long checksum_;
219 frontend::WorkAreaManager * wa_;
224 /// A cache for the bibfiles (including bibfiles of loaded child
225 /// documents), needed for appropriate update of natbib labels.
226 mutable support::FileNameList bibfilesCache_;
228 // FIXME The caching mechanism could be improved. At present, we have a
229 // cache for each Buffer, that caches all the bibliography info for that
230 // Buffer. A more efficient solution would be to have a global cache per
231 // file, and then to construct the Buffer's bibinfo from that.
232 /// A cache for bibliography info
233 mutable BiblioInfo bibinfo_;
234 /// whether the bibinfo cache is valid
235 bool bibinfoCacheValid_;
236 /// Cache of timestamps of .bib files
237 map<FileName, time_t> bibfileStatus_;
239 mutable RefCache ref_cache_;
241 /// our Text that should be wrapped in an InsetText
244 /// This is here to force the test to be done whenever parent_buffer
246 Buffer const * parent() const {
247 // if parent_buffer is not loaded, then it has been unloaded,
248 // which means that parent_buffer is an invalid pointer. So we
249 // set it to null in that case.
250 if (!theBufferList().isLoaded(parent_buffer))
252 return parent_buffer;
255 void setParent(Buffer const * pb) { parent_buffer = pb; }
257 /// So we can force access via the accessors.
258 mutable Buffer const * parent_buffer;
262 /// Creates the per buffer temporary directory
263 static FileName createBufferTmpDir()
266 // We are in our own directory. Why bother to mangle name?
267 // In fact I wrote this code to circumvent a problematic behaviour
268 // (bug?) of EMX mkstemp().
269 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
270 convert<string>(count++));
272 if (!tmpfl.createDirectory(0777)) {
273 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
274 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
275 from_utf8(tmpfl.absFilename())));
281 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
282 : lyx_clean(true), bak_clean(true), unnamed(false),
283 read_only(readonly_), filename(file), file_fully_loaded(false),
284 toc_backend(&parent), macro_lock(false), timestamp_(0),
285 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
288 temppath = createBufferTmpDir();
289 lyxvc.setBuffer(&parent);
291 wa_ = new frontend::WorkAreaManager;
295 Buffer::Buffer(string const & file, bool readonly)
296 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
298 LYXERR(Debug::INFO, "Buffer::Buffer()");
300 d->inset = new InsetText(*this);
301 d->inset->setAutoBreakRows(true);
302 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
308 LYXERR(Debug::INFO, "Buffer::~Buffer()");
309 // here the buffer should take care that it is
310 // saved properly, before it goes into the void.
312 // GuiView already destroyed
315 if (d->unnamed && d->filename.extension() == "internal") {
316 // No need to do additional cleanups for internal buffer.
321 // loop over children
322 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
323 Impl::BufferPositionMap::iterator end = d->children_positions.end();
324 for (; it != end; ++it) {
325 Buffer * child = const_cast<Buffer *>(it->first);
326 // The child buffer might have been closed already.
327 if (theBufferList().isLoaded(child))
328 theBufferList().releaseChild(this, child);
331 // clear references to children in macro tables
332 d->children_positions.clear();
333 d->position_to_children.clear();
335 if (!d->temppath.destroyDirectory()) {
336 Alert::warning(_("Could not remove temporary directory"),
337 bformat(_("Could not remove the temporary directory %1$s"),
338 from_utf8(d->temppath.absFilename())));
341 // Remove any previewed LaTeX snippets associated with this buffer.
342 thePreviews().removeLoader(*this);
348 void Buffer::changed() const
355 frontend::WorkAreaManager & Buffer::workAreaManager() const
357 LASSERT(d->wa_, /**/);
362 Text & Buffer::text() const
364 return d->inset->text();
368 Inset & Buffer::inset() const
374 BufferParams & Buffer::params()
380 BufferParams const & Buffer::params() const
386 ParagraphList & Buffer::paragraphs()
388 return text().paragraphs();
392 ParagraphList const & Buffer::paragraphs() const
394 return text().paragraphs();
398 LyXVC & Buffer::lyxvc()
404 LyXVC const & Buffer::lyxvc() const
410 string const Buffer::temppath() const
412 return d->temppath.absFilename();
416 TexRow & Buffer::texrow()
422 TexRow const & Buffer::texrow() const
428 TocBackend & Buffer::tocBackend() const
430 return d->toc_backend;
434 Undo & Buffer::undo()
440 string Buffer::latexName(bool const no_path) const
442 FileName latex_name = makeLatexName(d->filename);
443 return no_path ? latex_name.onlyFileName()
444 : latex_name.absFilename();
448 string Buffer::logName(LogType * type) const
450 string const filename = latexName(false);
452 if (filename.empty()) {
458 string const path = temppath();
460 FileName const fname(addName(temppath(),
461 onlyFilename(changeExtension(filename,
464 // FIXME: how do we know this is the name of the build log?
465 FileName const bname(
466 addName(path, onlyFilename(
467 changeExtension(filename,
468 formats.extension(bufferFormat()) + ".out"))));
470 // Also consider the master buffer log file
471 FileName masterfname = fname;
473 if (masterBuffer() != this) {
474 string const mlogfile = masterBuffer()->logName(&mtype);
475 masterfname = FileName(mlogfile);
478 // If no Latex log or Build log is newer, show Build log
479 if (bname.exists() &&
480 ((!fname.exists() && !masterfname.exists())
481 || (fname.lastModified() < bname.lastModified()
482 && masterfname.lastModified() < bname.lastModified()))) {
483 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
486 return bname.absFilename();
487 // If we have a newer master file log or only a master log, show this
488 } else if (fname != masterfname
489 && (!fname.exists() && masterfname.exists()
490 || fname.lastModified() < masterfname.lastModified())) {
491 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
494 return masterfname.absFilename();
496 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
499 return fname.absFilename();
503 void Buffer::setReadonly(bool const flag)
505 if (d->read_only != flag) {
512 void Buffer::setFileName(string const & newfile)
514 d->filename = makeAbsPath(newfile);
515 setReadonly(d->filename.isReadOnly());
520 int Buffer::readHeader(Lexer & lex)
522 int unknown_tokens = 0;
524 int begin_header_line = -1;
526 // Initialize parameters that may be/go lacking in header:
527 params().branchlist().clear();
528 params().preamble.erase();
529 params().options.erase();
530 params().master.erase();
531 params().float_placement.erase();
532 params().paperwidth.erase();
533 params().paperheight.erase();
534 params().leftmargin.erase();
535 params().rightmargin.erase();
536 params().topmargin.erase();
537 params().bottommargin.erase();
538 params().headheight.erase();
539 params().headsep.erase();
540 params().footskip.erase();
541 params().columnsep.erase();
542 params().fontsCJK.erase();
543 params().listings_params.clear();
544 params().clearLayoutModules();
545 params().clearRemovedModules();
546 params().pdfoptions().clear();
547 params().indiceslist().clear();
548 params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
550 for (int i = 0; i < 4; ++i) {
551 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
552 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
555 ErrorList & errorList = d->errorLists["Parse"];
564 if (token == "\\end_header")
568 if (token == "\\begin_header") {
569 begin_header_line = line;
573 LYXERR(Debug::PARSER, "Handling document header token: `"
576 string unknown = params().readToken(lex, token, d->filename.onlyPath());
577 if (!unknown.empty()) {
578 if (unknown[0] != '\\' && token == "\\textclass") {
579 Alert::warning(_("Unknown document class"),
580 bformat(_("Using the default document class, because the "
581 "class %1$s is unknown."), from_utf8(unknown)));
584 docstring const s = bformat(_("Unknown token: "
588 errorList.push_back(ErrorItem(_("Document header error"),
593 if (begin_header_line) {
594 docstring const s = _("\\begin_header is missing");
595 errorList.push_back(ErrorItem(_("Document header error"),
599 params().makeDocumentClass();
601 return unknown_tokens;
606 // changed to be public and have one parameter
607 // Returns true if "\end_document" is not read (Asger)
608 bool Buffer::readDocument(Lexer & lex)
610 ErrorList & errorList = d->errorLists["Parse"];
613 if (!lex.checkFor("\\begin_document")) {
614 docstring const s = _("\\begin_document is missing");
615 errorList.push_back(ErrorItem(_("Document header error"),
619 // we are reading in a brand new document
620 LASSERT(paragraphs().empty(), /**/);
624 if (params().outputChanges) {
625 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
626 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
627 LaTeXFeatures::isAvailable("xcolor");
629 if (!dvipost && !xcolorulem) {
630 Alert::warning(_("Changes not shown in LaTeX output"),
631 _("Changes will not be highlighted in LaTeX output, "
632 "because neither dvipost nor xcolor/ulem are installed.\n"
633 "Please install these packages or redefine "
634 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
635 } else if (!xcolorulem) {
636 Alert::warning(_("Changes not shown in LaTeX output"),
637 _("Changes will not be highlighted in LaTeX output "
638 "when using pdflatex, because xcolor and ulem are not installed.\n"
639 "Please install both packages or redefine "
640 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
644 if (!params().master.empty()) {
645 FileName const master_file = makeAbsPath(params().master,
646 onlyPath(absFileName()));
647 if (isLyXFilename(master_file.absFilename())) {
649 checkAndLoadLyXFile(master_file, true);
651 // necessary e.g. after a reload
652 // to re-register the child (bug 5873)
653 // FIXME: clean up updateMacros (here, only
654 // child registering is needed).
655 master->updateMacros();
656 // set master as master buffer, but only
657 // if we are a real child
658 if (master->isChild(this))
660 // if the master is not fully loaded
661 // it is probably just loading this
662 // child. No warning needed then.
663 else if (master->isFullyLoaded())
664 LYXERR0("The master '"
666 << "' assigned to this document ("
668 << ") does not include "
669 "this document. Ignoring the master assignment.");
675 bool const res = text().read(*this, lex, errorList, d->inset);
678 updateMacroInstances();
683 // needed to insert the selection
684 void Buffer::insertStringAsLines(ParagraphList & pars,
685 pit_type & pit, pos_type & pos,
686 Font const & fn, docstring const & str, bool autobreakrows)
690 // insert the string, don't insert doublespace
691 bool space_inserted = true;
692 for (docstring::const_iterator cit = str.begin();
693 cit != str.end(); ++cit) {
694 Paragraph & par = pars[pit];
696 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
697 breakParagraph(params(), pars, pit, pos,
698 par.layout().isEnvironment());
701 space_inserted = true;
705 // do not insert consecutive spaces if !free_spacing
706 } else if ((*cit == ' ' || *cit == '\t') &&
707 space_inserted && !par.isFreeSpacing()) {
709 } else if (*cit == '\t') {
710 if (!par.isFreeSpacing()) {
711 // tabs are like spaces here
712 par.insertChar(pos, ' ', font, params().trackChanges);
714 space_inserted = true;
716 par.insertChar(pos, *cit, font, params().trackChanges);
718 space_inserted = true;
720 } else if (!isPrintable(*cit)) {
721 // Ignore unprintables
724 // just insert the character
725 par.insertChar(pos, *cit, font, params().trackChanges);
727 space_inserted = (*cit == ' ');
734 bool Buffer::readString(string const & s)
736 params().compressed = false;
738 // remove dummy empty par
739 paragraphs().clear();
743 FileName const name = FileName::tempName("Buffer_readString");
744 switch (readFile(lex, name, true)) {
748 // We need to call lyx2lyx, so write the input to a file
749 ofstream os(name.toFilesystemEncoding().c_str());
752 return readFile(name);
762 bool Buffer::readFile(FileName const & filename)
764 FileName fname(filename);
766 params().compressed = fname.isZippedFile();
768 // remove dummy empty par
769 paragraphs().clear();
772 if (readFile(lex, fname) != success)
779 bool Buffer::isFullyLoaded() const
781 return d->file_fully_loaded;
785 void Buffer::setFullyLoaded(bool value)
787 d->file_fully_loaded = value;
791 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
794 LASSERT(!filename.empty(), /**/);
796 // the first (non-comment) token _must_ be...
797 if (!lex.checkFor("\\lyxformat")) {
798 Alert::error(_("Document format failure"),
799 bformat(_("%1$s is not a readable LyX document."),
800 from_utf8(filename.absFilename())));
806 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
807 // if present remove ".," from string.
808 size_t dot = tmp_format.find_first_of(".,");
809 //lyxerr << " dot found at " << dot << endl;
810 if (dot != string::npos)
811 tmp_format.erase(dot, 1);
812 int const file_format = convert<int>(tmp_format);
813 //lyxerr << "format: " << file_format << endl;
815 // save timestamp and checksum of the original disk file, making sure
816 // to not overwrite them with those of the file created in the tempdir
817 // when it has to be converted to the current format.
819 // Save the timestamp and checksum of disk file. If filename is an
820 // emergency file, save the timestamp and checksum of the original lyx file
821 // because isExternallyModified will check for this file. (BUG4193)
822 string diskfile = filename.absFilename();
823 if (suffixIs(diskfile, ".emergency"))
824 diskfile = diskfile.substr(0, diskfile.size() - 10);
825 saveCheckSum(FileName(diskfile));
828 if (file_format != LYX_FORMAT) {
831 // lyx2lyx would fail
834 FileName const tmpfile = FileName::tempName("Buffer_readFile");
835 if (tmpfile.empty()) {
836 Alert::error(_("Conversion failed"),
837 bformat(_("%1$s is from a different"
838 " version of LyX, but a temporary"
839 " file for converting it could"
841 from_utf8(filename.absFilename())));
844 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
845 if (lyx2lyx.empty()) {
846 Alert::error(_("Conversion script not found"),
847 bformat(_("%1$s is from a different"
848 " version of LyX, but the"
849 " conversion script lyx2lyx"
850 " could not be found."),
851 from_utf8(filename.absFilename())));
854 ostringstream command;
855 command << os::python()
856 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
857 << " -t " << convert<string>(LYX_FORMAT)
858 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
859 << ' ' << quoteName(filename.toFilesystemEncoding());
860 string const command_str = command.str();
862 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
864 cmd_ret const ret = runCommand(command_str);
865 if (ret.first != 0) {
866 Alert::error(_("Conversion script failed"),
867 bformat(_("%1$s is from a different version"
868 " of LyX, but the lyx2lyx script"
869 " failed to convert it."),
870 from_utf8(filename.absFilename())));
873 bool const ret = readFile(tmpfile);
874 // Do stuff with tmpfile name and buffer name here.
875 return ret ? success : failure;
880 if (readDocument(lex)) {
881 Alert::error(_("Document format failure"),
882 bformat(_("%1$s ended unexpectedly, which means"
883 " that it is probably corrupted."),
884 from_utf8(filename.absFilename())));
887 d->file_fully_loaded = true;
892 // Should probably be moved to somewhere else: BufferView? LyXView?
893 bool Buffer::save() const
895 // We don't need autosaves in the immediate future. (Asger)
896 resetAutosaveTimers();
898 string const encodedFilename = d->filename.toFilesystemEncoding();
901 bool madeBackup = false;
903 // make a backup if the file already exists
904 if (lyxrc.make_backup && fileName().exists()) {
905 backupName = FileName(absFileName() + '~');
906 if (!lyxrc.backupdir_path.empty()) {
907 string const mangledName =
908 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
909 backupName = FileName(addName(lyxrc.backupdir_path,
912 if (fileName().copyTo(backupName)) {
915 Alert::error(_("Backup failure"),
916 bformat(_("Cannot create backup file %1$s.\n"
917 "Please check whether the directory exists and is writeable."),
918 from_utf8(backupName.absFilename())));
919 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
923 // ask if the disk file has been externally modified (use checksum method)
924 if (fileName().exists() && isExternallyModified(checksum_method)) {
925 docstring const file = makeDisplayPath(absFileName(), 20);
926 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
927 "you want to overwrite this file?"), file);
928 int const ret = Alert::prompt(_("Overwrite modified file?"),
929 text, 1, 1, _("&Overwrite"), _("&Cancel"));
934 if (writeFile(d->filename)) {
938 // Saving failed, so backup is not backup
940 backupName.moveTo(d->filename);
946 bool Buffer::writeFile(FileName const & fname) const
948 if (d->read_only && fname == d->filename)
953 docstring const str = bformat(_("Saving document %1$s..."),
954 makeDisplayPath(fname.absFilename()));
957 if (params().compressed) {
958 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
959 retval = ofs && write(ofs);
961 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
962 retval = ofs && write(ofs);
966 message(str + _(" could not write file!"));
970 removeAutosaveFile();
972 saveCheckSum(d->filename);
973 message(str + _(" done."));
979 bool Buffer::write(ostream & ofs) const
982 // Use the standard "C" locale for file output.
983 ofs.imbue(locale::classic());
986 // The top of the file should not be written by params().
988 // write out a comment in the top of the file
989 ofs << "#LyX " << lyx_version
990 << " created this file. For more info see http://www.lyx.org/\n"
991 << "\\lyxformat " << LYX_FORMAT << "\n"
992 << "\\begin_document\n";
994 /// For each author, set 'used' to true if there is a change
995 /// by this author in the document; otherwise set it to 'false'.
996 AuthorList::Authors::const_iterator a_it = params().authors().begin();
997 AuthorList::Authors::const_iterator a_end = params().authors().end();
998 for (; a_it != a_end; ++a_it)
999 a_it->second.setUsed(false);
1001 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1002 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1003 for ( ; it != end; ++it)
1004 it->checkAuthors(params().authors());
1006 // now write out the buffer parameters.
1007 ofs << "\\begin_header\n";
1008 params().writeFile(ofs);
1009 ofs << "\\end_header\n";
1012 ofs << "\n\\begin_body\n";
1013 text().write(*this, ofs);
1014 ofs << "\n\\end_body\n";
1016 // Write marker that shows file is complete
1017 ofs << "\\end_document" << endl;
1019 // Shouldn't really be needed....
1022 // how to check if close went ok?
1023 // Following is an attempt... (BE 20001011)
1025 // good() returns false if any error occured, including some
1026 // formatting error.
1027 // bad() returns true if something bad happened in the buffer,
1028 // which should include file system full errors.
1033 lyxerr << "File was not closed properly." << endl;
1040 bool Buffer::makeLaTeXFile(FileName const & fname,
1041 string const & original_path,
1042 OutputParams const & runparams_in,
1043 bool output_preamble, bool output_body) const
1045 OutputParams runparams = runparams_in;
1046 if (params().useXetex)
1047 runparams.flavor = OutputParams::XETEX;
1049 string const encoding = runparams.encoding->iconvName();
1050 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1053 try { ofs.reset(encoding); }
1054 catch (iconv_codecvt_facet_exception & e) {
1055 lyxerr << "Caught iconv exception: " << e.what() << endl;
1056 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1057 "verify that the support software for your encoding (%1$s) is "
1058 "properly installed"), from_ascii(encoding)));
1061 if (!openFileWrite(ofs, fname))
1064 //TexStream ts(ofs.rdbuf(), &texrow());
1065 ErrorList & errorList = d->errorLists["Export"];
1067 bool failed_export = false;
1070 writeLaTeXSource(ofs, original_path,
1071 runparams, output_preamble, output_body);
1073 catch (EncodingException & e) {
1074 odocstringstream ods;
1075 ods.put(e.failed_char);
1077 oss << "0x" << hex << e.failed_char << dec;
1078 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1079 " (code point %2$s)"),
1080 ods.str(), from_utf8(oss.str()));
1081 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1082 "representable in the chosen encoding.\n"
1083 "Changing the document encoding to utf8 could help."),
1084 e.par_id, e.pos, e.pos + 1));
1085 failed_export = true;
1087 catch (iconv_codecvt_facet_exception & e) {
1088 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1089 _(e.what()), -1, 0, 0));
1090 failed_export = true;
1092 catch (exception const & e) {
1093 errorList.push_back(ErrorItem(_("conversion failed"),
1094 _(e.what()), -1, 0, 0));
1095 failed_export = true;
1098 lyxerr << "Caught some really weird exception..." << endl;
1104 failed_export = true;
1105 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1109 return !failed_export;
1113 void Buffer::writeLaTeXSource(odocstream & os,
1114 string const & original_path,
1115 OutputParams const & runparams_in,
1116 bool const output_preamble, bool const output_body) const
1118 // The child documents, if any, shall be already loaded at this point.
1120 OutputParams runparams = runparams_in;
1122 // Classify the unicode characters appearing in math insets
1123 Encodings::initUnicodeMath(*this);
1125 // validate the buffer.
1126 LYXERR(Debug::LATEX, " Validating buffer...");
1127 LaTeXFeatures features(*this, params(), runparams);
1129 LYXERR(Debug::LATEX, " Buffer validation done.");
1131 // The starting paragraph of the coming rows is the
1132 // first paragraph of the document. (Asger)
1133 if (output_preamble && runparams.nice) {
1134 os << "%% LyX " << lyx_version << " created this file. "
1135 "For more info, see http://www.lyx.org/.\n"
1136 "%% Do not edit unless you really know what "
1138 d->texrow.newline();
1139 d->texrow.newline();
1141 LYXERR(Debug::INFO, "lyx document header finished");
1143 // Don't move this behind the parent_buffer=0 code below,
1144 // because then the macros will not get the right "redefinition"
1145 // flag as they don't see the parent macros which are output before.
1148 // fold macros if possible, still with parent buffer as the
1149 // macros will be put in the prefix anyway.
1150 updateMacroInstances();
1152 // There are a few differences between nice LaTeX and usual files:
1153 // usual is \batchmode and has a
1154 // special input@path to allow the including of figures
1155 // with either \input or \includegraphics (what figinsets do).
1156 // input@path is set when the actual parameter
1157 // original_path is set. This is done for usual tex-file, but not
1158 // for nice-latex-file. (Matthias 250696)
1159 // Note that input@path is only needed for something the user does
1160 // in the preamble, included .tex files or ERT, files included by
1161 // LyX work without it.
1162 if (output_preamble) {
1163 if (!runparams.nice) {
1164 // code for usual, NOT nice-latex-file
1165 os << "\\batchmode\n"; // changed
1166 // from \nonstopmode
1167 d->texrow.newline();
1169 if (!original_path.empty()) {
1171 // We don't know the encoding of inputpath
1172 docstring const inputpath = from_utf8(latex_path(original_path));
1173 os << "\\makeatletter\n"
1174 << "\\def\\input@path{{"
1175 << inputpath << "/}}\n"
1176 << "\\makeatother\n";
1177 d->texrow.newline();
1178 d->texrow.newline();
1179 d->texrow.newline();
1182 // get parent macros (if this buffer has a parent) which will be
1183 // written at the document begin further down.
1184 MacroSet parentMacros;
1185 listParentMacros(parentMacros, features);
1187 // Write the preamble
1188 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1190 runparams.use_japanese = features.isRequired("japanese");
1196 os << "\\begin{document}\n";
1197 d->texrow.newline();
1199 // output the parent macros
1200 MacroSet::iterator it = parentMacros.begin();
1201 MacroSet::iterator end = parentMacros.end();
1202 for (; it != end; ++it)
1203 (*it)->write(os, true);
1204 } // output_preamble
1206 d->texrow.start(paragraphs().begin()->id(), 0);
1208 LYXERR(Debug::INFO, "preamble finished, now the body.");
1210 // if we are doing a real file with body, even if this is the
1211 // child of some other buffer, let's cut the link here.
1212 // This happens for example if only a child document is printed.
1213 Buffer const * save_parent = 0;
1214 if (output_preamble) {
1215 save_parent = d->parent();
1220 latexParagraphs(*this, text(), os, d->texrow, runparams);
1222 // Restore the parenthood if needed
1223 if (output_preamble)
1224 d->setParent(save_parent);
1226 // add this just in case after all the paragraphs
1228 d->texrow.newline();
1230 if (output_preamble) {
1231 os << "\\end{document}\n";
1232 d->texrow.newline();
1233 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1235 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1237 runparams_in.encoding = runparams.encoding;
1239 // Just to be sure. (Asger)
1240 d->texrow.newline();
1242 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1243 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1247 bool Buffer::isLatex() const
1249 return params().documentClass().outputType() == LATEX;
1253 bool Buffer::isLiterate() const
1255 return params().documentClass().outputType() == LITERATE;
1259 bool Buffer::isDocBook() const
1261 return params().documentClass().outputType() == DOCBOOK;
1265 void Buffer::makeDocBookFile(FileName const & fname,
1266 OutputParams const & runparams,
1267 bool const body_only) const
1269 LYXERR(Debug::LATEX, "makeDocBookFile...");
1272 if (!openFileWrite(ofs, fname))
1275 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1279 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1283 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1284 OutputParams const & runparams,
1285 bool const only_body) const
1287 LaTeXFeatures features(*this, params(), runparams);
1292 DocumentClass const & tclass = params().documentClass();
1293 string const top_element = tclass.latexname();
1296 if (runparams.flavor == OutputParams::XML)
1297 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1300 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1303 if (! tclass.class_header().empty())
1304 os << from_ascii(tclass.class_header());
1305 else if (runparams.flavor == OutputParams::XML)
1306 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1307 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1309 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1311 docstring preamble = from_utf8(params().preamble);
1312 if (runparams.flavor != OutputParams::XML ) {
1313 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1314 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1315 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1316 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1319 string const name = runparams.nice
1320 ? changeExtension(absFileName(), ".sgml") : fname;
1321 preamble += features.getIncludedFiles(name);
1322 preamble += features.getLyXSGMLEntities();
1324 if (!preamble.empty()) {
1325 os << "\n [ " << preamble << " ]";
1330 string top = top_element;
1332 if (runparams.flavor == OutputParams::XML)
1333 top += params().language->code();
1335 top += params().language->code().substr(0, 2);
1338 if (!params().options.empty()) {
1340 top += params().options;
1343 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1344 << " file was created by LyX " << lyx_version
1345 << "\n See http://www.lyx.org/ for more information -->\n";
1347 params().documentClass().counters().reset();
1351 sgml::openTag(os, top);
1353 docbookParagraphs(paragraphs(), *this, os, runparams);
1354 sgml::closeTag(os, top_element);
1358 void Buffer::makeLyXHTMLFile(FileName const & fname,
1359 OutputParams const & runparams,
1360 bool const body_only) const
1362 LYXERR(Debug::LATEX, "makeLYXHTMLFile...");
1365 if (!openFileWrite(ofs, fname))
1368 writeLyXHTMLSource(ofs, runparams, body_only);
1372 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1376 void Buffer::writeLyXHTMLSource(odocstream & os,
1377 OutputParams const & runparams,
1378 bool const only_body) const
1380 LaTeXFeatures features(*this, params(), runparams);
1386 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
1387 " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
1388 // FIXME Language should be set properly.
1389 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n";
1392 // FIXME Presumably need to set this right
1393 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1394 // FIXME Get this during validation? What about other meta-data?
1395 os << "<title>TBA</title>\n";
1397 os << features.getTClassHTMLPreamble();
1401 docstring const styleinfo = features.getTClassHTMLStyles();
1402 if (!styleinfo.empty()) {
1403 os << "<style type='text/css'>\n";
1407 os << "</head>\n<body>\n";
1410 params().documentClass().counters().reset();
1411 xhtmlParagraphs(paragraphs(), *this, os, runparams);
1413 os << "</body>\n</html>\n";
1417 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1418 // Other flags: -wall -v0 -x
1419 int Buffer::runChktex()
1423 // get LaTeX-Filename
1424 FileName const path(temppath());
1425 string const name = addName(path.absFilename(), latexName());
1426 string const org_path = filePath();
1428 PathChanger p(path); // path to LaTeX file
1429 message(_("Running chktex..."));
1431 // Generate the LaTeX file if neccessary
1432 OutputParams runparams(¶ms().encoding());
1433 runparams.flavor = OutputParams::LATEX;
1434 runparams.nice = false;
1435 makeLaTeXFile(FileName(name), org_path, runparams);
1438 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1439 int const res = chktex.run(terr); // run chktex
1442 Alert::error(_("chktex failure"),
1443 _("Could not run chktex successfully."));
1444 } else if (res > 0) {
1445 ErrorList & errlist = d->errorLists["ChkTeX"];
1447 bufferErrors(terr, errlist);
1458 void Buffer::validate(LaTeXFeatures & features) const
1460 params().validate(features);
1464 for_each(paragraphs().begin(), paragraphs().end(),
1465 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1467 if (lyxerr.debugging(Debug::LATEX)) {
1468 features.showStruct();
1473 void Buffer::getLabelList(vector<docstring> & list) const
1475 // If this is a child document, use the parent's list instead.
1476 Buffer const * const pbuf = d->parent();
1478 pbuf->getLabelList(list);
1483 Toc & toc = d->toc_backend.toc("label");
1484 TocIterator toc_it = toc.begin();
1485 TocIterator end = toc.end();
1486 for (; toc_it != end; ++toc_it) {
1487 if (toc_it->depth() == 0)
1488 list.push_back(toc_it->str());
1493 void Buffer::updateBibfilesCache(UpdateScope scope) const
1495 // If this is a child document, use the parent's cache instead.
1496 Buffer const * const pbuf = d->parent();
1497 if (pbuf && scope != UpdateChildOnly) {
1498 pbuf->updateBibfilesCache();
1502 d->bibfilesCache_.clear();
1503 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1504 if (it->lyxCode() == BIBTEX_CODE) {
1505 InsetBibtex const & inset =
1506 static_cast<InsetBibtex const &>(*it);
1507 support::FileNameList const bibfiles = inset.getBibFiles();
1508 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1511 } else if (it->lyxCode() == INCLUDE_CODE) {
1512 InsetInclude & inset =
1513 static_cast<InsetInclude &>(*it);
1514 inset.updateBibfilesCache();
1515 support::FileNameList const & bibfiles =
1516 inset.getBibfilesCache();
1517 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1522 // the bibinfo cache is now invalid
1523 d->bibinfoCacheValid_ = false;
1527 void Buffer::invalidateBibinfoCache()
1529 d->bibinfoCacheValid_ = false;
1533 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1535 // If this is a child document, use the parent's cache instead.
1536 Buffer const * const pbuf = d->parent();
1537 if (pbuf && scope != UpdateChildOnly)
1538 return pbuf->getBibfilesCache();
1540 // We update the cache when first used instead of at loading time.
1541 if (d->bibfilesCache_.empty())
1542 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1544 return d->bibfilesCache_;
1548 BiblioInfo const & Buffer::masterBibInfo() const
1550 // if this is a child document and the parent is already loaded
1551 // use the parent's list instead [ale990412]
1552 Buffer const * const tmp = masterBuffer();
1555 return tmp->masterBibInfo();
1556 return localBibInfo();
1560 BiblioInfo const & Buffer::localBibInfo() const
1562 if (d->bibinfoCacheValid_) {
1563 support::FileNameList const & bibfilesCache = getBibfilesCache();
1564 // compare the cached timestamps with the actual ones.
1565 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1566 support::FileNameList::const_iterator en = bibfilesCache.end();
1567 for (; ei != en; ++ ei) {
1568 time_t lastw = ei->lastModified();
1569 if (lastw != d->bibfileStatus_[*ei]) {
1570 d->bibinfoCacheValid_ = false;
1571 d->bibfileStatus_[*ei] = lastw;
1577 if (!d->bibinfoCacheValid_) {
1578 d->bibinfo_.clear();
1579 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1580 it->fillWithBibKeys(d->bibinfo_, it);
1581 d->bibinfoCacheValid_ = true;
1587 bool Buffer::isDepClean(string const & name) const
1589 DepClean::const_iterator const it = d->dep_clean.find(name);
1590 if (it == d->dep_clean.end())
1596 void Buffer::markDepClean(string const & name)
1598 d->dep_clean[name] = true;
1602 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1604 switch (cmd.action) {
1605 case LFUN_BUFFER_EXPORT: {
1606 docstring const arg = cmd.argument();
1607 bool enable = arg == "custom" || isExportable(to_utf8(arg));
1609 flag.message(bformat(
1610 _("Don't know how to export to format: %1$s"), arg));
1611 flag.setEnabled(enable);
1615 case LFUN_BRANCH_ACTIVATE:
1616 case LFUN_BRANCH_DEACTIVATE: {
1617 BranchList const & branchList = params().branchlist();
1618 docstring const branchName = cmd.argument();
1619 flag.setEnabled(!branchName.empty()
1620 && branchList.find(branchName));
1624 case LFUN_BUFFER_PRINT:
1625 // if no Buffer is present, then of course we won't be called!
1626 flag.setEnabled(true);
1636 void Buffer::dispatch(string const & command, DispatchResult & result)
1638 return dispatch(lyxaction.lookupFunc(command), result);
1642 // NOTE We can end up here even if we have no GUI, because we are called
1643 // by LyX::exec to handled command-line requests. So we may need to check
1644 // whether we have a GUI or not. The boolean use_gui holds this information.
1645 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1647 // We'll set this back to false if need be.
1648 bool dispatched = true;
1650 switch (func.action) {
1651 case LFUN_BUFFER_EXPORT: {
1652 bool success = doExport(to_utf8(func.argument()), false);
1653 dr.setError(success);
1655 dr.setMessage(bformat(_("Error exporting to format: %1$s."),
1660 case LFUN_BRANCH_ACTIVATE:
1661 case LFUN_BRANCH_DEACTIVATE: {
1662 BranchList & branchList = params().branchlist();
1663 docstring const branchName = func.argument();
1664 // the case without a branch name is handled elsewhere
1665 if (branchName.empty()) {
1669 Branch * branch = branchList.find(branchName);
1671 LYXERR0("Branch " << branchName << " does not exist.");
1673 docstring const msg =
1674 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1677 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1679 dr.update(Update::Force);
1684 case LFUN_BUFFER_PRINT: {
1685 // we'll assume there's a problem until we succeed
1687 string target = func.getArg(0);
1688 string target_name = func.getArg(1);
1689 string command = func.getArg(2);
1692 || target_name.empty()
1693 || command.empty()) {
1694 LYXERR0("Unable to parse " << func.argument());
1695 docstring const msg =
1696 bformat(_("Unable to parse \"%1$s\""), func.argument());
1700 if (target != "printer" && target != "file") {
1701 LYXERR0("Unrecognized target \"" << target << '"');
1702 docstring const msg =
1703 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1708 if (!doExport("dvi", true)) {
1709 showPrintError(absFileName());
1710 dr.setMessage(_("Error exporting to DVI."));
1714 // Push directory path.
1715 string const path = temppath();
1716 // Prevent the compiler from optimizing away p
1720 // there are three cases here:
1721 // 1. we print to a file
1722 // 2. we print directly to a printer
1723 // 3. we print using a spool command (print to file first)
1726 string const dviname = changeExtension(latexName(true), "dvi");
1728 if (target == "printer") {
1729 if (!lyxrc.print_spool_command.empty()) {
1730 // case 3: print using a spool
1731 string const psname = changeExtension(dviname,".ps");
1732 command += ' ' + lyxrc.print_to_file
1735 + quoteName(dviname);
1737 string command2 = lyxrc.print_spool_command + ' ';
1738 if (target_name != "default") {
1739 command2 += lyxrc.print_spool_printerprefix
1743 command2 += quoteName(psname);
1745 // If successful, then spool command
1746 res = one.startscript(Systemcall::Wait, command);
1749 // If there's no GUI, we have to wait on this command. Otherwise,
1750 // LyX deletes the temporary directory, and with it the spooled
1751 // file, before it can be printed!!
1752 Systemcall::Starttype stype = use_gui ?
1753 Systemcall::DontWait : Systemcall::Wait;
1754 res = one.startscript(stype, command2);
1757 // case 2: print directly to a printer
1758 if (target_name != "default")
1759 command += ' ' + lyxrc.print_to_printer + target_name + ' ';
1761 Systemcall::Starttype stype = use_gui ?
1762 Systemcall::DontWait : Systemcall::Wait;
1763 res = one.startscript(stype, command + quoteName(dviname));
1767 // case 1: print to a file
1768 FileName const filename(makeAbsPath(target_name, filePath()));
1769 FileName const dvifile(makeAbsPath(dviname, path));
1770 if (filename.exists()) {
1771 docstring text = bformat(
1772 _("The file %1$s already exists.\n\n"
1773 "Do you want to overwrite that file?"),
1774 makeDisplayPath(filename.absFilename()));
1775 if (Alert::prompt(_("Overwrite file?"),
1776 text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
1779 command += ' ' + lyxrc.print_to_file
1780 + quoteName(filename.toFilesystemEncoding())
1782 + quoteName(dvifile.toFilesystemEncoding());
1784 Systemcall::Starttype stype = use_gui ?
1785 Systemcall::DontWait : Systemcall::Wait;
1786 res = one.startscript(stype, command);
1792 dr.setMessage(_("Error running external commands."));
1793 showPrintError(absFileName());
1802 dr.dispatched(dispatched);
1806 void Buffer::changeLanguage(Language const * from, Language const * to)
1808 LASSERT(from, /**/);
1811 for_each(par_iterator_begin(),
1813 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1817 bool Buffer::isMultiLingual() const
1819 ParConstIterator end = par_iterator_end();
1820 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1821 if (it->isMultiLingual(params()))
1828 DocIterator Buffer::getParFromID(int const id) const
1830 Buffer * buf = const_cast<Buffer *>(this);
1832 // John says this is called with id == -1 from undo
1833 lyxerr << "getParFromID(), id: " << id << endl;
1834 return doc_iterator_end(buf);
1837 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1838 if (it.paragraph().id() == id)
1841 return doc_iterator_end(buf);
1845 bool Buffer::hasParWithID(int const id) const
1847 return !getParFromID(id).atEnd();
1851 ParIterator Buffer::par_iterator_begin()
1853 return ParIterator(doc_iterator_begin(this));
1857 ParIterator Buffer::par_iterator_end()
1859 return ParIterator(doc_iterator_end(this));
1863 ParConstIterator Buffer::par_iterator_begin() const
1865 return ParConstIterator(doc_iterator_begin(this));
1869 ParConstIterator Buffer::par_iterator_end() const
1871 return ParConstIterator(doc_iterator_end(this));
1875 Language const * Buffer::language() const
1877 return params().language;
1881 docstring const Buffer::B_(string const & l10n) const
1883 return params().B_(l10n);
1887 bool Buffer::isClean() const
1889 return d->lyx_clean;
1893 bool Buffer::isBakClean() const
1895 return d->bak_clean;
1899 bool Buffer::isExternallyModified(CheckMethod method) const
1901 LASSERT(d->filename.exists(), /**/);
1902 // if method == timestamp, check timestamp before checksum
1903 return (method == checksum_method
1904 || d->timestamp_ != d->filename.lastModified())
1905 && d->checksum_ != d->filename.checksum();
1909 void Buffer::saveCheckSum(FileName const & file) const
1911 if (file.exists()) {
1912 d->timestamp_ = file.lastModified();
1913 d->checksum_ = file.checksum();
1915 // in the case of save to a new file.
1922 void Buffer::markClean() const
1924 if (!d->lyx_clean) {
1925 d->lyx_clean = true;
1928 // if the .lyx file has been saved, we don't need an
1930 d->bak_clean = true;
1934 void Buffer::markBakClean() const
1936 d->bak_clean = true;
1940 void Buffer::setUnnamed(bool flag)
1946 bool Buffer::isUnnamed() const
1952 // FIXME: this function should be moved to buffer_pimpl.C
1953 void Buffer::markDirty()
1956 d->lyx_clean = false;
1959 d->bak_clean = false;
1961 DepClean::iterator it = d->dep_clean.begin();
1962 DepClean::const_iterator const end = d->dep_clean.end();
1964 for (; it != end; ++it)
1969 FileName Buffer::fileName() const
1975 string Buffer::absFileName() const
1977 return d->filename.absFilename();
1981 string Buffer::filePath() const
1983 return d->filename.onlyPath().absFilename() + "/";
1987 bool Buffer::isReadonly() const
1989 return d->read_only;
1993 void Buffer::setParent(Buffer const * buffer)
1995 // Avoids recursive include.
1996 d->setParent(buffer == this ? 0 : buffer);
2001 Buffer const * Buffer::parent() const
2007 void Buffer::collectRelatives(BufferSet & bufs) const
2011 parent()->collectRelatives(bufs);
2013 // loop over children
2014 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2015 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2016 for (; it != end; ++it)
2017 bufs.insert(const_cast<Buffer *>(it->first));
2021 std::vector<Buffer const *> Buffer::allRelatives() const
2024 collectRelatives(bufs);
2025 BufferSet::iterator it = bufs.begin();
2026 std::vector<Buffer const *> ret;
2027 for (; it != bufs.end(); ++it)
2033 Buffer const * Buffer::masterBuffer() const
2035 Buffer const * const pbuf = d->parent();
2039 return pbuf->masterBuffer();
2043 bool Buffer::isChild(Buffer * child) const
2045 return d->children_positions.find(child) != d->children_positions.end();
2049 DocIterator Buffer::firstChildPosition(Buffer const * child)
2051 Impl::BufferPositionMap::iterator it;
2052 it = d->children_positions.find(child);
2053 if (it == d->children_positions.end())
2054 return DocIterator(this);
2059 std::vector<Buffer *> Buffer::getChildren() const
2061 std::vector<Buffer *> clist;
2062 // loop over children
2063 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2064 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2065 for (; it != end; ++it) {
2066 Buffer * child = const_cast<Buffer *>(it->first);
2067 clist.push_back(child);
2068 // there might be grandchildren
2069 std::vector<Buffer *> glist = child->getChildren();
2070 for (vector<Buffer *>::const_iterator git = glist.begin();
2071 git != glist.end(); ++git)
2072 clist.push_back(*git);
2078 template<typename M>
2079 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2084 typename M::iterator it = m.lower_bound(x);
2085 if (it == m.begin())
2093 MacroData const * Buffer::getBufferMacro(docstring const & name,
2094 DocIterator const & pos) const
2096 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2098 // if paragraphs have no macro context set, pos will be empty
2102 // we haven't found anything yet
2103 DocIterator bestPos = par_iterator_begin();
2104 MacroData const * bestData = 0;
2106 // find macro definitions for name
2107 Impl::NamePositionScopeMacroMap::iterator nameIt
2108 = d->macros.find(name);
2109 if (nameIt != d->macros.end()) {
2110 // find last definition in front of pos or at pos itself
2111 Impl::PositionScopeMacroMap::const_iterator it
2112 = greatest_below(nameIt->second, pos);
2113 if (it != nameIt->second.end()) {
2115 // scope ends behind pos?
2116 if (pos < it->second.first) {
2117 // Looks good, remember this. If there
2118 // is no external macro behind this,
2119 // we found the right one already.
2120 bestPos = it->first;
2121 bestData = &it->second.second;
2125 // try previous macro if there is one
2126 if (it == nameIt->second.begin())
2133 // find macros in included files
2134 Impl::PositionScopeBufferMap::const_iterator it
2135 = greatest_below(d->position_to_children, pos);
2136 if (it == d->position_to_children.end())
2137 // no children before
2141 // do we know something better (i.e. later) already?
2142 if (it->first < bestPos )
2145 // scope ends behind pos?
2146 if (pos < it->second.first) {
2147 // look for macro in external file
2148 d->macro_lock = true;
2149 MacroData const * data
2150 = it->second.second->getMacro(name, false);
2151 d->macro_lock = false;
2153 bestPos = it->first;
2159 // try previous file if there is one
2160 if (it == d->position_to_children.begin())
2165 // return the best macro we have found
2170 MacroData const * Buffer::getMacro(docstring const & name,
2171 DocIterator const & pos, bool global) const
2176 // query buffer macros
2177 MacroData const * data = getBufferMacro(name, pos);
2181 // If there is a master buffer, query that
2182 Buffer const * const pbuf = d->parent();
2184 d->macro_lock = true;
2185 MacroData const * macro = pbuf->getMacro(
2186 name, *this, false);
2187 d->macro_lock = false;
2193 data = MacroTable::globalMacros().get(name);
2202 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2204 // set scope end behind the last paragraph
2205 DocIterator scope = par_iterator_begin();
2206 scope.pit() = scope.lastpit() + 1;
2208 return getMacro(name, scope, global);
2212 MacroData const * Buffer::getMacro(docstring const & name,
2213 Buffer const & child, bool global) const
2215 // look where the child buffer is included first
2216 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2217 if (it == d->children_positions.end())
2220 // check for macros at the inclusion position
2221 return getMacro(name, it->second, global);
2225 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2227 pit_type lastpit = it.lastpit();
2229 // look for macros in each paragraph
2230 while (it.pit() <= lastpit) {
2231 Paragraph & par = it.paragraph();
2233 // iterate over the insets of the current paragraph
2234 InsetList const & insets = par.insetList();
2235 InsetList::const_iterator iit = insets.begin();
2236 InsetList::const_iterator end = insets.end();
2237 for (; iit != end; ++iit) {
2238 it.pos() = iit->pos;
2240 // is it a nested text inset?
2241 if (iit->inset->asInsetText()) {
2242 // Inset needs its own scope?
2243 InsetText const * itext = iit->inset->asInsetText();
2244 bool newScope = itext->isMacroScope();
2246 // scope which ends just behind the inset
2247 DocIterator insetScope = it;
2250 // collect macros in inset
2251 it.push_back(CursorSlice(*iit->inset));
2252 updateMacros(it, newScope ? insetScope : scope);
2257 // is it an external file?
2258 if (iit->inset->lyxCode() == INCLUDE_CODE) {
2259 // get buffer of external file
2260 InsetInclude const & inset =
2261 static_cast<InsetInclude const &>(*iit->inset);
2262 d->macro_lock = true;
2263 Buffer * child = inset.getChildBuffer();
2264 d->macro_lock = false;
2268 // register its position, but only when it is
2269 // included first in the buffer
2270 if (d->children_positions.find(child) ==
2271 d->children_positions.end())
2272 d->children_positions[child] = it;
2274 // register child with its scope
2275 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2279 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2283 MathMacroTemplate & macroTemplate =
2284 static_cast<MathMacroTemplate &>(*iit->inset);
2285 MacroContext mc(*this, it);
2286 macroTemplate.updateToContext(mc);
2289 bool valid = macroTemplate.validMacro();
2290 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2291 // then the BufferView's cursor will be invalid in
2292 // some cases which leads to crashes.
2297 d->macros[macroTemplate.name()][it] =
2298 Impl::ScopeMacro(scope, MacroData(*this, it));
2308 void Buffer::updateMacros() const
2313 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2315 // start with empty table
2317 d->children_positions.clear();
2318 d->position_to_children.clear();
2320 // Iterate over buffer, starting with first paragraph
2321 // The scope must be bigger than any lookup DocIterator
2322 // later. For the global lookup, lastpit+1 is used, hence
2323 // we use lastpit+2 here.
2324 DocIterator it = par_iterator_begin();
2325 DocIterator outerScope = it;
2326 outerScope.pit() = outerScope.lastpit() + 2;
2327 updateMacros(it, outerScope);
2331 void Buffer::updateMacroInstances() const
2333 LYXERR(Debug::MACROS, "updateMacroInstances for "
2334 << d->filename.onlyFileName());
2335 DocIterator it = doc_iterator_begin(this);
2336 DocIterator end = doc_iterator_end(this);
2337 for (; it != end; it.forwardPos()) {
2338 // look for MathData cells in InsetMathNest insets
2339 Inset * inset = it.nextInset();
2343 InsetMath * minset = inset->asInsetMath();
2347 // update macro in all cells of the InsetMathNest
2348 DocIterator::idx_type n = minset->nargs();
2349 MacroContext mc = MacroContext(*this, it);
2350 for (DocIterator::idx_type i = 0; i < n; ++i) {
2351 MathData & data = minset->cell(i);
2352 data.updateMacros(0, mc);
2358 void Buffer::listMacroNames(MacroNameSet & macros) const
2363 d->macro_lock = true;
2365 // loop over macro names
2366 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2367 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2368 for (; nameIt != nameEnd; ++nameIt)
2369 macros.insert(nameIt->first);
2371 // loop over children
2372 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2373 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2374 for (; it != end; ++it)
2375 it->first->listMacroNames(macros);
2378 Buffer const * const pbuf = d->parent();
2380 pbuf->listMacroNames(macros);
2382 d->macro_lock = false;
2386 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2388 Buffer const * const pbuf = d->parent();
2393 pbuf->listMacroNames(names);
2396 MacroNameSet::iterator it = names.begin();
2397 MacroNameSet::iterator end = names.end();
2398 for (; it != end; ++it) {
2400 MacroData const * data =
2401 pbuf->getMacro(*it, *this, false);
2403 macros.insert(data);
2405 // we cannot access the original MathMacroTemplate anymore
2406 // here to calls validate method. So we do its work here manually.
2407 // FIXME: somehow make the template accessible here.
2408 if (data->optionals() > 0)
2409 features.require("xargs");
2415 Buffer::References & Buffer::references(docstring const & label)
2418 return const_cast<Buffer *>(masterBuffer())->references(label);
2420 RefCache::iterator it = d->ref_cache_.find(label);
2421 if (it != d->ref_cache_.end())
2422 return it->second.second;
2424 static InsetLabel const * dummy_il = 0;
2425 static References const dummy_refs;
2426 it = d->ref_cache_.insert(
2427 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2428 return it->second.second;
2432 Buffer::References const & Buffer::references(docstring const & label) const
2434 return const_cast<Buffer *>(this)->references(label);
2438 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2440 masterBuffer()->d->ref_cache_[label].first = il;
2444 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2446 return masterBuffer()->d->ref_cache_[label].first;
2450 void Buffer::clearReferenceCache() const
2453 d->ref_cache_.clear();
2457 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2460 //FIXME: This does not work for child documents yet.
2461 LASSERT(code == CITE_CODE, /**/);
2462 // Check if the label 'from' appears more than once
2463 vector<docstring> labels;
2465 BiblioInfo const & keys = masterBibInfo();
2466 BiblioInfo::const_iterator bit = keys.begin();
2467 BiblioInfo::const_iterator bend = keys.end();
2469 for (; bit != bend; ++bit)
2471 labels.push_back(bit->first);
2474 if (count(labels.begin(), labels.end(), from) > 1)
2477 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2478 if (it->lyxCode() == code) {
2479 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2480 docstring const oldValue = inset.getParam(paramName);
2481 if (oldValue == from)
2482 inset.setParam(paramName, to);
2488 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2489 pit_type par_end, bool full_source) const
2491 OutputParams runparams(¶ms().encoding());
2492 runparams.nice = true;
2493 runparams.flavor = params().useXetex ?
2494 OutputParams::XETEX : OutputParams::LATEX;
2495 runparams.linelen = lyxrc.plaintext_linelen;
2496 // No side effect of file copying and image conversion
2497 runparams.dryrun = true;
2500 os << "% " << _("Preview source code") << "\n\n";
2502 d->texrow.newline();
2503 d->texrow.newline();
2505 writeDocBookSource(os, absFileName(), runparams, false);
2507 // latex or literate
2508 writeLaTeXSource(os, string(), runparams, true, true);
2510 runparams.par_begin = par_begin;
2511 runparams.par_end = par_end;
2512 if (par_begin + 1 == par_end) {
2514 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2518 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2519 convert<docstring>(par_begin),
2520 convert<docstring>(par_end - 1))
2527 // output paragraphs
2529 docbookParagraphs(paragraphs(), *this, os, runparams);
2531 // latex or literate
2532 latexParagraphs(*this, text(), os, texrow, runparams);
2537 ErrorList & Buffer::errorList(string const & type) const
2539 static ErrorList emptyErrorList;
2540 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2541 if (I == d->errorLists.end())
2542 return emptyErrorList;
2548 void Buffer::updateTocItem(std::string const & type,
2549 DocIterator const & dit) const
2552 gui_->updateTocItem(type, dit);
2556 void Buffer::structureChanged() const
2559 gui_->structureChanged();
2563 void Buffer::errors(string const & err, bool from_master) const
2566 gui_->errors(err, from_master);
2570 void Buffer::message(docstring const & msg) const
2577 void Buffer::setBusy(bool on) const
2584 void Buffer::setReadOnly(bool on) const
2587 d->wa_->setReadOnly(on);
2591 void Buffer::updateTitles() const
2594 d->wa_->updateTitles();
2598 void Buffer::resetAutosaveTimers() const
2601 gui_->resetAutosaveTimers();
2605 bool Buffer::hasGuiDelegate() const
2611 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2620 class AutoSaveBuffer : public ForkedProcess {
2623 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2624 : buffer_(buffer), fname_(fname) {}
2626 virtual boost::shared_ptr<ForkedProcess> clone() const
2628 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2633 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2634 from_utf8(fname_.absFilename())));
2635 return run(DontWait);
2639 virtual int generateChild();
2641 Buffer const & buffer_;
2646 int AutoSaveBuffer::generateChild()
2648 // tmp_ret will be located (usually) in /tmp
2649 // will that be a problem?
2650 // Note that this calls ForkedCalls::fork(), so it's
2651 // ok cross-platform.
2652 pid_t const pid = fork();
2653 // If you want to debug the autosave
2654 // you should set pid to -1, and comment out the fork.
2655 if (pid != 0 && pid != -1)
2658 // pid = -1 signifies that lyx was unable
2659 // to fork. But we will do the save
2661 bool failed = false;
2662 FileName const tmp_ret = FileName::tempName("lyxauto");
2663 if (!tmp_ret.empty()) {
2664 buffer_.writeFile(tmp_ret);
2665 // assume successful write of tmp_ret
2666 if (!tmp_ret.moveTo(fname_))
2672 // failed to write/rename tmp_ret so try writing direct
2673 if (!buffer_.writeFile(fname_)) {
2674 // It is dangerous to do this in the child,
2675 // but safe in the parent, so...
2676 if (pid == -1) // emit message signal.
2677 buffer_.message(_("Autosave failed!"));
2681 if (pid == 0) // we are the child so...
2690 FileName Buffer::getAutosaveFilename() const
2692 // if the document is unnamed try to save in the backup dir, else
2693 // in the default document path, and as a last try in the filePath,
2694 // which will most often be the temporary directory
2697 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
2698 : lyxrc.backupdir_path;
2699 if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
2702 string const fname = "#" + d->filename.onlyFileName() + "#";
2703 return makeAbsPath(fname, fpath);
2707 void Buffer::removeAutosaveFile() const
2709 FileName const f = getAutosaveFilename();
2715 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
2717 FileName const newauto = getAutosaveFilename();
2718 if (!(oldauto == newauto || oldauto.moveTo(newauto)))
2719 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
2723 // Perfect target for a thread...
2724 void Buffer::autoSave() const
2726 if (isBakClean() || isReadonly()) {
2727 // We don't save now, but we'll try again later
2728 resetAutosaveTimers();
2732 // emit message signal.
2733 message(_("Autosaving current document..."));
2734 AutoSaveBuffer autosave(*this, getAutosaveFilename());
2738 resetAutosaveTimers();
2742 string Buffer::bufferFormat() const
2744 string format = params().documentClass().outputFormat();
2745 if (format == "latex") {
2746 if (params().useXetex)
2748 if (params().encoding().package() == Encoding::japanese)
2755 string Buffer::getDefaultOutputFormat() const
2757 if (!params().defaultOutputFormat.empty()
2758 && params().defaultOutputFormat != "default")
2759 return params().defaultOutputFormat;
2760 typedef vector<Format const *> Formats;
2761 Formats formats = exportableFormats(true);
2764 || params().useXetex
2765 || params().encoding().package() == Encoding::japanese) {
2766 if (formats.empty())
2768 // return the first we find
2769 return formats.front()->name();
2771 return lyxrc.default_view_format;
2776 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2777 string & result_file) const
2779 string backend_format;
2780 OutputParams runparams(¶ms().encoding());
2781 runparams.flavor = OutputParams::LATEX;
2782 runparams.linelen = lyxrc.plaintext_linelen;
2783 vector<string> backs = backends();
2784 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2785 // Get shortest path to format
2786 Graph::EdgePath path;
2787 for (vector<string>::const_iterator it = backs.begin();
2788 it != backs.end(); ++it) {
2789 Graph::EdgePath p = theConverters().getPath(*it, format);
2790 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2791 backend_format = *it;
2796 runparams.flavor = theConverters().getFlavor(path);
2798 Alert::error(_("Couldn't export file"),
2799 bformat(_("No information for exporting the format %1$s."),
2800 formats.prettyName(format)));
2804 backend_format = format;
2805 // FIXME: Don't hardcode format names here, but use a flag
2806 if (backend_format == "pdflatex")
2807 runparams.flavor = OutputParams::PDFLATEX;
2810 string filename = latexName(false);
2811 filename = addName(temppath(), filename);
2812 filename = changeExtension(filename,
2813 formats.extension(backend_format));
2816 updateMacroInstances();
2818 // Plain text backend
2819 if (backend_format == "text")
2820 writePlaintextFile(*this, FileName(filename), runparams);
2822 else if (backend_format == "xhtml")
2823 makeLyXHTMLFile(FileName(filename), runparams);
2824 else if (backend_format == "lyx")
2825 writeFile(FileName(filename));
2827 else if (isDocBook()) {
2828 runparams.nice = !put_in_tempdir;
2829 makeDocBookFile(FileName(filename), runparams);
2832 else if (backend_format == format) {
2833 runparams.nice = true;
2834 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2836 } else if (!lyxrc.tex_allows_spaces
2837 && contains(filePath(), ' ')) {
2838 Alert::error(_("File name error"),
2839 _("The directory path to the document cannot contain spaces."));
2842 runparams.nice = false;
2843 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2847 string const error_type = (format == "program")
2848 ? "Build" : bufferFormat();
2849 ErrorList & error_list = d->errorLists[error_type];
2850 string const ext = formats.extension(format);
2851 FileName const tmp_result_file(changeExtension(filename, ext));
2852 bool const success = theConverters().convert(this, FileName(filename),
2853 tmp_result_file, FileName(absFileName()), backend_format, format,
2855 // Emit the signal to show the error list.
2856 if (format != backend_format) {
2858 // also to the children, in case of master-buffer-view
2859 std::vector<Buffer *> clist = getChildren();
2860 for (vector<Buffer *>::const_iterator cit = clist.begin();
2861 cit != clist.end(); ++cit)
2862 (*cit)->errors(error_type, true);
2867 if (put_in_tempdir) {
2868 result_file = tmp_result_file.absFilename();
2872 result_file = changeExtension(absFileName(), ext);
2873 // We need to copy referenced files (e. g. included graphics
2874 // if format == "dvi") to the result dir.
2875 vector<ExportedFile> const files =
2876 runparams.exportdata->externalFiles(format);
2877 string const dest = onlyPath(result_file);
2878 CopyStatus status = SUCCESS;
2879 for (vector<ExportedFile>::const_iterator it = files.begin();
2880 it != files.end() && status != CANCEL; ++it) {
2881 string const fmt = formats.getFormatFromFile(it->sourceName);
2882 status = copyFile(fmt, it->sourceName,
2883 makeAbsPath(it->exportName, dest),
2884 it->exportName, status == FORCE);
2886 if (status == CANCEL) {
2887 message(_("Document export cancelled."));
2888 } else if (tmp_result_file.exists()) {
2889 // Finally copy the main file
2890 status = copyFile(format, tmp_result_file,
2891 FileName(result_file), result_file,
2893 message(bformat(_("Document exported as %1$s "
2895 formats.prettyName(format),
2896 makeDisplayPath(result_file)));
2898 // This must be a dummy converter like fax (bug 1888)
2899 message(bformat(_("Document exported as %1$s"),
2900 formats.prettyName(format)));
2907 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2910 return doExport(format, put_in_tempdir, result_file);
2914 bool Buffer::preview(string const & format) const
2917 if (!doExport(format, true, result_file))
2919 return formats.view(*this, FileName(result_file), format);
2923 bool Buffer::isExportable(string const & format) const
2925 vector<string> backs = backends();
2926 for (vector<string>::const_iterator it = backs.begin();
2927 it != backs.end(); ++it)
2928 if (theConverters().isReachable(*it, format))
2934 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2936 vector<string> backs = backends();
2937 vector<Format const *> result =
2938 theConverters().getReachable(backs[0], only_viewable, true);
2939 for (vector<string>::const_iterator it = backs.begin() + 1;
2940 it != backs.end(); ++it) {
2941 vector<Format const *> r =
2942 theConverters().getReachable(*it, only_viewable, false);
2943 result.insert(result.end(), r.begin(), r.end());
2949 vector<string> Buffer::backends() const
2952 if (params().baseClass()->isTeXClassAvailable()) {
2953 v.push_back(bufferFormat());
2954 // FIXME: Don't hardcode format names here, but use a flag
2955 if (v.back() == "latex")
2956 v.push_back("pdflatex");
2958 v.push_back("text");
2959 v.push_back("xhtml");
2965 bool Buffer::readFileHelper(FileName const & s)
2967 // File information about normal file
2969 docstring const file = makeDisplayPath(s.absFilename(), 50);
2970 docstring text = bformat(_("The specified document\n%1$s"
2971 "\ncould not be read."), file);
2972 Alert::error(_("Could not read document"), text);
2976 // Check if emergency save file exists and is newer.
2977 FileName const e(s.absFilename() + ".emergency");
2979 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2980 docstring const file = makeDisplayPath(s.absFilename(), 20);
2981 docstring const text =
2982 bformat(_("An emergency save of the document "
2984 "Recover emergency save?"), file);
2985 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2986 _("&Recover"), _("&Load Original"),
2990 // the file is not saved if we load the emergency file.
3000 // Now check if autosave file is newer.
3001 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3003 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3004 docstring const file = makeDisplayPath(s.absFilename(), 20);
3005 docstring const text =
3006 bformat(_("The backup of the document "
3007 "%1$s is newer.\n\nLoad the "
3008 "backup instead?"), file);
3009 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3010 _("&Load backup"), _("Load &original"),
3014 // the file is not saved if we load the autosave file.
3018 // Here we delete the autosave
3029 bool Buffer::loadLyXFile(FileName const & s)
3031 if (s.isReadableFile()) {
3032 if (readFileHelper(s)) {
3033 lyxvc().file_found_hook(s);
3034 if (!s.isWritable())
3039 docstring const file = makeDisplayPath(s.absFilename(), 20);
3040 // Here we probably should run
3041 if (LyXVC::file_not_found_hook(s)) {
3042 docstring const text =
3043 bformat(_("Do you want to retrieve the document"
3044 " %1$s from version control?"), file);
3045 int const ret = Alert::prompt(_("Retrieve from version control?"),
3046 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3049 // How can we know _how_ to do the checkout?
3050 // With the current VC support it has to be,
3051 // a RCS file since CVS do not have special ,v files.
3053 return loadLyXFile(s);
3061 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3063 TeXErrors::Errors::const_iterator cit = terr.begin();
3064 TeXErrors::Errors::const_iterator end = terr.end();
3066 for (; cit != end; ++cit) {
3069 int errorRow = cit->error_in_line;
3070 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3076 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3077 } while (found && id_start == id_end && pos_start == pos_end);
3079 errorList.push_back(ErrorItem(cit->error_desc,
3080 cit->error_text, id_start, pos_start, pos_end));
3085 void Buffer::setBuffersForInsets() const
3087 inset().setBuffer(const_cast<Buffer &>(*this));
3091 void Buffer::updateLabels(UpdateScope scope) const
3093 // Use the master text class also for child documents
3094 Buffer const * const master = masterBuffer();
3095 DocumentClass const & textclass = master->params().documentClass();
3097 // keep the buffers to be children in this set. If the call from the
3098 // master comes back we can see which of them were actually seen (i.e.
3099 // via an InsetInclude). The remaining ones in the set need still be updated.
3100 static std::set<Buffer const *> bufToUpdate;
3101 if (scope == UpdateMaster) {
3102 // If this is a child document start with the master
3103 if (master != this) {
3104 bufToUpdate.insert(this);
3105 master->updateLabels();
3106 // Do this here in case the master has no gui associated with it. Then,
3107 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3111 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3112 if (bufToUpdate.find(this) == bufToUpdate.end())
3116 // start over the counters in the master
3117 textclass.counters().reset();
3120 // update will be done below for this buffer
3121 bufToUpdate.erase(this);
3123 // update all caches
3124 clearReferenceCache();
3127 Buffer & cbuf = const_cast<Buffer &>(*this);
3129 LASSERT(!text().paragraphs().empty(), /**/);
3132 ParIterator parit = cbuf.par_iterator_begin();
3133 updateLabels(parit);
3136 // TocBackend update will be done later.
3139 cbuf.tocBackend().update();
3140 if (scope == UpdateMaster)
3141 cbuf.structureChanged();
3145 static depth_type getDepth(DocIterator const & it)
3147 depth_type depth = 0;
3148 for (size_t i = 0 ; i < it.depth() ; ++i)
3149 if (!it[i].inset().inMathed())
3150 depth += it[i].paragraph().getDepth() + 1;
3151 // remove 1 since the outer inset does not count
3155 static depth_type getItemDepth(ParIterator const & it)
3157 Paragraph const & par = *it;
3158 LabelType const labeltype = par.layout().labeltype;
3160 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3163 // this will hold the lowest depth encountered up to now.
3164 depth_type min_depth = getDepth(it);
3165 ParIterator prev_it = it;
3168 --prev_it.top().pit();
3170 // start of nested inset: go to outer par
3172 if (prev_it.empty()) {
3173 // start of document: nothing to do
3178 // We search for the first paragraph with same label
3179 // that is not more deeply nested.
3180 Paragraph & prev_par = *prev_it;
3181 depth_type const prev_depth = getDepth(prev_it);
3182 if (labeltype == prev_par.layout().labeltype) {
3183 if (prev_depth < min_depth)
3184 return prev_par.itemdepth + 1;
3185 if (prev_depth == min_depth)
3186 return prev_par.itemdepth;
3188 min_depth = min(min_depth, prev_depth);
3189 // small optimization: if we are at depth 0, we won't
3190 // find anything else
3191 if (prev_depth == 0)
3197 static bool needEnumCounterReset(ParIterator const & it)
3199 Paragraph const & par = *it;
3200 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3201 depth_type const cur_depth = par.getDepth();
3202 ParIterator prev_it = it;
3203 while (prev_it.pit()) {
3204 --prev_it.top().pit();
3205 Paragraph const & prev_par = *prev_it;
3206 if (prev_par.getDepth() <= cur_depth)
3207 return prev_par.layout().labeltype != LABEL_ENUMERATE;
3209 // start of nested inset: reset
3214 // set the label of a paragraph. This includes the counters.
3215 static void setLabel(Buffer const & buf, ParIterator & it)
3217 BufferParams const & bp = buf.masterBuffer()->params();
3218 DocumentClass const & textclass = bp.documentClass();
3219 Paragraph & par = it.paragraph();
3220 Layout const & layout = par.layout();
3221 Counters & counters = textclass.counters();
3223 if (par.params().startOfAppendix()) {
3224 // FIXME: only the counter corresponding to toplevel
3225 // sectionning should be reset
3227 counters.appendix(true);
3229 par.params().appendix(counters.appendix());
3231 // Compute the item depth of the paragraph
3232 par.itemdepth = getItemDepth(it);
3234 if (layout.margintype == MARGIN_MANUAL
3235 || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3236 if (par.params().labelWidthString().empty())
3237 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
3239 par.params().labelWidthString(docstring());
3242 switch(layout.labeltype) {
3244 if (layout.toclevel <= bp.secnumdepth
3245 && (layout.latextype != LATEX_ENVIRONMENT
3246 || isFirstInSequence(it.pit(), it.plist()))) {
3247 counters.step(layout.counter);
3248 par.params().labelString(
3249 par.expandLabel(layout, bp));
3251 par.params().labelString(docstring());
3254 case LABEL_ITEMIZE: {
3255 // At some point of time we should do something more
3256 // clever here, like:
3257 // par.params().labelString(
3258 // bp.user_defined_bullet(par.itemdepth).getText());
3259 // for now, use a simple hardcoded label
3260 docstring itemlabel;
3261 switch (par.itemdepth) {
3263 itemlabel = char_type(0x2022);
3266 itemlabel = char_type(0x2013);
3269 itemlabel = char_type(0x2217);
3272 itemlabel = char_type(0x2219); // or 0x00b7
3275 par.params().labelString(itemlabel);
3279 case LABEL_ENUMERATE: {
3280 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3282 switch (par.itemdepth) {
3291 enumcounter += "iv";
3294 // not a valid enumdepth...
3298 // Maybe we have to reset the enumeration counter.
3299 if (needEnumCounterReset(it))
3300 counters.reset(enumcounter);
3301 counters.step(enumcounter);
3303 par.params().labelString(counters.theCounter(enumcounter));
3308 case LABEL_SENSITIVE: {
3309 string const & type = counters.current_float();
3310 docstring full_label;
3312 full_label = buf.B_("Senseless!!! ");
3314 docstring name = buf.B_(textclass.floats().getType(type).name());
3315 if (counters.hasCounter(from_utf8(type))) {
3316 counters.step(from_utf8(type));
3317 full_label = bformat(from_ascii("%1$s %2$s:"),
3319 counters.theCounter(from_utf8(type)));
3321 full_label = bformat(from_ascii("%1$s #:"), name);
3323 par.params().labelString(full_label);
3327 case LABEL_NO_LABEL:
3328 par.params().labelString(docstring());
3332 case LABEL_TOP_ENVIRONMENT:
3333 case LABEL_CENTERED_TOP_ENVIRONMENT:
3336 par.params().labelString(
3337 par.translateIfPossible(layout.labelstring(), bp));
3343 void Buffer::updateLabels(ParIterator & parit) const
3345 LASSERT(parit.pit() == 0, /**/);
3347 // set the position of the text in the buffer to be able
3348 // to resolve macros in it. This has nothing to do with
3349 // labels, but by putting it here we avoid implementing
3350 // a whole bunch of traversal routines just for this call.
3351 parit.text()->setMacrocontextPosition(parit);
3353 depth_type maxdepth = 0;
3354 pit_type const lastpit = parit.lastpit();
3355 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3356 // reduce depth if necessary
3357 parit->params().depth(min(parit->params().depth(), maxdepth));
3358 maxdepth = parit->getMaxDepthAfter();
3360 // set the counter for this paragraph
3361 setLabel(*this, parit);
3364 InsetList::const_iterator iit = parit->insetList().begin();
3365 InsetList::const_iterator end = parit->insetList().end();
3366 for (; iit != end; ++iit) {
3367 parit.pos() = iit->pos;
3368 iit->inset->updateLabels(parit);
3374 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3375 WordLangTuple & word_lang, docstring_list & suggestions) const
3379 suggestions.clear();
3380 // We are only interested in text so remove the math CursorSlice.
3381 while (from.inMathed())
3384 // OK, we start from here.
3386 while (!from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3389 // end of file reached.
3390 word_lang = WordLangTuple();
3391 suggestions.clear();