]> git.lyx.org Git - features.git/blob - src/Buffer.h
Proper fix now for bug #6846. The idea, due to JMarc, is to collect
[features.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21
22 #include <list>
23 #include <set>
24 #include <string>
25 #include <vector>
26
27
28 namespace lyx {
29
30 class BiblioInfo;
31 class BufferParams;
32 class DispatchResult;
33 class DocIterator;
34 class docstring_list;
35 class ErrorList;
36 class FuncRequest;
37 class FuncStatus;
38 class Inset;
39 class InsetLabel;
40 class InsetRef;
41 class Font;
42 class Format;
43 class Lexer;
44 class Text;
45 class LyXVC;
46 class LaTeXFeatures;
47 class Language;
48 class MacroData;
49 class MacroNameSet;
50 class MacroSet;
51 class OutputParams;
52 class Paragraph;
53 class ParConstIterator;
54 class ParIterator;
55 class ParagraphList;
56 class TeXErrors;
57 class TexRow;
58 class TocBackend;
59 class Undo;
60 class WordLangTuple;
61
62 namespace frontend {
63 class GuiBufferDelegate;
64 class WorkAreaManager;
65 }
66
67 namespace support {
68 class FileName;
69 class FileNameList;
70 }
71
72
73 class Buffer;
74 typedef std::list<Buffer *> ListOfBuffers;
75
76
77 /** The buffer object.
78  * This is the buffer object. It contains all the informations about
79  * a document loaded into LyX.
80  * The buffer object owns the Text (wrapped in an InsetText), which
81  * contains the individual paragraphs of the document.
82  *
83  *
84  * I am not sure if the class is complete or
85  * minimal, probably not.
86  * \author Lars Gullik Bjønnes
87  */
88 class Buffer {
89 public:
90         /// What type of log will \c getLogName() return?
91         enum LogType {
92                 latexlog, ///< LaTeX log
93                 buildlog  ///< Literate build log
94         };
95
96         /// Result of \c readFile()
97         enum ReadStatus {
98                 ReadSuccess,
99                 ReadCancel,
100                 // failures
101                 ReadFailure,
102                 ReadWrongVersion,
103                 ReadFileNotFound,
104                 ReadVCError,
105                 ReadAutosaveFailure,            
106                 ReadEmergencyFailure,
107                 ReadNoLyXFormat,
108                 ReadDocumentFailure,
109                 // lyx2lyx
110                 LyX2LyXNoTempFile,
111                 LyX2LyXNotFound,
112                 LyX2LyXOlderFormat,
113                 LyX2LyXNewerFormat,
114                 // other
115                 ReadOriginal
116         };
117
118
119         /// Method to check if a file is externally modified, used by
120         /// isExternallyModified()
121         /**
122          * timestamp is fast but inaccurate. For example, the granularity
123          * of timestamp on a FAT filesystem is 2 second. Also, various operations
124          * may touch the timestamp of a file even when its content is unchanged.
125          *
126          * checksum is accurate but slow, which can be a problem when it is
127          * frequently used, or used for a large file on a slow (network) file
128          * system.
129          *
130          * FIXME: replace this method with support/FileMonitor.
131          */
132         enum CheckMethod {
133                 checksum_method,  ///< Use file checksum
134                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
135         };
136
137         ///
138         enum UpdateScope {
139                 UpdateMaster,
140                 UpdateChildOnly
141         };
142
143         /// Constructor
144         explicit Buffer(std::string const & file, bool readonly = false,
145                 Buffer const * cloned_buffer = 0);
146
147         /// Destructor
148         ~Buffer();
149
150         ///
151         Buffer * clone() const;
152         ///
153         bool isClone() const;
154
155         /** High-level interface to buffer functionality.
156             This function parses a command string and executes it.
157         */
158         void dispatch(std::string const & command, DispatchResult & result);
159
160         /// Maybe we know the function already by number...
161         void dispatch(FuncRequest const & func, DispatchResult & result);
162
163         /// Can this function be exectued?
164         /// \return true if we made a decision
165         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
166
167         ///
168         DocIterator getParFromID(int id) const;
169         /// do we have a paragraph with this id?
170         bool hasParWithID(int id) const;
171
172         ///
173         frontend::WorkAreaManager & workAreaManager() const;
174
175         /** Save file.
176             Takes care of auto-save files and backup file if requested.
177             Returns \c true if the save is successful, \c false otherwise.
178         */
179         bool save() const;
180         /// Renames and saves the buffer
181         bool saveAs(support::FileName const & fn);
182
183         /// Write document to stream. Returns \c false if unsuccesful.
184         bool write(std::ostream &) const;
185         /// Write file. Returns \c false if unsuccesful.
186         bool writeFile(support::FileName const &) const;
187
188         /// \name Functions involved in reading files/strings.
189         //@{
190         /// Loads the LyX file into the buffer. This function
191         /// tries to extract the file from version control if it
192         /// cannot be found. If it can be found, it will try to
193         /// read an emergency save file or an autosave file.
194         /// \sa loadThisLyXFile
195         ReadStatus loadLyXFile();
196         /// Loads the LyX file \c fn into the buffer. If you want
197         /// to check for files in a version control container,
198         /// emergency or autosave files, one should use \c loadLyXFile.
199         /// /sa loadLyXFile
200         ReadStatus loadThisLyXFile(support::FileName const & fn);
201         /// read a new document from a string
202         bool readString(std::string const &);
203         /// Reloads the LyX file
204         ReadStatus reload();
205 //FIXME: The following function should be private
206 //private:
207         /// read the header, returns number of unknown tokens
208         int readHeader(Lexer & lex);
209
210 private:
211         /// save timestamp and checksum of the given file.
212         void saveCheckSum() const;      
213         /// read a new file
214         ReadStatus readFile(support::FileName const & fn);
215         /// Reads a file without header.
216         /// \param par if != 0 insert the file.
217         /// \return \c true if file is not completely read.
218         bool readDocument(Lexer &);
219         /// Try to extract the file from a version control container
220         /// before reading if the file cannot be found. This is only
221         /// implemented for RCS.
222         /// \sa LyXVC::file_not_found_hook
223         ReadStatus extractFromVC();
224         /// Reads the first tag of a LyX File and 
225         /// returns the file format number.
226         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
227                 int & file_format) const;
228         /// Convert the LyX file to the LYX_FORMAT using
229         /// the lyx2lyx script and returns the filename
230         /// of the temporary file to be read
231         ReadStatus convertLyXFormat(support::FileName const & fn, 
232                 support::FileName & tmpfile, int from_format);
233         //@}
234
235 public:
236         /// \name Functions involved in autosave and emergency files.
237         //@{
238         /// Save an autosave file to #filename.lyx#
239         bool autoSave() const;  
240         /// save emergency file
241         /// \return a status message towards the user.
242         docstring emergencyWrite();
243
244 //FIXME:The following function should be private
245 //private:
246         ///
247         void removeAutosaveFile() const;
248         
249 private:
250         /// Try to load an autosave file associated to \c fn.
251         ReadStatus loadAutosave();
252         /// Try to load an emergency file associated to \c fn. 
253         ReadStatus loadEmergency();
254         /// Get the filename of the emergency file associated with the Buffer
255         support::FileName getEmergencyFileName() const;
256         /// Get the filename of the autosave file associated with the Buffer
257         support::FileName getAutosaveFileName() const;
258         ///
259         void moveAutosaveFile(support::FileName const & old) const;
260         //@}
261
262 public:
263         /// Fill in the ErrorList with the TeXErrors
264         void bufferErrors(TeXErrors const &, ErrorList &) const;
265
266         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
267         bool makeLaTeXFile(support::FileName const & filename,
268                            std::string const & original_path,
269                            OutputParams const &,
270                            bool output_preamble = true,
271                            bool output_body = true) const;
272         /** Export the buffer to LaTeX.
273             If \p os is a file stream, and params().inputenc is "auto" or
274             "default", and the buffer contains text in different languages
275             with more than one encoding, then this method will change the
276             encoding associated to \p os. Therefore you must not call this
277             method with a string stream if the output is supposed to go to a
278             file. \code
279             ofdocstream ofs;
280             ofs.open("test.tex");
281             writeLaTeXSource(ofs, ...);
282             ofs.close();
283             \endcode is NOT equivalent to \code
284             odocstringstream oss;
285             writeLaTeXSource(oss, ...);
286             ofdocstream ofs;
287             ofs.open("test.tex");
288             ofs << oss.str();
289             ofs.close();
290             \endcode
291          */
292         void writeLaTeXSource(odocstream & os,
293                            std::string const & original_path,
294                            OutputParams const &,
295                            bool output_preamble = true,
296                            bool output_body = true) const;
297         ///
298         void makeDocBookFile(support::FileName const & filename,
299                              OutputParams const & runparams_in,
300                              bool only_body = false) const;
301         ///
302         void writeDocBookSource(odocstream & os, std::string const & filename,
303                              OutputParams const & runparams_in,
304                              bool only_body = false) const;
305         ///
306         void makeLyXHTMLFile(support::FileName const & filename,
307                              OutputParams const & runparams_in,
308                              bool only_body = false) const;
309         ///
310         void writeLyXHTMLSource(odocstream & os,
311                              OutputParams const & runparams_in,
312                              bool only_body = false) const;
313         /// returns the main language for the buffer (document)
314         Language const * language() const;
315         /// get l10n translated to the buffers language
316         docstring const B_(std::string const & l10n) const;
317
318         ///
319         int runChktex();
320         /// return true if the main lyx file does not need saving
321         bool isClean() const;
322         ///
323         bool isDepClean(std::string const & name) const;
324
325         /// whether or not disk file has been externally modified
326         bool isExternallyModified(CheckMethod method) const;
327
328         /// mark the main lyx file as not needing saving
329         void markClean() const;
330
331         ///
332         void markDepClean(std::string const & name);
333
334         ///
335         void setUnnamed(bool flag = true);
336
337         /// Whether or not a filename has been assigned to this buffer
338         bool isUnnamed() const;
339
340         /// Whether or not this buffer is internal.
341         ///
342         /// An internal buffer does not contain a real document, but some auxiliary text segment.
343         /// It is not associated with a filename, it is never saved, thus it does not need to be
344         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
345         bool isInternal() const;
346
347         /// Mark this buffer as dirty.
348         void markDirty();
349
350         /// Returns the buffer's filename. It is always an absolute path.
351         support::FileName fileName() const;
352
353         /// Returns the buffer's filename. It is always an absolute path.
354         std::string absFileName() const;
355
356         /// Returns the the path where the buffer lives.
357         /// It is always an absolute path.
358         std::string filePath() const;
359
360         /** A transformed version of the file name, adequate for LaTeX.
361             \param no_path optional if \c true then the path is stripped.
362         */
363         std::string latexName(bool no_path = true) const;
364
365         /// Get the name and type of the log.
366         std::string logName(LogType * type = 0) const;
367
368         /// Set document's parent Buffer.
369         void setParent(Buffer const *);
370         Buffer const * parent() const;
371
372         /** Get the document's master (or \c this if this is not a
373             child document)
374          */
375         Buffer const * masterBuffer() const;
376
377         /// \return true if \p child is a child of this \c Buffer.
378         bool isChild(Buffer * child) const;
379         
380         /// \return true if this \c Buffer has children
381         bool hasChildren() const;
382         
383         /// \return a list of the direct children of this Buffer.
384         /// this list has no duplicates and is in the order in which
385         /// the children appear.
386         ListOfBuffers getChildren() const;
387         
388         /// \return a list of all descendents of this Buffer (children,
389         /// grandchildren, etc). this list has no duplicates and is in
390         /// the order in which the children appear.
391         ListOfBuffers getDescendents() const;
392
393         /// Collect all relative buffers, in the order in which they appear.
394         /// I.e., the "root" Buffer is first, then its first child, then any
395         /// of its children, etc. However, there are no duplicates in this
396         /// list.
397         /// This is "stable", too, in the sense that it returns the same
398         /// thing from whichever Buffer it is called.
399         ListOfBuffers allRelatives() const;
400
401         /// Is buffer read-only?
402         bool isReadonly() const;
403
404         /// Set buffer read-only flag
405         void setReadonly(bool flag = true);
406
407         /// returns \c true if the buffer contains a LaTeX document
408         bool isLatex() const;
409         /// returns \c true if the buffer contains a DocBook document
410         bool isDocBook() const;
411         /// returns \c true if the buffer contains a Wed document
412         bool isLiterate() const;
413
414         /** Validate a buffer for LaTeX.
415             This validates the buffer, and returns a struct for use by
416             #makeLaTeX# and others. Its main use is to figure out what
417             commands and packages need to be included in the LaTeX file.
418             It (should) also check that the needed constructs are there
419             (i.e. that the \refs points to coresponding \labels). It
420             should perhaps inset "error" insets to help the user correct
421             obvious mistakes.
422         */
423         void validate(LaTeXFeatures &) const;
424
425         /// Reference information is cached in the Buffer, so we do not
426         /// have to check or read things over and over. 
427         ///
428         /// There are two caches.
429         ///
430         /// One is a cache of the BibTeX files from which reference info is
431         /// being gathered. This cache is PER BUFFER, and the cache for the
432         /// master essentially includes the cache for its children. This gets
433         /// invalidated when an InsetBibtex is created, deleted, or modified.
434         /// 
435         /// The other is a cache of the reference information itself. This
436         /// exists only in the master buffer, and when it needs to be updated,
437         /// the children add their information to the master's cache.
438         
439         /// Calling this method invalidates the cache and so requires a
440         /// re-read.
441         void invalidateBibinfoCache() const;
442         /// This invalidates the cache of files we need to check.
443         void invalidateBibfileCache() const;
444         /// Updates the cached bibliography information, checking first to see
445         /// whether the cache is valid. If so, we do nothing. If not, then we
446         /// reload all the BibTeX info.
447         /// Note that this operates on the master document.
448         /// Normally, this is done (more cheaply) in updateBuffer(), but there are
449         /// times when we need to force it to be done and don't need a full buffer
450         /// update. This is in GuiCitation and in changeRefsIfUnique() now.
451         void reloadBibInfoCache() const;
452         /// Was the cache valid the last time we checked?
453         bool isBibInfoCacheValid() const;
454         /// \return the bibliography information for this buffer's master,
455         /// or just for it, if it isn't a child.
456         BiblioInfo const & masterBibInfo() const;
457         BiblioInfo & masterBibInfo();
458         ///
459         void fillWithBibKeys(BiblioInfo & keys) const;
460         ///
461         void getLabelList(std::vector<docstring> &) const;
462
463         ///
464         void changeLanguage(Language const * from, Language const * to);
465
466         ///
467         bool isMultiLingual() const;
468         ///
469         std::set<Language const *> getLanguages() const;
470
471         ///
472         BufferParams & params();
473         BufferParams const & params() const;
474
475         /** The list of paragraphs.
476             This is a linked list of paragraph, this list holds the
477             whole contents of the document.
478          */
479         ParagraphList & paragraphs();
480         ParagraphList const & paragraphs() const;
481
482         /// LyX version control object.
483         LyXVC & lyxvc();
484         LyXVC const & lyxvc() const;
485
486         /// Where to put temporary files.
487         std::string const temppath() const;
488
489         /// Used when typesetting to place errorboxes.
490         TexRow const & texrow() const;
491         TexRow & texrow();
492
493         ///
494         ParIterator par_iterator_begin();
495         ///
496         ParConstIterator par_iterator_begin() const;
497         ///
498         ParIterator par_iterator_end();
499         ///
500         ParConstIterator par_iterator_end() const;
501
502         // Position of the child buffer where it appears first in the master.
503         DocIterator firstChildPosition(Buffer const * child);
504
505         /** \returns true only when the file is fully loaded.
506          *  Used to prevent the premature generation of previews
507          *  and by the citation inset.
508          */
509         bool isFullyLoaded() const;
510         /// Set by buffer_funcs' newFile.
511         void setFullyLoaded(bool);
512
513         /// Update the LaTeX preview snippets associated with this buffer
514         void updatePreviews() const;
515         /// Remove any previewed LaTeX snippets associated with this buffer
516         void removePreviews() const;
517
518         /// Our main text (inside the top InsetText)
519         Text & text() const;
520
521         /// Our top InsetText
522         Inset & inset() const;
523
524         //
525         // Macro handling
526         //
527         /// Collect macro definitions in paragraphs
528         void updateMacros() const;
529         /// Iterate through the whole buffer and try to resolve macros
530         void updateMacroInstances() const;
531
532         /// List macro names of this buffer, the parent and the children
533         void listMacroNames(MacroNameSet & macros) const;
534         /// Collect macros of the parent and its children in front of this buffer.
535         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
536
537         /// Return macro defined before pos (or in the master buffer)
538         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
539         /// Return macro defined anywhere in the buffer (or in the master buffer)
540         MacroData const * getMacro(docstring const & name, bool global = true) const;
541         /// Return macro defined before the inclusion of the child
542         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
543
544         /// Collect user macro names at loading time
545         typedef std::set<docstring> UserMacroSet;
546         UserMacroSet usermacros;
547
548         /// Replace the inset contents for insets which InsetCode is equal
549         /// to the passed \p inset_code.
550         void changeRefsIfUnique(docstring const & from, docstring const & to,
551                 InsetCode code);
552
553         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
554         /// including preamble
555         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
556                 bool full_source) const;
557
558         /// Access to error list.
559         /// This method is used only for GUI visualisation of Buffer related
560         /// errors (like parsing or LateX compilation). This method is const
561         /// because modifying the returned ErrorList does not touch the document
562         /// contents.
563         ErrorList & errorList(std::string const & type) const;
564
565         /// The Toc backend.
566         /// This is useful only for screen visualisation of the Buffer. This
567         /// method is const because modifying this backend does not touch
568         /// the document contents.
569         TocBackend & tocBackend() const;
570
571         ///
572         Undo & undo();
573
574         /// This function is called when the buffer is changed.
575         void changed(bool update_metrics) const;
576         ///
577         void setChild(DocIterator const & dit, Buffer * child);
578         ///
579         void updateTocItem(std::string const &, DocIterator const &) const;
580         /// This function is called when the buffer structure is changed.
581         void structureChanged() const;
582         /// This function is called when some parsing error shows up.
583         void errors(std::string const & err, bool from_master = false) const;
584         /// This function is called when the buffer busy status change.
585         void setBusy(bool on) const;
586         /// Update window titles of all users.
587         void updateTitles() const;
588         /// Reset autosave timers for all users.
589         void resetAutosaveTimers() const;
590         ///
591         void message(docstring const & msg) const;
592
593         ///
594         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
595         ///
596         bool hasGuiDelegate() const;
597
598         
599
600         /// return the format of the buffer on a string
601         std::string bufferFormat() const;
602         /// return the default output format of the current backend
603         std::string getDefaultOutputFormat() const;
604
605         ///
606         bool doExport(std::string const & format, bool put_in_tempdir,
607                 bool includeall, std::string & result_file) const;
608         ///
609         bool doExport(std::string const & format, bool put_in_tempdir,
610                       bool includeall = false) const;
611         ///
612         bool preview(std::string const & format, bool includeall = false) const;
613         ///
614         bool isExportable(std::string const & format) const;
615         ///
616         std::vector<Format const *> exportableFormats(bool only_viewable) const;
617         ///
618         bool isExportableFormat(std::string const & format) const;
619         /// mark the buffer as busy exporting something, or not
620         void setExportStatus(bool e) const;
621         ///
622         bool isExporting() const;
623
624         ///
625         typedef std::vector<std::pair<Inset *, ParIterator> > References;
626         References & references(docstring const & label);
627         References const & references(docstring const & label) const;
628         void clearReferenceCache() const;
629         void setInsetLabel(docstring const & label, InsetLabel const * il);
630         InsetLabel const * insetLabel(docstring const & label) const;
631
632         /// return a list of all used branches (also in children)
633         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
634
635         /// sets the buffer_ member for every inset in this buffer.
636         // FIXME This really shouldn't be needed, but at the moment it's not
637         // clear how to do it just for the individual pieces we need.
638         void setBuffersForInsets() const;
639         /// Updates screen labels and some other information associated with
640         /// insets and paragraphs. Actually, it's more like a general "recurse
641         /// through the Buffer" routine, that visits all the insets and paragraphs.
642         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
643         /// \param scope: whether to start with the master document or just
644         /// do this one.
645         /// \param output: whether we are preparing for output.
646         void updateBuffer(UpdateScope scope, UpdateType utype) const;
647         /// 
648         void updateBuffer(ParIterator & parit, UpdateType utype) const;
649
650         /// Spellcheck starting from \p from.
651         /// \p from initial position, will then points to the next misspelled
652         ///    word.
653         /// \p to will points to the end of the next misspelled word.
654         /// \p word_lang will contain the found misspelled word.
655         /// \return progress if a new word was found.
656         int spellCheck(DocIterator & from, DocIterator & to,
657                 WordLangTuple & word_lang, docstring_list & suggestions) const;
658         ///
659         void checkChildBuffers();
660
661 private:
662         /// Change name of buffer. Updates "read-only" flag.
663         void setFileName(support::FileName const & fname);
664         ///
665         std::vector<std::string> backends() const;
666         ///
667         void getLanguages(std::set<Language const *> &) const;
668         /// Checks whether any of the referenced bibfiles have changed since the
669         /// last time we loaded the cache. Note that this does NOT update the
670         /// cached information.
671         void checkIfBibInfoCacheIsValid() const;
672         /// Update the list of all bibfiles in use (including bibfiles
673         /// of loaded child documents).
674         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
675         /// Return the list with all bibfiles in use (including bibfiles
676         /// of loaded child documents).
677         support::FileNameList const & 
678                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
679         ///
680         void collectChildren(ListOfBuffers & children, bool grand_children) const;
681
682         
683         /// Use the Pimpl idiom to hide the internals.
684         class Impl;
685         /// The pointer never changes although *pimpl_'s contents may.
686         Impl * const d;
687 };
688
689
690 } // namespace lyx
691
692 #endif