]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
37382e5dffcf48de6da861c325cbe5beebb18ef3
[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 "insets/InsetCode.h"
16
17 #include "support/strfwd.h"
18 #include "support/types.h"
19 #include "support/SignalSlot.h"
20
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BiblioInfo;
28 class BufferParams;
29 class BufferSet;
30 class DocIterator;
31 class docstring_list;
32 class ErrorItem;
33 class ErrorList;
34 class FuncRequest;
35 class Inset;
36 class InsetRef;
37 class InsetLabel;
38 class Font;
39 class Format;
40 class Lexer;
41 class LyXRC;
42 class Text;
43 class LyXVC;
44 class LaTeXFeatures;
45 class Language;
46 class MacroData;
47 class MacroNameSet;
48 class MacroSet;
49 class OutputParams;
50 class Paragraph;
51 class ParConstIterator;
52 class ParIterator;
53 class ParagraphList;
54 class TeXErrors;
55 class TexRow;
56 class TocBackend;
57 class Undo;
58 class WordLangTuple;
59
60 namespace frontend {
61 class GuiBufferDelegate;
62 class WorkAreaManager;
63 }
64
65 namespace support {
66 class FileName;
67 class FileNameList;
68 }
69
70 /** The buffer object.
71  * This is the buffer object. It contains all the informations about
72  * a document loaded into LyX.
73  * The buffer object owns the Text (wrapped in an InsetText), which
74  * contains the individual paragraphs of the document.
75  *
76  *
77  * I am not sure if the class is complete or
78  * minimal, probably not.
79  * \author Lars Gullik Bjønnes
80  */
81 class Buffer {
82 public:
83         /// What type of log will \c getLogName() return?
84         enum LogType {
85                 latexlog, ///< LaTeX log
86                 buildlog  ///< Literate build log
87         };
88
89         /// Result of \c readFile()
90         enum ReadStatus {
91                 failure, ///< The file could not be read
92                 success, ///< The file could not be read
93                 wrongversion ///< The version of the file does not match ours
94         };
95
96
97         /// Method to check if a file is externally modified, used by
98         /// isExternallyModified()
99         /**
100          * timestamp is fast but inaccurate. For example, the granularity
101          * of timestamp on a FAT filesystem is 2 second. Also, various operations
102          * may touch the timestamp of a file even when its content is unchanged.
103          *
104          * checksum is accurate but slow, which can be a problem when it is
105          * frequently used, or used for a large file on a slow (network) file
106          * system.
107          *
108          * FIXME: replace this method with support/FileMonitor.
109          */
110         enum CheckMethod {
111                 checksum_method,  ///< Use file checksum
112                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
113         };
114
115         ///
116         enum UpdateScope {
117                 UpdateMaster,
118                 UpdateChildOnly
119         };
120
121         /// Constructor
122         explicit Buffer(std::string const & file, bool b = false);
123
124         /// Destructor
125         ~Buffer();
126
127         /** High-level interface to buffer functionality.
128             This function parses a command string and executes it
129         */
130         bool dispatch(std::string const & command, bool * result = 0);
131
132         /// Maybe we know the function already by number...
133         bool dispatch(FuncRequest const & func, bool * result = 0);
134
135         /// read a new document from a string
136         bool readString(std::string const &);
137         /// load a new file
138         bool readFile(support::FileName const & filename);
139
140         /// read the header, returns number of unknown tokens
141         int readHeader(Lexer & lex);
142
143         /** Reads a file without header.
144             \param par if != 0 insert the file.
145             \return \c true if file is not completely read.
146         */
147         bool readDocument(Lexer &);
148
149         ///
150         void insertStringAsLines(ParagraphList & plist,
151                 pit_type &, pos_type &,
152                 Font const &, docstring const &, bool);
153         ///
154         DocIterator getParFromID(int id) const;
155         /// do we have a paragraph with this id?
156         bool hasParWithID(int id) const;
157
158         ///
159         frontend::WorkAreaManager & workAreaManager() const;
160
161         /** Save file.
162             Takes care of auto-save files and backup file if requested.
163             Returns \c true if the save is successful, \c false otherwise.
164         */
165         bool save() const;
166
167         /// Write document to stream. Returns \c false if unsuccesful.
168         bool write(std::ostream &) const;
169         /// Write file. Returns \c false if unsuccesful.
170         bool writeFile(support::FileName const &) const;
171
172         /// Loads LyX file \c filename into buffer, *  and \return success
173         bool loadLyXFile(support::FileName const & s);
174
175         /// Fill in the ErrorList with the TeXErrors
176         void bufferErrors(TeXErrors const &, ErrorList &) const;
177
178         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
179         bool makeLaTeXFile(support::FileName const & filename,
180                            std::string const & original_path,
181                            OutputParams const &,
182                            bool output_preamble = true,
183                            bool output_body = true) const;
184         /** Export the buffer to LaTeX.
185             If \p os is a file stream, and params().inputenc is "auto" or
186             "default", and the buffer contains text in different languages
187             with more than one encoding, then this method will change the
188             encoding associated to \p os. Therefore you must not call this
189             method with a string stream if the output is supposed to go to a
190             file. \code
191             ofdocstream ofs;
192             ofs.open("test.tex");
193             writeLaTeXSource(ofs, ...);
194             ofs.close();
195             \endcode is NOT equivalent to \code
196             odocstringstream oss;
197             writeLaTeXSource(oss, ...);
198             ofdocstream ofs;
199             ofs.open("test.tex");
200             ofs << oss.str();
201             ofs.close();
202             \endcode
203          */
204         void writeLaTeXSource(odocstream & os,
205                            std::string const & original_path,
206                            OutputParams const &,
207                            bool output_preamble = true,
208                            bool output_body = true) const;
209         ///
210         void makeDocBookFile(support::FileName const & filename,
211                              OutputParams const & runparams_in,
212                              bool only_body = false) const;
213         ///
214         void writeDocBookSource(odocstream & os, std::string const & filename,
215                              OutputParams const & runparams_in,
216                              bool only_body = false) const;
217         /// returns the main language for the buffer (document)
218         Language const * language() const;
219         /// get l10n translated to the buffers language
220         docstring const B_(std::string const & l10n) const;
221
222         ///
223         int runChktex();
224         /// return true if the main lyx file does not need saving
225         bool isClean() const;
226         ///
227         bool isBakClean() const;
228         ///
229         bool isDepClean(std::string const & name) const;
230
231         /// whether or not disk file has been externally modified
232         bool isExternallyModified(CheckMethod method) const;
233
234         /// save timestamp and checksum of the given file.
235         void saveCheckSum(support::FileName const & file) const;
236
237         /// mark the main lyx file as not needing saving
238         void markClean() const;
239
240         ///
241         void markBakClean() const;
242
243         ///
244         void markDepClean(std::string const & name);
245
246         ///
247         void setUnnamed(bool flag = true);
248
249         ///
250         bool isUnnamed() const;
251
252         /// Mark this buffer as dirty.
253         void markDirty();
254
255         /// Returns the buffer's filename. It is always an absolute path.
256         support::FileName fileName() const;
257
258         /// Returns the buffer's filename. It is always an absolute path.
259         std::string absFileName() const;
260
261         /// Returns the the path where the buffer lives.
262         /// It is always an absolute path.
263         std::string filePath() const;
264
265         /** A transformed version of the file name, adequate for LaTeX.
266             \param no_path optional if \c true then the path is stripped.
267         */
268         std::string latexName(bool no_path = true) const;
269
270         /// Get thee name and type of the log.
271         std::string logName(LogType * type = 0) const;
272
273         /// Change name of buffer. Updates "read-only" flag.
274         void setFileName(std::string const & newfile);
275
276         /// Set document's parent Buffer.
277         void setParent(Buffer const *);
278         Buffer const * parent() const;
279
280         // Collect all relative buffer
281         std::vector<Buffer const *> allRelatives() const;
282
283         /** Get the document's master (or \c this if this is not a
284             child document)
285          */
286         Buffer const * masterBuffer() const;
287
288         /// \return true if \p child is a child of this \c Buffer.
289         bool isChild(Buffer * child) const;
290         
291         /// return a vector with all children and grandchildren
292         std::vector<Buffer *> getChildren() const;
293
294         /// Is buffer read-only?
295         bool isReadonly() const;
296
297         /// Set buffer read-only flag
298         void setReadonly(bool flag = true);
299
300         /// returns \c true if the buffer contains a LaTeX document
301         bool isLatex() const;
302         /// returns \c true if the buffer contains a DocBook document
303         bool isDocBook() const;
304         /// returns \c true if the buffer contains a Wed document
305         bool isLiterate() const;
306
307         /** Validate a buffer for LaTeX.
308             This validates the buffer, and returns a struct for use by
309             #makeLaTeX# and others. Its main use is to figure out what
310             commands and packages need to be included in the LaTeX file.
311             It (should) also check that the needed constructs are there
312             (i.e. that the \refs points to coresponding \labels). It
313             should perhaps inset "error" insets to help the user correct
314             obvious mistakes.
315         */
316         void validate(LaTeXFeatures &) const;
317
318         /// Update the cache with all bibfiles in use (including bibfiles
319         /// of loaded child documents).
320         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
321         ///
322         void invalidateBibinfoCache();
323         /// Return the cache with all bibfiles in use (including bibfiles
324         /// of loaded child documents).
325         support::FileNameList const & 
326                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
327         /// \return the bibliography information for this buffer's master,
328         /// or just for it, if it isn't a child.
329         BiblioInfo const & masterBibInfo() const;
330         /// \return the bibliography information for this buffer ONLY.
331         BiblioInfo const & localBibInfo() const;
332         ///
333         void getLabelList(std::vector<docstring> &) const;
334
335         ///
336         void changeLanguage(Language const * from, Language const * to);
337
338         ///
339         bool isMultiLingual() const;
340
341         ///
342         BufferParams & params();
343         BufferParams const & params() const;
344
345         /** The list of paragraphs.
346             This is a linked list of paragraph, this list holds the
347             whole contents of the document.
348          */
349         ParagraphList & paragraphs();
350         ParagraphList const & paragraphs() const;
351
352         /// LyX version control object.
353         LyXVC & lyxvc();
354         LyXVC const & lyxvc() const;
355
356         /// Where to put temporary files.
357         std::string const temppath() const;
358
359         /// Used when typesetting to place errorboxes.
360         TexRow const & texrow() const;
361         TexRow & texrow();
362
363         ///
364         ParIterator par_iterator_begin();
365         ///
366         ParConstIterator par_iterator_begin() const;
367         ///
368         ParIterator par_iterator_end();
369         ///
370         ParConstIterator par_iterator_end() const;
371
372         // Position of the child buffer where it appears first in the master.
373         DocIterator firstChildPosition(Buffer const * child);
374
375         /** \returns true only when the file is fully loaded.
376          *  Used to prevent the premature generation of previews
377          *  and by the citation inset.
378          */
379         bool isFullyLoaded() const;
380         /// Set by buffer_funcs' newFile.
381         void setFullyLoaded(bool);
382
383         /// Our main text (inside the top InsetText)
384         Text & text() const;
385
386         /// Our top InsetText
387         Inset & inset() const;
388
389         //
390         // Macro handling
391         //
392         /// Collect macro definitions in paragraphs
393         void updateMacros() const;
394         /// Iterate through the whole buffer and try to resolve macros
395         void updateMacroInstances() const;
396
397         /// List macro names of this buffer, the parent and the children
398         void listMacroNames(MacroNameSet & macros) const;
399         /// Collect macros of the parent and its children in front of this buffer.
400         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
401
402         /// Return macro defined before pos (or in the master buffer)
403         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
404         /// Return macro defined anywhere in the buffer (or in the master buffer)
405         MacroData const * getMacro(docstring const & name, bool global = true) const;
406         /// Return macro defined before the inclusion of the child
407         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
408
409         /// Replace the inset contents for insets which InsetCode is equal
410         /// to the passed \p inset_code.
411         void changeRefsIfUnique(docstring const & from, docstring const & to,
412                 InsetCode code);
413
414         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
415         /// including preamble
416         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
417                 bool full_source) const;
418
419         /// Access to error list.
420         /// This method is used only for GUI visualisation of Buffer related
421         /// errors (like parsing or LateX compilation). This method is const
422         /// because modifying the returned ErrorList does not touch the document
423         /// contents.
424         ErrorList & errorList(std::string const & type) const;
425
426         /// The Toc backend.
427         /// This is useful only for screen visualisation of the Buffer. This
428         /// method is const because modifying this backend does not touch
429         /// the document contents.
430         TocBackend & tocBackend() const;
431
432         ///
433         Undo & undo();
434
435         /// This function is called when the buffer is changed.
436         void changed() const;
437         ///
438         void updateTocItem(std::string const &, DocIterator const &) const;
439         /// This function is called when the buffer structure is changed.
440         void structureChanged() const;
441         /// This function is called when some parsing error shows up.
442         void errors(std::string const & err) const;
443         /// This function is called when the buffer busy status change.
444         void setBusy(bool on) const;
445         /// This function is called when the buffer readonly status change.
446         void setReadOnly(bool on) const;
447         /// Update window titles of all users.
448         void updateTitles() const;
449         /// Reset autosave timers for all users.
450         void resetAutosaveTimers() const;
451         ///
452         void message(docstring const & msg) const;
453
454         ///
455         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
456         ///
457         bool hasGuiDelegate() const;
458
459         ///
460         void autoSave() const;
461         ///
462         void removeAutosaveFile() const;
463
464         /// return the format of the buffer on a string
465         std::string bufferFormat() const;
466
467         ///
468         bool doExport(std::string const & format, bool put_in_tempdir,
469                 std::string & result_file) const;
470         ///
471         bool doExport(std::string const & format, bool put_in_tempdir) const;
472         ///
473         bool preview(std::string const & format) const;
474         ///
475         bool isExportable(std::string const & format) const;
476         ///
477         std::vector<Format const *> exportableFormats(bool only_viewable) const;
478
479         ///
480         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
481         References & references(docstring const & label);
482         References const & references(docstring const & label) const;
483         void clearReferenceCache() const;
484         void setInsetLabel(docstring const & label, InsetLabel const * il);
485         InsetLabel const * insetLabel(docstring const & label) const;
486
487         /// sets the buffer_ member for every inset in this buffer.
488         // FIXME This really shouldn't be needed, but at the moment it's not
489         // clear how to do it just for the individual pieces we need.
490         void setBuffersForInsets() const;
491         ///
492         void updateLabels(UpdateScope = UpdateMaster) const;
493         ///
494         void updateLabels(ParIterator & parit) const;
495
496         /// Find next word starting from \p from.
497         /// \p from initial position to search, will then points to the next
498         ///    word.
499         /// \p to will points to the end of the next word.
500         /// \p word will contain the found word if any.
501         /// \return true if a new word was found.
502         bool nextWord(DocIterator & from, DocIterator & to,
503                 docstring & word) const;
504
505         int spellCheck(DocIterator & from, DocIterator & to,
506                 WordLangTuple & word_lang, docstring_list & suggestions) const;
507
508 private:
509         /// search for macro in local (buffer) table or in children
510         MacroData const * getBufferMacro(docstring const & name,
511                                          DocIterator const & pos) const;
512         /** Update macro table starting with position of it
513             \param it in some text inset
514         */
515         void updateMacros(DocIterator & it,
516                                      DocIterator & scope) const;
517
518         ///
519         void collectRelatives(BufferSet & bufs) const;
520
521         ///
522         bool readFileHelper(support::FileName const & s);
523         ///
524         std::vector<std::string> backends() const;
525         /** Inserts a file into a document
526             \return \c false if method fails.
527         */
528         ReadStatus readFile(Lexer &, support::FileName const & filename,
529                             bool fromString = false);
530         ///
531         support::FileName getAutosaveFilename() const;
532
533         /// Use the Pimpl idiom to hide the internals.
534         class Impl;
535         /// The pointer never changes although *pimpl_'s contents may.
536         Impl * const d;
537
538         frontend::GuiBufferDelegate * gui_;
539
540         /// This function is called when the buffer structure is changed.
541         Signal structureChanged_;
542         /// This function is called when some parsing error shows up.
543         //Signal errors(std::string const &) = 0;
544         /// This function is called when some message shows up.
545         //Signal message(docstring const &) = 0;
546         /// This function is called when the buffer busy status change.
547         //Signal setBusy(bool) = 0;
548         /// Reset autosave timers for all users.
549         Signal resetAutosaveTimers_;
550 };
551
552
553 } // namespace lyx
554
555 #endif