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 "DocIterator.h"
29 #include "ErrorList.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
36 #include "LaTeXFeatures.h"
40 #include "LyXAction.h"
44 #include "output_docbook.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
55 #include "TexStream.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
60 #include "VCBackend.h"
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
77 #include "graphics/Previews.h"
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
110 using namespace lyx::support;
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 348; // uwestoehr: add support for \*phantom
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
128 class BufferSet : public std::set<Buffer const *> {};
133 Impl(Buffer & parent, FileName const & file, bool readonly);
147 mutable TexRow texrow;
149 /// need to regenerate .tex?
153 mutable bool lyx_clean;
155 /// is autosave needed?
156 mutable bool bak_clean;
158 /// is this a unnamed file (New...)?
164 /// name of the file the buffer is associated with.
167 /** Set to true only when the file is fully loaded.
168 * Used to prevent the premature generation of previews
169 * and by the citation inset.
171 bool file_fully_loaded;
174 mutable TocBackend toc_backend;
177 typedef pair<DocIterator, MacroData> ScopeMacro;
178 typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
179 typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
180 /// map from the macro name to the position map,
181 /// which maps the macro definition position to the scope and the MacroData.
182 NamePositionScopeMacroMap macros;
185 /// positions of child buffers in the buffer
186 typedef map<Buffer const * const, DocIterator> BufferPositionMap;
187 typedef pair<DocIterator, Buffer const *> ScopeBuffer;
188 typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
189 /// position of children buffers in this buffer
190 BufferPositionMap children_positions;
191 /// map from children inclusion positions to their scope and their buffer
192 PositionScopeBufferMap position_to_children;
194 /// Container for all sort of Buffer dependant errors.
195 map<string, ErrorList> errorLists;
197 /// timestamp and checksum used to test if the file has been externally
198 /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200 unsigned long checksum_;
203 frontend::WorkAreaManager * wa_;
208 /// A cache for the bibfiles (including bibfiles of loaded child
209 /// documents), needed for appropriate update of natbib labels.
210 mutable support::FileNameList bibfilesCache_;
212 // FIXME The caching mechanism could be improved. At present, we have a
213 // cache for each Buffer, that caches all the bibliography info for that
214 // Buffer. A more efficient solution would be to have a global cache per
215 // file, and then to construct the Buffer's bibinfo from that.
216 /// A cache for bibliography info
217 mutable BiblioInfo bibinfo_;
218 /// whether the bibinfo cache is valid
219 bool bibinfoCacheValid_;
220 /// Cache of timestamps of .bib files
221 map<FileName, time_t> bibfileStatus_;
223 mutable RefCache ref_cache_;
225 /// our Text that should be wrapped in an InsetText
228 /// This is here to force the test to be done whenever parent_buffer
230 Buffer const * parent() const {
231 if (!theBufferList().isLoaded(parent_buffer))
233 return parent_buffer;
236 void setParent(Buffer const * pb) { parent_buffer = pb; }
238 /// So we can force access via the accessors.
239 mutable Buffer const * parent_buffer;
243 /// Creates the per buffer temporary directory
244 static FileName createBufferTmpDir()
247 // We are in our own directory. Why bother to mangle name?
248 // In fact I wrote this code to circumvent a problematic behaviour
249 // (bug?) of EMX mkstemp().
250 FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
251 convert<string>(count++));
253 if (!tmpfl.createDirectory(0777)) {
254 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
255 _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
256 from_utf8(tmpfl.absFilename())));
262 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
263 : lyx_clean(true), bak_clean(true), unnamed(false),
264 read_only(readonly_), filename(file), file_fully_loaded(false),
265 toc_backend(&parent), macro_lock(false), timestamp_(0),
266 checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
269 temppath = createBufferTmpDir();
270 lyxvc.setBuffer(&parent);
272 wa_ = new frontend::WorkAreaManager;
276 Buffer::Buffer(string const & file, bool readonly)
277 : d(new Impl(*this, FileName(file), readonly)), gui_(0)
279 LYXERR(Debug::INFO, "Buffer::Buffer()");
281 d->inset = new InsetText(*this);
282 d->inset->setAutoBreakRows(true);
283 d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
289 LYXERR(Debug::INFO, "Buffer::~Buffer()");
290 // here the buffer should take care that it is
291 // saved properly, before it goes into the void.
293 // GuiView already destroyed
296 if (d->unnamed && d->filename.extension() == "internal") {
297 // No need to do additional cleanups for internal buffer.
302 // loop over children
303 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
304 Impl::BufferPositionMap::iterator end = d->children_positions.end();
305 for (; it != end; ++it) {
306 Buffer * child = const_cast<Buffer *>(it->first);
307 // The child buffer might have been closed already.
308 if (theBufferList().isLoaded(child))
309 theBufferList().releaseChild(this, child);
312 // clear references to children in macro tables
313 d->children_positions.clear();
314 d->position_to_children.clear();
316 if (!d->temppath.destroyDirectory()) {
317 Alert::warning(_("Could not remove temporary directory"),
318 bformat(_("Could not remove the temporary directory %1$s"),
319 from_utf8(d->temppath.absFilename())));
322 // Remove any previewed LaTeX snippets associated with this buffer.
323 thePreviews().removeLoader(*this);
329 void Buffer::changed() const
336 frontend::WorkAreaManager & Buffer::workAreaManager() const
338 LASSERT(d->wa_, /**/);
343 Text & Buffer::text() const
345 return d->inset->text();
349 Inset & Buffer::inset() const
355 BufferParams & Buffer::params()
361 BufferParams const & Buffer::params() const
367 ParagraphList & Buffer::paragraphs()
369 return text().paragraphs();
373 ParagraphList const & Buffer::paragraphs() const
375 return text().paragraphs();
379 LyXVC & Buffer::lyxvc()
385 LyXVC const & Buffer::lyxvc() const
391 string const Buffer::temppath() const
393 return d->temppath.absFilename();
397 TexRow & Buffer::texrow()
403 TexRow const & Buffer::texrow() const
409 TocBackend & Buffer::tocBackend() const
411 return d->toc_backend;
415 Undo & Buffer::undo()
421 string Buffer::latexName(bool const no_path) const
423 FileName latex_name = makeLatexName(d->filename);
424 return no_path ? latex_name.onlyFileName()
425 : latex_name.absFilename();
429 string Buffer::logName(LogType * type) const
431 string const filename = latexName(false);
433 if (filename.empty()) {
439 string const path = temppath();
441 FileName const fname(addName(temppath(),
442 onlyFilename(changeExtension(filename,
444 FileName const bname(
445 addName(path, onlyFilename(
446 changeExtension(filename,
447 formats.extension("literate") + ".out"))));
449 // If no Latex log or Build log is newer, show Build log
451 if (bname.exists() &&
452 (!fname.exists() || fname.lastModified() < bname.lastModified())) {
453 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
456 return bname.absFilename();
458 LYXERR(Debug::FILES, "Log name calculated as: " << fname);
461 return fname.absFilename();
465 void Buffer::setReadonly(bool const flag)
467 if (d->read_only != flag) {
474 void Buffer::setFileName(string const & newfile)
476 d->filename = makeAbsPath(newfile);
477 setReadonly(d->filename.isReadOnly());
482 int Buffer::readHeader(Lexer & lex)
484 int unknown_tokens = 0;
486 int begin_header_line = -1;
488 // Initialize parameters that may be/go lacking in header:
489 params().branchlist().clear();
490 params().preamble.erase();
491 params().options.erase();
492 params().master.erase();
493 params().float_placement.erase();
494 params().paperwidth.erase();
495 params().paperheight.erase();
496 params().leftmargin.erase();
497 params().rightmargin.erase();
498 params().topmargin.erase();
499 params().bottommargin.erase();
500 params().headheight.erase();
501 params().headsep.erase();
502 params().footskip.erase();
503 params().columnsep.erase();
504 params().fontsCJK.erase();
505 params().listings_params.clear();
506 params().clearLayoutModules();
507 params().clearRemovedModules();
508 params().pdfoptions().clear();
510 for (int i = 0; i < 4; ++i) {
511 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
512 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
515 ErrorList & errorList = d->errorLists["Parse"];
524 if (token == "\\end_header")
528 if (token == "\\begin_header") {
529 begin_header_line = line;
533 LYXERR(Debug::PARSER, "Handling document header token: `"
536 string unknown = params().readToken(lex, token, d->filename.onlyPath());
537 if (!unknown.empty()) {
538 if (unknown[0] != '\\' && token == "\\textclass") {
539 Alert::warning(_("Unknown document class"),
540 bformat(_("Using the default document class, because the "
541 "class %1$s is unknown."), from_utf8(unknown)));
544 docstring const s = bformat(_("Unknown token: "
548 errorList.push_back(ErrorItem(_("Document header error"),
553 if (begin_header_line) {
554 docstring const s = _("\\begin_header is missing");
555 errorList.push_back(ErrorItem(_("Document header error"),
559 params().makeDocumentClass();
561 return unknown_tokens;
566 // changed to be public and have one parameter
567 // Returns true if "\end_document" is not read (Asger)
568 bool Buffer::readDocument(Lexer & lex)
570 ErrorList & errorList = d->errorLists["Parse"];
573 if (!lex.checkFor("\\begin_document")) {
574 docstring const s = _("\\begin_document is missing");
575 errorList.push_back(ErrorItem(_("Document header error"),
579 // we are reading in a brand new document
580 LASSERT(paragraphs().empty(), /**/);
584 if (params().outputChanges) {
585 bool dvipost = LaTeXFeatures::isAvailable("dvipost");
586 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
587 LaTeXFeatures::isAvailable("xcolor");
589 if (!dvipost && !xcolorulem) {
590 Alert::warning(_("Changes not shown in LaTeX output"),
591 _("Changes will not be highlighted in LaTeX output, "
592 "because neither dvipost nor xcolor/ulem are installed.\n"
593 "Please install these packages or redefine "
594 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
595 } else if (!xcolorulem) {
596 Alert::warning(_("Changes not shown in LaTeX output"),
597 _("Changes will not be highlighted in LaTeX output "
598 "when using pdflatex, because xcolor and ulem are not installed.\n"
599 "Please install both packages or redefine "
600 "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
604 if (!params().master.empty()) {
605 FileName const master_file = makeAbsPath(params().master,
606 onlyPath(absFileName()));
607 if (isLyXFilename(master_file.absFilename())) {
609 checkAndLoadLyXFile(master_file, true);
611 // set master as master buffer, but only
612 // if we are a real child
613 if (master->isChild(this))
615 // if the master is not fully loaded
616 // it is probably just loading this
617 // child. No warning needed then.
618 else if (master->isFullyLoaded())
619 LYXERR0("The master '"
621 << "' assigned to this document '"
623 << "' does not include "
624 "this document. Ignoring the master assignment.");
630 bool const res = text().read(*this, lex, errorList, d->inset);
633 updateMacroInstances();
638 // needed to insert the selection
639 void Buffer::insertStringAsLines(ParagraphList & pars,
640 pit_type & pit, pos_type & pos,
641 Font const & fn, docstring const & str, bool autobreakrows)
645 // insert the string, don't insert doublespace
646 bool space_inserted = true;
647 for (docstring::const_iterator cit = str.begin();
648 cit != str.end(); ++cit) {
649 Paragraph & par = pars[pit];
651 if (autobreakrows && (!par.empty() || par.allowEmpty())) {
652 breakParagraph(params(), pars, pit, pos,
653 par.layout().isEnvironment());
656 space_inserted = true;
660 // do not insert consecutive spaces if !free_spacing
661 } else if ((*cit == ' ' || *cit == '\t') &&
662 space_inserted && !par.isFreeSpacing()) {
664 } else if (*cit == '\t') {
665 if (!par.isFreeSpacing()) {
666 // tabs are like spaces here
667 par.insertChar(pos, ' ', font, params().trackChanges);
669 space_inserted = true;
671 par.insertChar(pos, *cit, font, params().trackChanges);
673 space_inserted = true;
675 } else if (!isPrintable(*cit)) {
676 // Ignore unprintables
679 // just insert the character
680 par.insertChar(pos, *cit, font, params().trackChanges);
682 space_inserted = (*cit == ' ');
689 bool Buffer::readString(string const & s)
691 params().compressed = false;
693 // remove dummy empty par
694 paragraphs().clear();
698 FileName const name = FileName::tempName("Buffer_readString");
699 switch (readFile(lex, name, true)) {
703 // We need to call lyx2lyx, so write the input to a file
704 ofstream os(name.toFilesystemEncoding().c_str());
707 return readFile(name);
717 bool Buffer::readFile(FileName const & filename)
719 FileName fname(filename);
721 params().compressed = fname.isZippedFile();
723 // remove dummy empty par
724 paragraphs().clear();
727 if (readFile(lex, fname) != success)
734 bool Buffer::isFullyLoaded() const
736 return d->file_fully_loaded;
740 void Buffer::setFullyLoaded(bool value)
742 d->file_fully_loaded = value;
746 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
749 LASSERT(!filename.empty(), /**/);
751 // the first (non-comment) token _must_ be...
752 if (!lex.checkFor("\\lyxformat")) {
753 Alert::error(_("Document format failure"),
754 bformat(_("%1$s is not a readable LyX document."),
755 from_utf8(filename.absFilename())));
761 //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
762 // if present remove ".," from string.
763 size_t dot = tmp_format.find_first_of(".,");
764 //lyxerr << " dot found at " << dot << endl;
765 if (dot != string::npos)
766 tmp_format.erase(dot, 1);
767 int const file_format = convert<int>(tmp_format);
768 //lyxerr << "format: " << file_format << endl;
770 // save timestamp and checksum of the original disk file, making sure
771 // to not overwrite them with those of the file created in the tempdir
772 // when it has to be converted to the current format.
774 // Save the timestamp and checksum of disk file. If filename is an
775 // emergency file, save the timestamp and checksum of the original lyx file
776 // because isExternallyModified will check for this file. (BUG4193)
777 string diskfile = filename.absFilename();
778 if (suffixIs(diskfile, ".emergency"))
779 diskfile = diskfile.substr(0, diskfile.size() - 10);
780 saveCheckSum(FileName(diskfile));
783 if (file_format != LYX_FORMAT) {
786 // lyx2lyx would fail
789 FileName const tmpfile = FileName::tempName("Buffer_readFile");
790 if (tmpfile.empty()) {
791 Alert::error(_("Conversion failed"),
792 bformat(_("%1$s is from a different"
793 " version of LyX, but a temporary"
794 " file for converting it could"
796 from_utf8(filename.absFilename())));
799 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
800 if (lyx2lyx.empty()) {
801 Alert::error(_("Conversion script not found"),
802 bformat(_("%1$s is from a different"
803 " version of LyX, but the"
804 " conversion script lyx2lyx"
805 " could not be found."),
806 from_utf8(filename.absFilename())));
809 ostringstream command;
810 command << os::python()
811 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
812 << " -t " << convert<string>(LYX_FORMAT)
813 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
814 << ' ' << quoteName(filename.toFilesystemEncoding());
815 string const command_str = command.str();
817 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
819 cmd_ret const ret = runCommand(command_str);
820 if (ret.first != 0) {
821 Alert::error(_("Conversion script failed"),
822 bformat(_("%1$s is from a different version"
823 " of LyX, but the lyx2lyx script"
824 " failed to convert it."),
825 from_utf8(filename.absFilename())));
828 bool const ret = readFile(tmpfile);
829 // Do stuff with tmpfile name and buffer name here.
830 return ret ? success : failure;
835 if (readDocument(lex)) {
836 Alert::error(_("Document format failure"),
837 bformat(_("%1$s ended unexpectedly, which means"
838 " that it is probably corrupted."),
839 from_utf8(filename.absFilename())));
842 d->file_fully_loaded = true;
847 // Should probably be moved to somewhere else: BufferView? LyXView?
848 bool Buffer::save() const
850 // We don't need autosaves in the immediate future. (Asger)
851 resetAutosaveTimers();
853 string const encodedFilename = d->filename.toFilesystemEncoding();
856 bool madeBackup = false;
858 // make a backup if the file already exists
859 if (lyxrc.make_backup && fileName().exists()) {
860 backupName = FileName(absFileName() + '~');
861 if (!lyxrc.backupdir_path.empty()) {
862 string const mangledName =
863 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
864 backupName = FileName(addName(lyxrc.backupdir_path,
867 if (fileName().copyTo(backupName)) {
870 Alert::error(_("Backup failure"),
871 bformat(_("Cannot create backup file %1$s.\n"
872 "Please check whether the directory exists and is writeable."),
873 from_utf8(backupName.absFilename())));
874 //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
878 // ask if the disk file has been externally modified (use checksum method)
879 if (fileName().exists() && isExternallyModified(checksum_method)) {
880 docstring const file = makeDisplayPath(absFileName(), 20);
881 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
882 "you want to overwrite this file?"), file);
883 int const ret = Alert::prompt(_("Overwrite modified file?"),
884 text, 1, 1, _("&Overwrite"), _("&Cancel"));
889 if (writeFile(d->filename)) {
893 // Saving failed, so backup is not backup
895 backupName.moveTo(d->filename);
901 bool Buffer::writeFile(FileName const & fname) const
903 if (d->read_only && fname == d->filename)
908 docstring const str = bformat(_("Saving document %1$s..."),
909 makeDisplayPath(fname.absFilename()));
912 if (params().compressed) {
913 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
914 retval = ofs && write(ofs);
916 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
917 retval = ofs && write(ofs);
921 message(str + _(" could not write file!"));
925 removeAutosaveFile(d->filename.absFilename());
927 saveCheckSum(d->filename);
928 message(str + _(" done."));
934 bool Buffer::write(ostream & ofs) const
937 // Use the standard "C" locale for file output.
938 ofs.imbue(locale::classic());
941 // The top of the file should not be written by params().
943 // write out a comment in the top of the file
944 ofs << "#LyX " << lyx_version
945 << " created this file. For more info see http://www.lyx.org/\n"
946 << "\\lyxformat " << LYX_FORMAT << "\n"
947 << "\\begin_document\n";
949 /// For each author, set 'used' to true if there is a change
950 /// by this author in the document; otherwise set it to 'false'.
951 AuthorList::Authors::const_iterator a_it = params().authors().begin();
952 AuthorList::Authors::const_iterator a_end = params().authors().end();
953 for (; a_it != a_end; ++a_it)
954 a_it->second.setUsed(false);
956 ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
957 ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
958 for ( ; it != end; ++it)
959 it->checkAuthors(params().authors());
961 // now write out the buffer parameters.
962 ofs << "\\begin_header\n";
963 params().writeFile(ofs);
964 ofs << "\\end_header\n";
967 ofs << "\n\\begin_body\n";
968 text().write(*this, ofs);
969 ofs << "\n\\end_body\n";
971 // Write marker that shows file is complete
972 ofs << "\\end_document" << endl;
974 // Shouldn't really be needed....
977 // how to check if close went ok?
978 // Following is an attempt... (BE 20001011)
980 // good() returns false if any error occured, including some
982 // bad() returns true if something bad happened in the buffer,
983 // which should include file system full errors.
988 lyxerr << "File was not closed properly." << endl;
995 bool Buffer::makeLaTeXFile(FileName const & fname,
996 string const & original_path,
997 OutputParams const & runparams,
998 bool output_preamble, bool output_body) const
1000 string const encoding = runparams.encoding->iconvName();
1001 LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1004 try { ofs.reset(encoding); }
1005 catch (iconv_codecvt_facet_exception & e) {
1006 lyxerr << "Caught iconv exception: " << e.what() << endl;
1007 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1008 "verify that the support software for your encoding (%1$s) is "
1009 "properly installed"), from_ascii(encoding)));
1012 if (!openFileWrite(ofs, fname))
1015 //TexStream ts(ofs.rdbuf(), &texrow());
1016 ErrorList & errorList = d->errorLists["Export"];
1018 bool failed_export = false;
1021 writeLaTeXSource(ofs, original_path,
1022 runparams, output_preamble, output_body);
1024 catch (EncodingException & e) {
1025 odocstringstream ods;
1026 ods.put(e.failed_char);
1028 oss << "0x" << hex << e.failed_char << dec;
1029 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1030 " (code point %2$s)"),
1031 ods.str(), from_utf8(oss.str()));
1032 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1033 "representable in the chosen encoding.\n"
1034 "Changing the document encoding to utf8 could help."),
1035 e.par_id, e.pos, e.pos + 1));
1036 failed_export = true;
1038 catch (iconv_codecvt_facet_exception & e) {
1039 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1040 _(e.what()), -1, 0, 0));
1041 failed_export = true;
1043 catch (exception const & e) {
1044 errorList.push_back(ErrorItem(_("conversion failed"),
1045 _(e.what()), -1, 0, 0));
1046 failed_export = true;
1049 lyxerr << "Caught some really weird exception..." << endl;
1055 failed_export = true;
1056 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1060 return !failed_export;
1064 void Buffer::writeLaTeXSource(odocstream & os,
1065 string const & original_path,
1066 OutputParams const & runparams_in,
1067 bool const output_preamble, bool const output_body) const
1069 // The child documents, if any, shall be already loaded at this point.
1071 OutputParams runparams = runparams_in;
1073 // Classify the unicode characters appearing in math insets
1074 Encodings::initUnicodeMath(*this);
1076 // validate the buffer.
1077 LYXERR(Debug::LATEX, " Validating buffer...");
1078 LaTeXFeatures features(*this, params(), runparams);
1080 LYXERR(Debug::LATEX, " Buffer validation done.");
1082 // The starting paragraph of the coming rows is the
1083 // first paragraph of the document. (Asger)
1084 if (output_preamble && runparams.nice) {
1085 os << "%% LyX " << lyx_version << " created this file. "
1086 "For more info, see http://www.lyx.org/.\n"
1087 "%% Do not edit unless you really know what "
1089 d->texrow.newline();
1090 d->texrow.newline();
1092 LYXERR(Debug::INFO, "lyx document header finished");
1094 // Don't move this behind the parent_buffer=0 code below,
1095 // because then the macros will not get the right "redefinition"
1096 // flag as they don't see the parent macros which are output before.
1099 // fold macros if possible, still with parent buffer as the
1100 // macros will be put in the prefix anyway.
1101 updateMacroInstances();
1103 // There are a few differences between nice LaTeX and usual files:
1104 // usual is \batchmode and has a
1105 // special input@path to allow the including of figures
1106 // with either \input or \includegraphics (what figinsets do).
1107 // input@path is set when the actual parameter
1108 // original_path is set. This is done for usual tex-file, but not
1109 // for nice-latex-file. (Matthias 250696)
1110 // Note that input@path is only needed for something the user does
1111 // in the preamble, included .tex files or ERT, files included by
1112 // LyX work without it.
1113 if (output_preamble) {
1114 if (!runparams.nice) {
1115 // code for usual, NOT nice-latex-file
1116 os << "\\batchmode\n"; // changed
1117 // from \nonstopmode
1118 d->texrow.newline();
1120 if (!original_path.empty()) {
1122 // We don't know the encoding of inputpath
1123 docstring const inputpath = from_utf8(latex_path(original_path));
1124 os << "\\makeatletter\n"
1125 << "\\def\\input@path{{"
1126 << inputpath << "/}}\n"
1127 << "\\makeatother\n";
1128 d->texrow.newline();
1129 d->texrow.newline();
1130 d->texrow.newline();
1133 // get parent macros (if this buffer has a parent) which will be
1134 // written at the document begin further down.
1135 MacroSet parentMacros;
1136 listParentMacros(parentMacros, features);
1138 // Write the preamble
1139 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1141 runparams.use_japanese = features.isRequired("japanese");
1147 os << "\\begin{document}\n";
1148 d->texrow.newline();
1150 // output the parent macros
1151 MacroSet::iterator it = parentMacros.begin();
1152 MacroSet::iterator end = parentMacros.end();
1153 for (; it != end; ++it)
1154 (*it)->write(os, true);
1155 } // output_preamble
1157 d->texrow.start(paragraphs().begin()->id(), 0);
1159 LYXERR(Debug::INFO, "preamble finished, now the body.");
1161 // if we are doing a real file with body, even if this is the
1162 // child of some other buffer, let's cut the link here.
1163 // This happens for example if only a child document is printed.
1164 Buffer const * save_parent = 0;
1165 if (output_preamble) {
1166 save_parent = d->parent();
1171 latexParagraphs(*this, text(), os, d->texrow, runparams);
1173 // Restore the parenthood if needed
1174 if (output_preamble)
1175 d->setParent(save_parent);
1177 // add this just in case after all the paragraphs
1179 d->texrow.newline();
1181 if (output_preamble) {
1182 os << "\\end{document}\n";
1183 d->texrow.newline();
1184 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1186 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1188 runparams_in.encoding = runparams.encoding;
1190 // Just to be sure. (Asger)
1191 d->texrow.newline();
1193 LYXERR(Debug::INFO, "Finished making LaTeX file.");
1194 LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1198 bool Buffer::isLatex() const
1200 return params().documentClass().outputType() == LATEX;
1204 bool Buffer::isLiterate() const
1206 return params().documentClass().outputType() == LITERATE;
1210 bool Buffer::isDocBook() const
1212 return params().documentClass().outputType() == DOCBOOK;
1216 void Buffer::makeDocBookFile(FileName const & fname,
1217 OutputParams const & runparams,
1218 bool const body_only) const
1220 LYXERR(Debug::LATEX, "makeDocBookFile...");
1223 if (!openFileWrite(ofs, fname))
1226 writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1230 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1234 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1235 OutputParams const & runparams,
1236 bool const only_body) const
1238 LaTeXFeatures features(*this, params(), runparams);
1243 DocumentClass const & tclass = params().documentClass();
1244 string const top_element = tclass.latexname();
1247 if (runparams.flavor == OutputParams::XML)
1248 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1251 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1254 if (! tclass.class_header().empty())
1255 os << from_ascii(tclass.class_header());
1256 else if (runparams.flavor == OutputParams::XML)
1257 os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1258 << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1260 os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1262 docstring preamble = from_utf8(params().preamble);
1263 if (runparams.flavor != OutputParams::XML ) {
1264 preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1265 preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1266 preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1267 preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1270 string const name = runparams.nice
1271 ? changeExtension(absFileName(), ".sgml") : fname;
1272 preamble += features.getIncludedFiles(name);
1273 preamble += features.getLyXSGMLEntities();
1275 if (!preamble.empty()) {
1276 os << "\n [ " << preamble << " ]";
1281 string top = top_element;
1283 if (runparams.flavor == OutputParams::XML)
1284 top += params().language->code();
1286 top += params().language->code().substr(0, 2);
1289 if (!params().options.empty()) {
1291 top += params().options;
1294 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1295 << " file was created by LyX " << lyx_version
1296 << "\n See http://www.lyx.org/ for more information -->\n";
1298 params().documentClass().counters().reset();
1302 sgml::openTag(os, top);
1304 docbookParagraphs(paragraphs(), *this, os, runparams);
1305 sgml::closeTag(os, top_element);
1309 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1310 // Other flags: -wall -v0 -x
1311 int Buffer::runChktex()
1315 // get LaTeX-Filename
1316 FileName const path(temppath());
1317 string const name = addName(path.absFilename(), latexName());
1318 string const org_path = filePath();
1320 PathChanger p(path); // path to LaTeX file
1321 message(_("Running chktex..."));
1323 // Generate the LaTeX file if neccessary
1324 OutputParams runparams(¶ms().encoding());
1325 runparams.flavor = OutputParams::LATEX;
1326 runparams.nice = false;
1327 makeLaTeXFile(FileName(name), org_path, runparams);
1330 Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1331 int const res = chktex.run(terr); // run chktex
1334 Alert::error(_("chktex failure"),
1335 _("Could not run chktex successfully."));
1336 } else if (res > 0) {
1337 ErrorList & errlist = d->errorLists["ChkTeX"];
1339 bufferErrors(terr, errlist);
1350 void Buffer::validate(LaTeXFeatures & features) const
1352 params().validate(features);
1356 for_each(paragraphs().begin(), paragraphs().end(),
1357 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1359 if (lyxerr.debugging(Debug::LATEX)) {
1360 features.showStruct();
1365 void Buffer::getLabelList(vector<docstring> & list) const
1367 // If this is a child document, use the parent's list instead.
1368 Buffer const * const pbuf = d->parent();
1370 pbuf->getLabelList(list);
1375 Toc & toc = d->toc_backend.toc("label");
1376 TocIterator toc_it = toc.begin();
1377 TocIterator end = toc.end();
1378 for (; toc_it != end; ++toc_it) {
1379 if (toc_it->depth() == 0)
1380 list.push_back(toc_it->str());
1385 void Buffer::updateBibfilesCache(UpdateScope scope) const
1387 // If this is a child document, use the parent's cache instead.
1388 Buffer const * const pbuf = d->parent();
1389 if (pbuf && scope != UpdateChildOnly) {
1390 pbuf->updateBibfilesCache();
1394 d->bibfilesCache_.clear();
1395 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1396 if (it->lyxCode() == BIBTEX_CODE) {
1397 InsetBibtex const & inset =
1398 static_cast<InsetBibtex const &>(*it);
1399 support::FileNameList const bibfiles = inset.getBibFiles();
1400 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1403 } else if (it->lyxCode() == INCLUDE_CODE) {
1404 InsetInclude & inset =
1405 static_cast<InsetInclude &>(*it);
1406 inset.updateBibfilesCache();
1407 support::FileNameList const & bibfiles =
1408 inset.getBibfilesCache();
1409 d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1414 // the bibinfo cache is now invalid
1415 d->bibinfoCacheValid_ = false;
1419 void Buffer::invalidateBibinfoCache()
1421 d->bibinfoCacheValid_ = false;
1425 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1427 // If this is a child document, use the parent's cache instead.
1428 Buffer const * const pbuf = d->parent();
1429 if (pbuf && scope != UpdateChildOnly)
1430 return pbuf->getBibfilesCache();
1432 // We update the cache when first used instead of at loading time.
1433 if (d->bibfilesCache_.empty())
1434 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1436 return d->bibfilesCache_;
1440 BiblioInfo const & Buffer::masterBibInfo() const
1442 // if this is a child document and the parent is already loaded
1443 // use the parent's list instead [ale990412]
1444 Buffer const * const tmp = masterBuffer();
1447 return tmp->masterBibInfo();
1448 return localBibInfo();
1452 BiblioInfo const & Buffer::localBibInfo() const
1454 if (d->bibinfoCacheValid_) {
1455 support::FileNameList const & bibfilesCache = getBibfilesCache();
1456 // compare the cached timestamps with the actual ones.
1457 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1458 support::FileNameList::const_iterator en = bibfilesCache.end();
1459 for (; ei != en; ++ ei) {
1460 time_t lastw = ei->lastModified();
1461 if (lastw != d->bibfileStatus_[*ei]) {
1462 d->bibinfoCacheValid_ = false;
1463 d->bibfileStatus_[*ei] = lastw;
1469 if (!d->bibinfoCacheValid_) {
1470 d->bibinfo_.clear();
1471 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1472 it->fillWithBibKeys(d->bibinfo_, it);
1473 d->bibinfoCacheValid_ = true;
1479 bool Buffer::isDepClean(string const & name) const
1481 DepClean::const_iterator const it = d->dep_clean.find(name);
1482 if (it == d->dep_clean.end())
1488 void Buffer::markDepClean(string const & name)
1490 d->dep_clean[name] = true;
1494 bool Buffer::dispatch(string const & command, bool * result)
1496 return dispatch(lyxaction.lookupFunc(command), result);
1500 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1502 bool dispatched = true;
1504 switch (func.action) {
1505 case LFUN_BUFFER_EXPORT: {
1506 bool const tmp = doExport(to_utf8(func.argument()), false);
1512 case LFUN_BRANCH_ACTIVATE:
1513 case LFUN_BRANCH_DEACTIVATE: {
1514 BranchList & branchList = params().branchlist();
1515 docstring const branchName = func.argument();
1516 // the case without a branch name is handled elsewhere
1517 if (branchName.empty()) {
1521 Branch * branch = branchList.find(branchName);
1523 LYXERR0("Branch " << branchName << " does not exist.");
1525 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1537 void Buffer::changeLanguage(Language const * from, Language const * to)
1539 LASSERT(from, /**/);
1542 for_each(par_iterator_begin(),
1544 bind(&Paragraph::changeLanguage, _1, params(), from, to));
1548 bool Buffer::isMultiLingual() const
1550 ParConstIterator end = par_iterator_end();
1551 for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1552 if (it->isMultiLingual(params()))
1559 DocIterator Buffer::getParFromID(int const id) const
1561 Buffer * buf = const_cast<Buffer *>(this);
1563 // John says this is called with id == -1 from undo
1564 lyxerr << "getParFromID(), id: " << id << endl;
1565 return doc_iterator_end(buf);
1568 for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
1569 if (it.paragraph().id() == id)
1572 return doc_iterator_end(buf);
1576 bool Buffer::hasParWithID(int const id) const
1578 return !getParFromID(id).atEnd();
1582 ParIterator Buffer::par_iterator_begin()
1584 return ParIterator(doc_iterator_begin(this));
1588 ParIterator Buffer::par_iterator_end()
1590 return ParIterator(doc_iterator_end(this));
1594 ParConstIterator Buffer::par_iterator_begin() const
1596 return ParConstIterator(doc_iterator_begin(this));
1600 ParConstIterator Buffer::par_iterator_end() const
1602 return ParConstIterator(doc_iterator_end(this));
1606 Language const * Buffer::language() const
1608 return params().language;
1612 docstring const Buffer::B_(string const & l10n) const
1614 return params().B_(l10n);
1618 bool Buffer::isClean() const
1620 return d->lyx_clean;
1624 bool Buffer::isBakClean() const
1626 return d->bak_clean;
1630 bool Buffer::isExternallyModified(CheckMethod method) const
1632 LASSERT(d->filename.exists(), /**/);
1633 // if method == timestamp, check timestamp before checksum
1634 return (method == checksum_method
1635 || d->timestamp_ != d->filename.lastModified())
1636 && d->checksum_ != d->filename.checksum();
1640 void Buffer::saveCheckSum(FileName const & file) const
1642 if (file.exists()) {
1643 d->timestamp_ = file.lastModified();
1644 d->checksum_ = file.checksum();
1646 // in the case of save to a new file.
1653 void Buffer::markClean() const
1655 if (!d->lyx_clean) {
1656 d->lyx_clean = true;
1659 // if the .lyx file has been saved, we don't need an
1661 d->bak_clean = true;
1665 void Buffer::markBakClean() const
1667 d->bak_clean = true;
1671 void Buffer::setUnnamed(bool flag)
1677 bool Buffer::isUnnamed() const
1683 // FIXME: this function should be moved to buffer_pimpl.C
1684 void Buffer::markDirty()
1687 d->lyx_clean = false;
1690 d->bak_clean = false;
1692 DepClean::iterator it = d->dep_clean.begin();
1693 DepClean::const_iterator const end = d->dep_clean.end();
1695 for (; it != end; ++it)
1700 FileName Buffer::fileName() const
1706 string Buffer::absFileName() const
1708 return d->filename.absFilename();
1712 string Buffer::filePath() const
1714 return d->filename.onlyPath().absFilename() + "/";
1718 bool Buffer::isReadonly() const
1720 return d->read_only;
1724 void Buffer::setParent(Buffer const * buffer)
1726 // Avoids recursive include.
1727 d->setParent(buffer == this ? 0 : buffer);
1732 Buffer const * Buffer::parent() const
1738 void Buffer::collectRelatives(BufferSet & bufs) const
1742 parent()->collectRelatives(bufs);
1744 // loop over children
1745 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1746 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1747 for (; it != end; ++it)
1748 bufs.insert(const_cast<Buffer *>(it->first));
1752 std::vector<Buffer const *> Buffer::allRelatives() const
1755 collectRelatives(bufs);
1756 BufferSet::iterator it = bufs.begin();
1757 std::vector<Buffer const *> ret;
1758 for (; it != bufs.end(); ++it)
1764 Buffer const * Buffer::masterBuffer() const
1766 Buffer const * const pbuf = d->parent();
1770 return pbuf->masterBuffer();
1774 bool Buffer::isChild(Buffer * child) const
1776 return d->children_positions.find(child) != d->children_positions.end();
1780 DocIterator Buffer::firstChildPosition(Buffer const * child)
1782 Impl::BufferPositionMap::iterator it;
1783 it = d->children_positions.find(child);
1784 if (it == d->children_positions.end())
1785 return DocIterator(this);
1790 std::vector<Buffer *> Buffer::getChildren() const
1792 std::vector<Buffer *> clist;
1793 // loop over children
1794 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1795 Impl::BufferPositionMap::iterator end = d->children_positions.end();
1796 for (; it != end; ++it) {
1797 Buffer * child = const_cast<Buffer *>(it->first);
1798 clist.push_back(child);
1799 // there might be grandchildren
1800 std::vector<Buffer *> glist = child->getChildren();
1801 for (vector<Buffer *>::const_iterator git = glist.begin();
1802 git != glist.end(); ++git)
1803 clist.push_back(*git);
1809 template<typename M>
1810 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1815 typename M::iterator it = m.lower_bound(x);
1816 if (it == m.begin())
1824 MacroData const * Buffer::getBufferMacro(docstring const & name,
1825 DocIterator const & pos) const
1827 LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1829 // if paragraphs have no macro context set, pos will be empty
1833 // we haven't found anything yet
1834 DocIterator bestPos = par_iterator_begin();
1835 MacroData const * bestData = 0;
1837 // find macro definitions for name
1838 Impl::NamePositionScopeMacroMap::iterator nameIt
1839 = d->macros.find(name);
1840 if (nameIt != d->macros.end()) {
1841 // find last definition in front of pos or at pos itself
1842 Impl::PositionScopeMacroMap::const_iterator it
1843 = greatest_below(nameIt->second, pos);
1844 if (it != nameIt->second.end()) {
1846 // scope ends behind pos?
1847 if (pos < it->second.first) {
1848 // Looks good, remember this. If there
1849 // is no external macro behind this,
1850 // we found the right one already.
1851 bestPos = it->first;
1852 bestData = &it->second.second;
1856 // try previous macro if there is one
1857 if (it == nameIt->second.begin())
1864 // find macros in included files
1865 Impl::PositionScopeBufferMap::const_iterator it
1866 = greatest_below(d->position_to_children, pos);
1867 if (it == d->position_to_children.end())
1868 // no children before
1872 // do we know something better (i.e. later) already?
1873 if (it->first < bestPos )
1876 // scope ends behind pos?
1877 if (pos < it->second.first) {
1878 // look for macro in external file
1879 d->macro_lock = true;
1880 MacroData const * data
1881 = it->second.second->getMacro(name, false);
1882 d->macro_lock = false;
1884 bestPos = it->first;
1890 // try previous file if there is one
1891 if (it == d->position_to_children.begin())
1896 // return the best macro we have found
1901 MacroData const * Buffer::getMacro(docstring const & name,
1902 DocIterator const & pos, bool global) const
1907 // query buffer macros
1908 MacroData const * data = getBufferMacro(name, pos);
1912 // If there is a master buffer, query that
1913 Buffer const * const pbuf = d->parent();
1915 d->macro_lock = true;
1916 MacroData const * macro = pbuf->getMacro(
1917 name, *this, false);
1918 d->macro_lock = false;
1924 data = MacroTable::globalMacros().get(name);
1933 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1935 // set scope end behind the last paragraph
1936 DocIterator scope = par_iterator_begin();
1937 scope.pit() = scope.lastpit() + 1;
1939 return getMacro(name, scope, global);
1943 MacroData const * Buffer::getMacro(docstring const & name,
1944 Buffer const & child, bool global) const
1946 // look where the child buffer is included first
1947 Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1948 if (it == d->children_positions.end())
1951 // check for macros at the inclusion position
1952 return getMacro(name, it->second, global);
1956 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1958 pit_type lastpit = it.lastpit();
1960 // look for macros in each paragraph
1961 while (it.pit() <= lastpit) {
1962 Paragraph & par = it.paragraph();
1964 // iterate over the insets of the current paragraph
1965 InsetList const & insets = par.insetList();
1966 InsetList::const_iterator iit = insets.begin();
1967 InsetList::const_iterator end = insets.end();
1968 for (; iit != end; ++iit) {
1969 it.pos() = iit->pos;
1971 // is it a nested text inset?
1972 if (iit->inset->asInsetText()) {
1973 // Inset needs its own scope?
1974 InsetText const * itext = iit->inset->asInsetText();
1975 bool newScope = itext->isMacroScope();
1977 // scope which ends just behind the inset
1978 DocIterator insetScope = it;
1981 // collect macros in inset
1982 it.push_back(CursorSlice(*iit->inset));
1983 updateMacros(it, newScope ? insetScope : scope);
1988 // is it an external file?
1989 if (iit->inset->lyxCode() == INCLUDE_CODE) {
1990 // get buffer of external file
1991 InsetInclude const & inset =
1992 static_cast<InsetInclude const &>(*iit->inset);
1993 d->macro_lock = true;
1994 Buffer * child = inset.getChildBuffer();
1995 d->macro_lock = false;
1999 // register its position, but only when it is
2000 // included first in the buffer
2001 if (d->children_positions.find(child) ==
2002 d->children_positions.end())
2003 d->children_positions[child] = it;
2005 // register child with its scope
2006 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2010 if (iit->inset->lyxCode() != MATHMACRO_CODE)
2014 MathMacroTemplate & macroTemplate =
2015 static_cast<MathMacroTemplate &>(*iit->inset);
2016 MacroContext mc(*this, it);
2017 macroTemplate.updateToContext(mc);
2020 bool valid = macroTemplate.validMacro();
2021 // FIXME: Should be fixNameAndCheckIfValid() in fact,
2022 // then the BufferView's cursor will be invalid in
2023 // some cases which leads to crashes.
2028 d->macros[macroTemplate.name()][it] =
2029 Impl::ScopeMacro(scope, MacroData(*this, it));
2039 void Buffer::updateMacros() const
2044 LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2046 // start with empty table
2048 d->children_positions.clear();
2049 d->position_to_children.clear();
2051 // Iterate over buffer, starting with first paragraph
2052 // The scope must be bigger than any lookup DocIterator
2053 // later. For the global lookup, lastpit+1 is used, hence
2054 // we use lastpit+2 here.
2055 DocIterator it = par_iterator_begin();
2056 DocIterator outerScope = it;
2057 outerScope.pit() = outerScope.lastpit() + 2;
2058 updateMacros(it, outerScope);
2062 void Buffer::updateMacroInstances() const
2064 LYXERR(Debug::MACROS, "updateMacroInstances for "
2065 << d->filename.onlyFileName());
2066 DocIterator it = doc_iterator_begin(this);
2067 DocIterator end = doc_iterator_end(this);
2068 for (; it != end; it.forwardPos()) {
2069 // look for MathData cells in InsetMathNest insets
2070 Inset * inset = it.nextInset();
2074 InsetMath * minset = inset->asInsetMath();
2078 // update macro in all cells of the InsetMathNest
2079 DocIterator::idx_type n = minset->nargs();
2080 MacroContext mc = MacroContext(*this, it);
2081 for (DocIterator::idx_type i = 0; i < n; ++i) {
2082 MathData & data = minset->cell(i);
2083 data.updateMacros(0, mc);
2089 void Buffer::listMacroNames(MacroNameSet & macros) const
2094 d->macro_lock = true;
2096 // loop over macro names
2097 Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2098 Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2099 for (; nameIt != nameEnd; ++nameIt)
2100 macros.insert(nameIt->first);
2102 // loop over children
2103 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2104 Impl::BufferPositionMap::iterator end = d->children_positions.end();
2105 for (; it != end; ++it)
2106 it->first->listMacroNames(macros);
2109 Buffer const * const pbuf = d->parent();
2111 pbuf->listMacroNames(macros);
2113 d->macro_lock = false;
2117 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2119 Buffer const * const pbuf = d->parent();
2124 pbuf->listMacroNames(names);
2127 MacroNameSet::iterator it = names.begin();
2128 MacroNameSet::iterator end = names.end();
2129 for (; it != end; ++it) {
2131 MacroData const * data =
2132 pbuf->getMacro(*it, *this, false);
2134 macros.insert(data);
2136 // we cannot access the original MathMacroTemplate anymore
2137 // here to calls validate method. So we do its work here manually.
2138 // FIXME: somehow make the template accessible here.
2139 if (data->optionals() > 0)
2140 features.require("xargs");
2146 Buffer::References & Buffer::references(docstring const & label)
2149 return const_cast<Buffer *>(masterBuffer())->references(label);
2151 RefCache::iterator it = d->ref_cache_.find(label);
2152 if (it != d->ref_cache_.end())
2153 return it->second.second;
2155 static InsetLabel const * dummy_il = 0;
2156 static References const dummy_refs;
2157 it = d->ref_cache_.insert(
2158 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2159 return it->second.second;
2163 Buffer::References const & Buffer::references(docstring const & label) const
2165 return const_cast<Buffer *>(this)->references(label);
2169 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2171 masterBuffer()->d->ref_cache_[label].first = il;
2175 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2177 return masterBuffer()->d->ref_cache_[label].first;
2181 void Buffer::clearReferenceCache() const
2184 d->ref_cache_.clear();
2188 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2191 //FIXME: This does not work for child documents yet.
2192 LASSERT(code == CITE_CODE, /**/);
2193 // Check if the label 'from' appears more than once
2194 vector<docstring> labels;
2196 BiblioInfo const & keys = masterBibInfo();
2197 BiblioInfo::const_iterator bit = keys.begin();
2198 BiblioInfo::const_iterator bend = keys.end();
2200 for (; bit != bend; ++bit)
2202 labels.push_back(bit->first);
2205 if (count(labels.begin(), labels.end(), from) > 1)
2208 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2209 if (it->lyxCode() == code) {
2210 InsetCommand & inset = static_cast<InsetCommand &>(*it);
2211 docstring const oldValue = inset.getParam(paramName);
2212 if (oldValue == from)
2213 inset.setParam(paramName, to);
2219 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2220 pit_type par_end, bool full_source) const
2222 OutputParams runparams(¶ms().encoding());
2223 runparams.nice = true;
2224 runparams.flavor = OutputParams::LATEX;
2225 runparams.linelen = lyxrc.plaintext_linelen;
2226 // No side effect of file copying and image conversion
2227 runparams.dryrun = true;
2231 os << "% " << _("Preview source code") << "\n\n";
2232 d->texrow.newline();
2233 d->texrow.newline();
2235 writeDocBookSource(os, absFileName(), runparams, false);
2237 // latex or literate
2238 writeLaTeXSource(os, string(), runparams, true, true);
2240 runparams.par_begin = par_begin;
2241 runparams.par_end = par_end;
2242 if (par_begin + 1 == par_end) {
2244 << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2248 << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2249 convert<docstring>(par_begin),
2250 convert<docstring>(par_end - 1))
2253 d->texrow.newline();
2254 d->texrow.newline();
2255 // output paragraphs
2257 docbookParagraphs(paragraphs(), *this, os, runparams);
2259 // latex or literate
2260 latexParagraphs(*this, text(), os, d->texrow, runparams);
2265 ErrorList & Buffer::errorList(string const & type) const
2267 static ErrorList emptyErrorList;
2268 map<string, ErrorList>::iterator I = d->errorLists.find(type);
2269 if (I == d->errorLists.end())
2270 return emptyErrorList;
2276 void Buffer::updateTocItem(std::string const & type,
2277 DocIterator const & dit) const
2280 gui_->updateTocItem(type, dit);
2284 void Buffer::structureChanged() const
2287 gui_->structureChanged();
2291 void Buffer::errors(string const & err) const
2298 void Buffer::message(docstring const & msg) const
2305 void Buffer::setBusy(bool on) const
2312 void Buffer::setReadOnly(bool on) const
2315 d->wa_->setReadOnly(on);
2319 void Buffer::updateTitles() const
2322 d->wa_->updateTitles();
2326 void Buffer::resetAutosaveTimers() const
2329 gui_->resetAutosaveTimers();
2333 bool Buffer::hasGuiDelegate() const
2339 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2348 class AutoSaveBuffer : public ForkedProcess {
2351 AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2352 : buffer_(buffer), fname_(fname) {}
2354 virtual boost::shared_ptr<ForkedProcess> clone() const
2356 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2361 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2362 from_utf8(fname_.absFilename())));
2363 return run(DontWait);
2367 virtual int generateChild();
2369 Buffer const & buffer_;
2374 int AutoSaveBuffer::generateChild()
2376 // tmp_ret will be located (usually) in /tmp
2377 // will that be a problem?
2378 // Note that this calls ForkedCalls::fork(), so it's
2379 // ok cross-platform.
2380 pid_t const pid = fork();
2381 // If you want to debug the autosave
2382 // you should set pid to -1, and comment out the fork.
2383 if (pid != 0 && pid != -1)
2386 // pid = -1 signifies that lyx was unable
2387 // to fork. But we will do the save
2389 bool failed = false;
2390 FileName const tmp_ret = FileName::tempName("lyxauto");
2391 if (!tmp_ret.empty()) {
2392 buffer_.writeFile(tmp_ret);
2393 // assume successful write of tmp_ret
2394 if (!tmp_ret.moveTo(fname_))
2400 // failed to write/rename tmp_ret so try writing direct
2401 if (!buffer_.writeFile(fname_)) {
2402 // It is dangerous to do this in the child,
2403 // but safe in the parent, so...
2404 if (pid == -1) // emit message signal.
2405 buffer_.message(_("Autosave failed!"));
2409 if (pid == 0) // we are the child so...
2418 // Perfect target for a thread...
2419 void Buffer::autoSave() const
2421 if (isBakClean() || isReadonly()) {
2422 // We don't save now, but we'll try again later
2423 resetAutosaveTimers();
2427 // emit message signal.
2428 message(_("Autosaving current document..."));
2430 // create autosave filename
2431 string fname = filePath();
2433 fname += d->filename.onlyFileName();
2436 AutoSaveBuffer autosave(*this, FileName(fname));
2440 resetAutosaveTimers();
2444 string Buffer::bufferFormat() const
2450 if (params().encoding().package() == Encoding::japanese)
2456 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2457 string & result_file) const
2459 string backend_format;
2460 OutputParams runparams(¶ms().encoding());
2461 runparams.flavor = OutputParams::LATEX;
2462 runparams.linelen = lyxrc.plaintext_linelen;
2463 vector<string> backs = backends();
2464 if (find(backs.begin(), backs.end(), format) == backs.end()) {
2465 // Get shortest path to format
2466 Graph::EdgePath path;
2467 for (vector<string>::const_iterator it = backs.begin();
2468 it != backs.end(); ++it) {
2469 Graph::EdgePath p = theConverters().getPath(*it, format);
2470 if (!p.empty() && (path.empty() || p.size() < path.size())) {
2471 backend_format = *it;
2476 runparams.flavor = theConverters().getFlavor(path);
2478 Alert::error(_("Couldn't export file"),
2479 bformat(_("No information for exporting the format %1$s."),
2480 formats.prettyName(format)));
2484 backend_format = format;
2485 // FIXME: Don't hardcode format names here, but use a flag
2486 if (backend_format == "pdflatex")
2487 runparams.flavor = OutputParams::PDFLATEX;
2490 string filename = latexName(false);
2491 filename = addName(temppath(), filename);
2492 filename = changeExtension(filename,
2493 formats.extension(backend_format));
2496 updateMacroInstances();
2498 // Plain text backend
2499 if (backend_format == "text")
2500 writePlaintextFile(*this, FileName(filename), runparams);
2502 else if (backend_format == "lyx")
2503 writeFile(FileName(filename));
2505 else if (isDocBook()) {
2506 runparams.nice = !put_in_tempdir;
2507 makeDocBookFile(FileName(filename), runparams);
2510 else if (backend_format == format) {
2511 runparams.nice = true;
2512 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2514 } else if (!lyxrc.tex_allows_spaces
2515 && contains(filePath(), ' ')) {
2516 Alert::error(_("File name error"),
2517 _("The directory path to the document cannot contain spaces."));
2520 runparams.nice = false;
2521 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2525 string const error_type = (format == "program")
2526 ? "Build" : bufferFormat();
2527 ErrorList & error_list = d->errorLists[error_type];
2528 string const ext = formats.extension(format);
2529 FileName const tmp_result_file(changeExtension(filename, ext));
2530 bool const success = theConverters().convert(this, FileName(filename),
2531 tmp_result_file, FileName(absFileName()), backend_format, format,
2533 // Emit the signal to show the error list.
2534 if (format != backend_format)
2539 if (put_in_tempdir) {
2540 result_file = tmp_result_file.absFilename();
2544 result_file = changeExtension(absFileName(), ext);
2545 // We need to copy referenced files (e. g. included graphics
2546 // if format == "dvi") to the result dir.
2547 vector<ExportedFile> const files =
2548 runparams.exportdata->externalFiles(format);
2549 string const dest = onlyPath(result_file);
2550 CopyStatus status = SUCCESS;
2551 for (vector<ExportedFile>::const_iterator it = files.begin();
2552 it != files.end() && status != CANCEL; ++it) {
2553 string const fmt = formats.getFormatFromFile(it->sourceName);
2554 status = copyFile(fmt, it->sourceName,
2555 makeAbsPath(it->exportName, dest),
2556 it->exportName, status == FORCE);
2558 if (status == CANCEL) {
2559 message(_("Document export cancelled."));
2560 } else if (tmp_result_file.exists()) {
2561 // Finally copy the main file
2562 status = copyFile(format, tmp_result_file,
2563 FileName(result_file), result_file,
2565 message(bformat(_("Document exported as %1$s "
2567 formats.prettyName(format),
2568 makeDisplayPath(result_file)));
2570 // This must be a dummy converter like fax (bug 1888)
2571 message(bformat(_("Document exported as %1$s"),
2572 formats.prettyName(format)));
2579 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2582 return doExport(format, put_in_tempdir, result_file);
2586 bool Buffer::preview(string const & format) const
2589 if (!doExport(format, true, result_file))
2591 return formats.view(*this, FileName(result_file), format);
2595 bool Buffer::isExportable(string const & format) const
2597 vector<string> backs = backends();
2598 for (vector<string>::const_iterator it = backs.begin();
2599 it != backs.end(); ++it)
2600 if (theConverters().isReachable(*it, format))
2606 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2608 vector<string> backs = backends();
2609 vector<Format const *> result =
2610 theConverters().getReachable(backs[0], only_viewable, true);
2611 for (vector<string>::const_iterator it = backs.begin() + 1;
2612 it != backs.end(); ++it) {
2613 vector<Format const *> r =
2614 theConverters().getReachable(*it, only_viewable, false);
2615 result.insert(result.end(), r.begin(), r.end());
2621 vector<string> Buffer::backends() const
2624 if (params().baseClass()->isTeXClassAvailable()) {
2625 v.push_back(bufferFormat());
2626 // FIXME: Don't hardcode format names here, but use a flag
2627 if (v.back() == "latex")
2628 v.push_back("pdflatex");
2630 v.push_back("text");
2636 bool Buffer::readFileHelper(FileName const & s)
2638 // File information about normal file
2640 docstring const file = makeDisplayPath(s.absFilename(), 50);
2641 docstring text = bformat(_("The specified document\n%1$s"
2642 "\ncould not be read."), file);
2643 Alert::error(_("Could not read document"), text);
2647 // Check if emergency save file exists and is newer.
2648 FileName const e(s.absFilename() + ".emergency");
2650 if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2651 docstring const file = makeDisplayPath(s.absFilename(), 20);
2652 docstring const text =
2653 bformat(_("An emergency save of the document "
2655 "Recover emergency save?"), file);
2656 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2657 _("&Recover"), _("&Load Original"),
2661 // the file is not saved if we load the emergency file.
2671 // Now check if autosave file is newer.
2672 FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2674 if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2675 docstring const file = makeDisplayPath(s.absFilename(), 20);
2676 docstring const text =
2677 bformat(_("The backup of the document "
2678 "%1$s is newer.\n\nLoad the "
2679 "backup instead?"), file);
2680 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2681 _("&Load backup"), _("Load &original"),
2685 // the file is not saved if we load the autosave file.
2689 // Here we delete the autosave
2700 bool Buffer::loadLyXFile(FileName const & s)
2702 if (s.isReadableFile()) {
2703 if (readFileHelper(s)) {
2704 lyxvc().file_found_hook(s);
2705 if (!s.isWritable())
2710 docstring const file = makeDisplayPath(s.absFilename(), 20);
2711 // Here we probably should run
2712 if (LyXVC::file_not_found_hook(s)) {
2713 docstring const text =
2714 bformat(_("Do you want to retrieve the document"
2715 " %1$s from version control?"), file);
2716 int const ret = Alert::prompt(_("Retrieve from version control?"),
2717 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2720 // How can we know _how_ to do the checkout?
2721 // With the current VC support it has to be,
2722 // a RCS file since CVS do not have special ,v files.
2724 return loadLyXFile(s);
2732 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2734 TeXErrors::Errors::const_iterator cit = terr.begin();
2735 TeXErrors::Errors::const_iterator end = terr.end();
2737 for (; cit != end; ++cit) {
2740 int errorRow = cit->error_in_line;
2741 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2747 found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2748 } while (found && id_start == id_end && pos_start == pos_end);
2750 errorList.push_back(ErrorItem(cit->error_desc,
2751 cit->error_text, id_start, pos_start, pos_end));
2756 void Buffer::setBuffersForInsets() const
2758 inset().setBuffer(const_cast<Buffer &>(*this));
2762 void Buffer::updateLabels(UpdateScope scope) const
2764 // Use the master text class also for child documents
2765 Buffer const * const master = masterBuffer();
2766 DocumentClass const & textclass = master->params().documentClass();
2768 // keep the buffers to be children in this set. If the call from the
2769 // master comes back we can see which of them were actually seen (i.e.
2770 // via an InsetInclude). The remaining ones in the set need still be updated.
2771 static std::set<Buffer const *> bufToUpdate;
2772 if (scope == UpdateMaster) {
2773 // If this is a child document start with the master
2774 if (master != this) {
2775 bufToUpdate.insert(this);
2776 master->updateLabels();
2777 // Do this here in case the master has no gui associated with it. Then,
2778 // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
2782 // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2783 if (bufToUpdate.find(this) == bufToUpdate.end())
2787 // start over the counters in the master
2788 textclass.counters().reset();
2791 // update will be done below for this buffer
2792 bufToUpdate.erase(this);
2794 // update all caches
2795 clearReferenceCache();
2798 Buffer & cbuf = const_cast<Buffer &>(*this);
2800 LASSERT(!text().paragraphs().empty(), /**/);
2803 ParIterator parit = cbuf.par_iterator_begin();
2804 updateLabels(parit);
2807 // TocBackend update will be done later.
2810 cbuf.tocBackend().update();
2811 if (scope == UpdateMaster)
2812 cbuf.structureChanged();
2816 static depth_type getDepth(DocIterator const & it)
2818 depth_type depth = 0;
2819 for (size_t i = 0 ; i < it.depth() ; ++i)
2820 if (!it[i].inset().inMathed())
2821 depth += it[i].paragraph().getDepth() + 1;
2822 // remove 1 since the outer inset does not count
2826 static depth_type getItemDepth(ParIterator const & it)
2828 Paragraph const & par = *it;
2829 LabelType const labeltype = par.layout().labeltype;
2831 if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2834 // this will hold the lowest depth encountered up to now.
2835 depth_type min_depth = getDepth(it);
2836 ParIterator prev_it = it;
2839 --prev_it.top().pit();
2841 // start of nested inset: go to outer par
2843 if (prev_it.empty()) {
2844 // start of document: nothing to do
2849 // We search for the first paragraph with same label
2850 // that is not more deeply nested.
2851 Paragraph & prev_par = *prev_it;
2852 depth_type const prev_depth = getDepth(prev_it);
2853 if (labeltype == prev_par.layout().labeltype) {
2854 if (prev_depth < min_depth)
2855 return prev_par.itemdepth + 1;
2856 if (prev_depth == min_depth)
2857 return prev_par.itemdepth;
2859 min_depth = min(min_depth, prev_depth);
2860 // small optimization: if we are at depth 0, we won't
2861 // find anything else
2862 if (prev_depth == 0)
2868 static bool needEnumCounterReset(ParIterator const & it)
2870 Paragraph const & par = *it;
2871 LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2872 depth_type const cur_depth = par.getDepth();
2873 ParIterator prev_it = it;
2874 while (prev_it.pit()) {
2875 --prev_it.top().pit();
2876 Paragraph const & prev_par = *prev_it;
2877 if (prev_par.getDepth() <= cur_depth)
2878 return prev_par.layout().labeltype != LABEL_ENUMERATE;
2880 // start of nested inset: reset
2885 // set the label of a paragraph. This includes the counters.
2886 static void setLabel(Buffer const & buf, ParIterator & it)
2888 BufferParams const & bp = buf.masterBuffer()->params();
2889 DocumentClass const & textclass = bp.documentClass();
2890 Paragraph & par = it.paragraph();
2891 Layout const & layout = par.layout();
2892 Counters & counters = textclass.counters();
2894 if (par.params().startOfAppendix()) {
2895 // FIXME: only the counter corresponding to toplevel
2896 // sectionning should be reset
2898 counters.appendix(true);
2900 par.params().appendix(counters.appendix());
2902 // Compute the item depth of the paragraph
2903 par.itemdepth = getItemDepth(it);
2905 if (layout.margintype == MARGIN_MANUAL) {
2906 if (par.params().labelWidthString().empty())
2907 par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2909 par.params().labelWidthString(docstring());
2912 switch(layout.labeltype) {
2914 if (layout.toclevel <= bp.secnumdepth
2915 && (layout.latextype != LATEX_ENVIRONMENT
2916 || isFirstInSequence(it.pit(), it.plist()))) {
2917 counters.step(layout.counter);
2918 par.params().labelString(
2919 par.expandLabel(layout, bp));
2921 par.params().labelString(docstring());
2924 case LABEL_ITEMIZE: {
2925 // At some point of time we should do something more
2926 // clever here, like:
2927 // par.params().labelString(
2928 // bp.user_defined_bullet(par.itemdepth).getText());
2929 // for now, use a simple hardcoded label
2930 docstring itemlabel;
2931 switch (par.itemdepth) {
2933 itemlabel = char_type(0x2022);
2936 itemlabel = char_type(0x2013);
2939 itemlabel = char_type(0x2217);
2942 itemlabel = char_type(0x2219); // or 0x00b7
2945 par.params().labelString(itemlabel);
2949 case LABEL_ENUMERATE: {
2950 // FIXME: Yes I know this is a really, really! bad solution
2952 docstring enumcounter = from_ascii("enum");
2954 switch (par.itemdepth) {
2963 enumcounter += "iv";
2966 // not a valid enumdepth...
2970 // Maybe we have to reset the enumeration counter.
2971 if (needEnumCounterReset(it))
2972 counters.reset(enumcounter);
2974 counters.step(enumcounter);
2978 switch (par.itemdepth) {
2980 format = N_("\\arabic{enumi}.");
2983 format = N_("(\\alph{enumii})");
2986 format = N_("\\roman{enumiii}.");
2989 format = N_("\\Alph{enumiv}.");
2992 // not a valid enumdepth...
2996 par.params().labelString(counters.counterLabel(
2997 par.translateIfPossible(from_ascii(format), bp)));
3002 case LABEL_SENSITIVE: {
3003 string const & type = counters.current_float();
3004 docstring full_label;
3006 full_label = buf.B_("Senseless!!! ");
3008 docstring name = buf.B_(textclass.floats().getType(type).name());
3009 if (counters.hasCounter(from_utf8(type))) {
3010 counters.step(from_utf8(type));
3011 full_label = bformat(from_ascii("%1$s %2$s:"),
3013 counters.theCounter(from_utf8(type)));
3015 full_label = bformat(from_ascii("%1$s #:"), name);
3017 par.params().labelString(full_label);
3021 case LABEL_NO_LABEL:
3022 par.params().labelString(docstring());
3026 case LABEL_TOP_ENVIRONMENT:
3027 case LABEL_CENTERED_TOP_ENVIRONMENT:
3030 par.params().labelString(
3031 par.translateIfPossible(layout.labelstring(), bp));
3037 void Buffer::updateLabels(ParIterator & parit) const
3039 LASSERT(parit.pit() == 0, /**/);
3041 // set the position of the text in the buffer to be able
3042 // to resolve macros in it. This has nothing to do with
3043 // labels, but by putting it here we avoid implementing
3044 // a whole bunch of traversal routines just for this call.
3045 parit.text()->setMacrocontextPosition(parit);
3047 depth_type maxdepth = 0;
3048 pit_type const lastpit = parit.lastpit();
3049 for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3050 // reduce depth if necessary
3051 parit->params().depth(min(parit->params().depth(), maxdepth));
3052 maxdepth = parit->getMaxDepthAfter();
3054 // set the counter for this paragraph
3055 setLabel(*this, parit);
3058 InsetList::const_iterator iit = parit->insetList().begin();
3059 InsetList::const_iterator end = parit->insetList().end();
3060 for (; iit != end; ++iit) {
3061 parit.pos() = iit->pos;
3062 iit->inset->updateLabels(parit);
3068 bool Buffer::nextWord(DocIterator & from, DocIterator & to,
3069 docstring & word) const
3071 bool inword = false;
3072 bool ignoreword = false;
3076 while (to.depth()) {
3083 lang_code = to.paragraph().getFontSettings(params(),
3084 to.pos()).language()->code();
3086 // Insets like optional hyphens and ligature
3087 // break are part of a word.
3088 if (!to.paragraph().isInset(to.pos())) {
3089 char_type const c = to.paragraph().getChar(to.pos());
3094 } else { // !isLetter(cur)
3095 if (inword && !word.empty() && !ignoreword)