]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
deb66ee4975b056724c7f0ec947c60eff7c4e199
[lyx.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
181         /// Write document to stream. Returns \c false if unsuccesful.
182         bool write(std::ostream &) const;
183         /// Write file. Returns \c false if unsuccesful.
184         bool writeFile(support::FileName const &) const;
185
186         /// \name Functions involved in reading files/strings.
187         //@{
188         /// Loads a LyX file \c fn into the buffer. This function
189         /// tries to extract the file from version control if it
190         /// cannot be found. If it can be found, it will try to
191         /// read an emergency save file or an autosave file.
192         /// \sa loadThisLyXFile
193         ReadStatus loadLyXFile(support::FileName const & fn);
194         /// Loads a LyX file \c fn into the buffer. If you want
195         /// to check for files in a version control container,
196         /// emergency or autosave files, one should use \c loadLyXFile.
197         /// /sa loadLyXFile
198         ReadStatus loadThisLyXFile(support::FileName const & fn);
199         /// read a new document from a string
200         bool readString(std::string const &);
201         /// Reloads the LyX file
202         bool reload();
203 //FIXME: The following function should be private
204 //private:
205         /// read the header, returns number of unknown tokens
206         int readHeader(Lexer & lex);
207         
208 private:
209         /// read a new file
210         ReadStatus readFile(support::FileName const & fn);
211         /// Reads a file without header.
212         /// \param par if != 0 insert the file.
213         /// \return \c true if file is not completely read.
214         bool readDocument(Lexer &);
215         /// Try to extract the file from a version control container
216         /// before reading if the file cannot be found. This is only
217         /// implemented for RCS.
218         /// \sa LyXVC::file_not_found_hook
219         ReadStatus readFromVC(support::FileName const & fn);
220         /// Reads the first tag of a LyX File and 
221         /// returns the file format number.
222         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
223                 int & file_format) const;
224         /// Convert the LyX file to the LYX_FORMAT using
225         /// the lyx2lyx script and returns the filename
226         /// of the temporary file to be read
227         ReadStatus convertLyXFormat(support::FileName const & fn, 
228                 support::FileName & tmpfile, int from_format);
229         //@}
230
231 public:
232         /// \name Functions involved in autosave and emergency files.
233         //@{
234         ///
235         void autoSave() const;
236         /// save emergency file
237         /// \return a status message towards the user.
238         docstring emergencyWrite();
239
240 //FIXME:The following three functions should be private
241 //private:
242         ///
243         void removeAutosaveFile() const;
244         ///
245         void moveAutosaveFile(support::FileName const & old) const;
246         /// Get the filename of the autosave file associated with the Buffer
247         support::FileName getAutosaveFileName() const;
248         
249 private:
250         /// Try to read an autosave file associated to \c fn.
251         ReadStatus readAutosave(support::FileName const & fn);
252         /// Get the filename of the autosave file associated with \c fn
253         support::FileName getAutosaveFileNameFor(support::FileName const & fn)
254                 const;
255
256         /// Try to read an emergency file associated to \c fn. 
257         ReadStatus readEmergency(support::FileName const & fn);
258         /// Get the filename of the emergency file associated with the Buffer
259         support::FileName getEmergencyFileName() const;
260         /// Get the filename of the emergency file associated with \c fn
261         support::FileName getEmergencyFileNameFor(support::FileName const & fn)
262                 const;
263         //@}
264
265 public:
266         /// Fill in the ErrorList with the TeXErrors
267         void bufferErrors(TeXErrors const &, ErrorList &) const;
268
269         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
270         bool makeLaTeXFile(support::FileName const & filename,
271                            std::string const & original_path,
272                            OutputParams const &,
273                            bool output_preamble = true,
274                            bool output_body = true) const;
275         /** Export the buffer to LaTeX.
276             If \p os is a file stream, and params().inputenc is "auto" or
277             "default", and the buffer contains text in different languages
278             with more than one encoding, then this method will change the
279             encoding associated to \p os. Therefore you must not call this
280             method with a string stream if the output is supposed to go to a
281             file. \code
282             ofdocstream ofs;
283             ofs.open("test.tex");
284             writeLaTeXSource(ofs, ...);
285             ofs.close();
286             \endcode is NOT equivalent to \code
287             odocstringstream oss;
288             writeLaTeXSource(oss, ...);
289             ofdocstream ofs;
290             ofs.open("test.tex");
291             ofs << oss.str();
292             ofs.close();
293             \endcode
294          */
295         void writeLaTeXSource(odocstream & os,
296                            std::string const & original_path,
297                            OutputParams const &,
298                            bool output_preamble = true,
299                            bool output_body = true) const;
300         ///
301         void makeDocBookFile(support::FileName const & filename,
302                              OutputParams const & runparams_in,
303                              bool only_body = false) const;
304         ///
305         void writeDocBookSource(odocstream & os, std::string const & filename,
306                              OutputParams const & runparams_in,
307                              bool only_body = false) const;
308         ///
309         void makeLyXHTMLFile(support::FileName const & filename,
310                              OutputParams const & runparams_in,
311                              bool only_body = false) const;
312         ///
313         void writeLyXHTMLSource(odocstream & os,
314                              OutputParams const & runparams_in,
315                              bool only_body = false) const;
316         /// returns the main language for the buffer (document)
317         Language const * language() const;
318         /// get l10n translated to the buffers language
319         docstring const B_(std::string const & l10n) const;
320
321         ///
322         int runChktex();
323         /// return true if the main lyx file does not need saving
324         bool isClean() const;
325         ///
326         bool isDepClean(std::string const & name) const;
327
328         /// whether or not disk file has been externally modified
329         bool isExternallyModified(CheckMethod method) const;
330
331         /// save timestamp and checksum of the given file.
332         void saveCheckSum(support::FileName const & file) const;
333
334         /// mark the main lyx file as not needing saving
335         void markClean() const;
336
337         ///
338         void markDepClean(std::string const & name);
339
340         ///
341         void setUnnamed(bool flag = true);
342
343         /// Whether or not a filename has been assigned to this buffer
344         bool isUnnamed() const;
345
346         /// Whether or not this buffer is internal.
347         ///
348         /// An internal buffer does not contain a real document, but some auxiliary text segment.
349         /// It is not associated with a filename, it is never saved, thus it does not need to be
350         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
351         bool isInternal() const;
352
353         /// Mark this buffer as dirty.
354         void markDirty();
355
356         /// Returns the buffer's filename. It is always an absolute path.
357         support::FileName fileName() const;
358
359         /// Returns the buffer's filename. It is always an absolute path.
360         std::string absFileName() const;
361
362         /// Returns the the path where the buffer lives.
363         /// It is always an absolute path.
364         std::string filePath() const;
365
366         /** A transformed version of the file name, adequate for LaTeX.
367             \param no_path optional if \c true then the path is stripped.
368         */
369         std::string latexName(bool no_path = true) const;
370
371         /// Get the name and type of the log.
372         std::string logName(LogType * type = 0) const;
373
374         /// Change name of buffer. Updates "read-only" flag.
375         void setFileName(std::string const & newfile);
376
377         /// Set document's parent Buffer.
378         void setParent(Buffer const *);
379         Buffer const * parent() const;
380
381         /** Get the document's master (or \c this if this is not a
382             child document)
383          */
384         Buffer const * masterBuffer() const;
385
386         /// \return true if \p child is a child of this \c Buffer.
387         bool isChild(Buffer * child) const;
388         
389         /// \return true if this \c Buffer has children
390         bool hasChildren() const;
391         
392         /// \return a list of the direct children of this Buffer.
393         /// this list has no duplicates and is in the order in which
394         /// the children appear.
395         ListOfBuffers getChildren() const;
396         
397         /// \return a list of all descendents of this Buffer (children,
398         /// grandchildren, etc). this list has no duplicates and is in
399         /// the order in which the children appear.
400         ListOfBuffers getDescendents() const;
401
402         /// Collect all relative buffers, in the order in which they appear.
403         /// I.e., the "root" Buffer is first, then its first child, then any
404         /// of its children, etc. However, there are no duplicates in this
405         /// list.
406         /// This is "stable", too, in the sense that it returns the same
407         /// thing from whichever Buffer it is called.
408         ListOfBuffers allRelatives() const;
409
410         /// Is buffer read-only?
411         bool isReadonly() const;
412
413         /// Set buffer read-only flag
414         void setReadonly(bool flag = true);
415
416         /// returns \c true if the buffer contains a LaTeX document
417         bool isLatex() const;
418         /// returns \c true if the buffer contains a DocBook document
419         bool isDocBook() const;
420         /// returns \c true if the buffer contains a Wed document
421         bool isLiterate() const;
422
423         /** Validate a buffer for LaTeX.
424             This validates the buffer, and returns a struct for use by
425             #makeLaTeX# and others. Its main use is to figure out what
426             commands and packages need to be included in the LaTeX file.
427             It (should) also check that the needed constructs are there
428             (i.e. that the \refs points to coresponding \labels). It
429             should perhaps inset "error" insets to help the user correct
430             obvious mistakes.
431         */
432         void validate(LaTeXFeatures &) const;
433
434         /// Reference information is cached in the Buffer, so we do not
435         /// have to check or read things over and over. 
436         ///
437         /// There are two caches.
438         ///
439         /// One is a cache of the BibTeX files from which reference info is
440         /// being gathered. This cache is PER BUFFER, and the cache for the
441         /// master essentially includes the cache for its children. This gets
442         /// invalidated when an InsetBibtex is created, deleted, or modified.
443         /// 
444         /// The other is a cache of the reference information itself. This
445         /// exists only in the master buffer, and when it needs to be updated,
446         /// the children add their information to the master's cache.
447         
448         /// Calling this method invalidates the cache and so requires a
449         /// re-read.
450         void invalidateBibinfoCache() const;
451         /// This invalidates the cache of files we need to check.
452         void invalidateBibfileCache() const;
453         /// Updates the cached bibliography information.
454         /// Note that you MUST call this method to update the cache. It will
455         /// not happen otherwise. (Currently, it is called at the start of
456         /// updateBuffer() and from GuiCitation.)
457         /// Note that this operates on the master document.
458         void checkBibInfoCache() const;
459         /// \return the bibliography information for this buffer's master,
460         /// or just for it, if it isn't a child.
461         BiblioInfo const & masterBibInfo() const;
462         ///
463         void fillWithBibKeys(BiblioInfo & keys) const;
464         ///
465         void getLabelList(std::vector<docstring> &) const;
466
467         ///
468         void changeLanguage(Language const * from, Language const * to);
469
470         ///
471         bool isMultiLingual() const;
472         ///
473         std::set<Language const *> getLanguages() const;
474
475         ///
476         BufferParams & params();
477         BufferParams const & params() const;
478
479         /** The list of paragraphs.
480             This is a linked list of paragraph, this list holds the
481             whole contents of the document.
482          */
483         ParagraphList & paragraphs();
484         ParagraphList const & paragraphs() const;
485
486         /// LyX version control object.
487         LyXVC & lyxvc();
488         LyXVC const & lyxvc() const;
489
490         /// Where to put temporary files.
491         std::string const temppath() const;
492
493         /// Used when typesetting to place errorboxes.
494         TexRow const & texrow() const;
495         TexRow & texrow();
496
497         ///
498         ParIterator par_iterator_begin();
499         ///
500         ParConstIterator par_iterator_begin() const;
501         ///
502         ParIterator par_iterator_end();
503         ///
504         ParConstIterator par_iterator_end() const;
505
506         // Position of the child buffer where it appears first in the master.
507         DocIterator firstChildPosition(Buffer const * child);
508
509         /** \returns true only when the file is fully loaded.
510          *  Used to prevent the premature generation of previews
511          *  and by the citation inset.
512          */
513         bool isFullyLoaded() const;
514         /// Set by buffer_funcs' newFile.
515         void setFullyLoaded(bool);
516
517         /// Our main text (inside the top InsetText)
518         Text & text() const;
519
520         /// Our top InsetText
521         Inset & inset() const;
522
523         //
524         // Macro handling
525         //
526         /// Collect macro definitions in paragraphs
527         void updateMacros() const;
528         /// Iterate through the whole buffer and try to resolve macros
529         void updateMacroInstances() const;
530
531         /// List macro names of this buffer, the parent and the children
532         void listMacroNames(MacroNameSet & macros) const;
533         /// Collect macros of the parent and its children in front of this buffer.
534         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
535
536         /// Return macro defined before pos (or in the master buffer)
537         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
538         /// Return macro defined anywhere in the buffer (or in the master buffer)
539         MacroData const * getMacro(docstring const & name, bool global = true) const;
540         /// Return macro defined before the inclusion of the child
541         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
542
543         /// Collect user macro names at loading time
544         typedef std::set<docstring> UserMacroSet;
545         UserMacroSet usermacros;
546
547         /// Replace the inset contents for insets which InsetCode is equal
548         /// to the passed \p inset_code.
549         void changeRefsIfUnique(docstring const & from, docstring const & to,
550                 InsetCode code);
551
552         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
553         /// including preamble
554         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
555                 bool full_source) const;
556
557         /// Access to error list.
558         /// This method is used only for GUI visualisation of Buffer related
559         /// errors (like parsing or LateX compilation). This method is const
560         /// because modifying the returned ErrorList does not touch the document
561         /// contents.
562         ErrorList & errorList(std::string const & type) const;
563
564         /// The Toc backend.
565         /// This is useful only for screen visualisation of the Buffer. This
566         /// method is const because modifying this backend does not touch
567         /// the document contents.
568         TocBackend & tocBackend() const;
569
570         ///
571         Undo & undo();
572
573         /// This function is called when the buffer is changed.
574         void changed(bool update_metrics) const;
575         ///
576         void setChild(DocIterator const & dit, Buffer * child);
577         ///
578         void updateTocItem(std::string const &, DocIterator const &) const;
579         /// This function is called when the buffer structure is changed.
580         void structureChanged() const;
581         /// This function is called when some parsing error shows up.
582         void errors(std::string const & err, bool from_master = false) const;
583         /// This function is called when the buffer busy status change.
584         void setBusy(bool on) const;
585         /// Update window titles of all users.
586         void updateTitles() const;
587         /// Reset autosave timers for all users.
588         void resetAutosaveTimers() const;
589         ///
590         void message(docstring const & msg) const;
591
592         ///
593         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
594         ///
595         bool hasGuiDelegate() const;
596
597         
598
599         /// return the format of the buffer on a string
600         std::string bufferFormat() const;
601         /// return the default output format of the current backend
602         std::string getDefaultOutputFormat() const;
603
604         ///
605         bool doExport(std::string const & format, bool put_in_tempdir,
606                 bool includeall, std::string & result_file) const;
607         ///
608         bool doExport(std::string const & format, bool put_in_tempdir,
609                       bool includeall = false) const;
610         ///
611         bool preview(std::string const & format, bool includeall = false) const;
612         ///
613         bool isExportable(std::string const & format) const;
614         ///
615         std::vector<Format const *> exportableFormats(bool only_viewable) const;
616         ///
617         bool isExportableFormat(std::string const & format) const;
618         /// mark the buffer as busy exporting something, or not
619         void setExportStatus(bool e) const;
620         ///
621         bool isExporting() const;
622
623         ///
624         typedef std::vector<std::pair<Inset *, ParIterator> > References;
625         References & references(docstring const & label);
626         References const & references(docstring const & label) const;
627         void clearReferenceCache() const;
628         void setInsetLabel(docstring const & label, InsetLabel const * il);
629         InsetLabel const * insetLabel(docstring const & label) const;
630
631         /// return a list of all used branches (also in children)
632         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
633
634         /// sets the buffer_ member for every inset in this buffer.
635         // FIXME This really shouldn't be needed, but at the moment it's not
636         // clear how to do it just for the individual pieces we need.
637         void setBuffersForInsets() const;
638         /// Updates screen labels and some other information associated with
639         /// insets and paragraphs. Actually, it's more like a general "recurse
640         /// through the Buffer" routine, that visits all the insets and paragraphs.
641         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
642         /// \param scope: whether to start with the master document or just
643         /// do this one.
644         /// \param output: whether we are preparing for output.
645         void updateBuffer(UpdateScope scope, UpdateType utype) const;
646         /// 
647         void updateBuffer(ParIterator & parit, UpdateType utype) const;
648
649         /// Spellcheck starting from \p from.
650         /// \p from initial position, will then points to the next misspelled
651         ///    word.
652         /// \p to will points to the end of the next misspelled word.
653         /// \p word_lang will contain the found misspelled word.
654         /// \return progress if a new word was found.
655         int spellCheck(DocIterator & from, DocIterator & to,
656                 WordLangTuple & word_lang, docstring_list & suggestions) const;
657         ///
658         void checkChildBuffers();
659
660 private:
661         ///
662         std::vector<std::string> backends() const;
663         ///
664         void getLanguages(std::set<Language const *> &) const;
665         /// Update the list of all bibfiles in use (including bibfiles
666         /// of loaded child documents).
667         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
668         /// Return the list with all bibfiles in use (including bibfiles
669         /// of loaded child documents).
670         support::FileNameList const & 
671                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
672         ///
673         void collectChildren(ListOfBuffers & children, bool grand_children) const;
674
675         
676         /// Use the Pimpl idiom to hide the internals.
677         class Impl;
678         /// The pointer never changes although *pimpl_'s contents may.
679         Impl * const d;
680 };
681
682
683 } // namespace lyx
684
685 #endif