From 3bd25acd82d2fbfff7a00c7cb3b6871155ebed6b Mon Sep 17 00:00:00 2001 From: Aleksandr Glotov Date: Sun, 19 Nov 2023 23:50:17 +0100 Subject: [PATCH 01/10] =?UTF-8?q?-=20Updated=20script=20to=20work=20with?= =?UTF-8?q?=20Steam=20version=20-=20Added=20support=20of=20screens:=20=20?= =?UTF-8?q?=20=20=20-=20Unit/Health/Description=20=20=20=20=20-=20Unit/Per?= =?UTF-8?q?sonality/Traits=20=20=20=20=20-=20Item/Description=20-=20Added?= =?UTF-8?q?=20name,=20age=20&=20profession=20of=20units=20to=20description?= =?UTF-8?q?=20-=20Refactored=20the=20code=20-=20By=20default,=20file=20nam?= =?UTF-8?q?e=20is=20now=20=E2=80=9Cmarkdown=5F/worldName/=5Fexport.md?= =?UTF-8?q?=E2=80=9D=20-=20Improved=20markdown=20formatting=20-=20Removed?= =?UTF-8?q?=20code=20for=20unsupported=20screens?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- markdown.lua | 316 +++++++++++++++++++++++---------------------------- 1 file changed, 140 insertions(+), 176 deletions(-) diff --git a/markdown.lua b/markdown.lua index 5ca9f03749..46c834fde9 100644 --- a/markdown.lua +++ b/markdown.lua @@ -1,227 +1,191 @@ --- Save a text screen in markdown (eg for reddit) +-- Save selected unit/item' description in markdown (e.g., for reddit) +-- This script extracts descriptions of selected units or items and saves them in markdown format. -- This is a derivatiwe work based upon scripts/forum-dwarves.lua by Caldfir and expwnent -- Adapted for markdown by Mchl https://github.com/Mchl +-- Updated to work with Steam version by Glotov4 https://github.com/glotov4 + local helpstr = [====[ markdown -======== -Save a copy of a text screen in markdown (useful for Reddit, among other sites). -See `forum-dwarves` for BBCode export (for e.g. the Bay12 Forums). +=========== +Tags: fort | inspection | units + +Save a description of selected unit or item to a markdown file. + +This script will attempt to get description of selected unit or item. +For units, script will collect: +- Name, race, age, profession +- Description, as seen at the Unit/Health/Description screen +- Traits, as seen at the Unit/Personality/Traits + +For items: +- Decorated name ("☼«☼Chalk Statue of Dakas☼»☼") +- Full description, as seen when clicking "View this item's sheet" + +Then the script will append marked-down version of this data +to the target file (for easy pasting on reddit for example). + +This script doesn't work with the data from other screens. -This script will attempt to read the current df-screen, and if it is a -text-viewscreen (such as the dwarf 'thoughts' screen or an item / creature -'description') or an announcement list screen (such as announcements and -combat reports) then append a marked-down version of this text to the -target file (for easy pasting on reddit for example). Previous entries in the file are not overwritten, so you -may use the``markdown`` command multiple times to create a single -document containing the text from multiple screens (eg: text screens -from several dwarves, or text screens from multiple artifacts/items, -or some combination). +may use the ``markdown`` command multiple times to create a single +document containing the description of multiple items & units. -Usage:: +By default, data is stored in markdown_/YourWorldName/_export.md + +See `forum-dwarves` for BBCode export (for e.g. the Bay12 Forums). + +Usage +----- markdown [-n] [filename] :-n: overwrites contents of output file :filename: - if provided, save to :file:`md_{filename}.md` instead - of the default :file:`md_export.md` + if provided, save to :file:`markdown_{filename}.md` instead + of the default :file:`markdown_/worldName/_export.md` +:help: show help + +Examples +----- + +### -chalk statue of Bìlalo Bandbeach- + +#### Description: +This is a well-crafted chalk statue of Bìlalo Bandbeach. The item is a well-designed image of Bìlalo Bandbeach the elf and Lani Lyricmonks the Learned the ettin in chalk by Domas Uthmiklikot. Lani Lyricmonks the Learned is striking down Bìlalo Bandbeach. The artwork relates to the killing of the elf Bìlalo Bandbeach by the ettin Lani Lyricmonks the Learned with Hailbite in The Forest of Indignation in 147. -The screens which have been tested and known to function properly with -this script are: +--- -#. dwarf/unit 'thoughts' screen -#. item/art 'description' screen -#. individual 'historical item/figure' screens -#. manual -#. announements screen -#. combat reports screen -#. latest news (when meeting with liaison) +### Lokum Alnisendok, dwarf, 27 years old Presser. -There may be other screens to which the script applies. It should be -safe to attempt running the script with any screen active, with an -error message to inform you when the selected screen is not appropriate -for this script. +#### Description: +A short, sturdy creature fond of drink and industry. +He is very quick to tire. + +His very long beard is neatly combed. His very long sideburns are braided. His very long moustache is neatly combed. His hair is clean-shaven. He is average in size. His nose is sharply hooked. His nose bridge is convex. His gold eyes are slightly wide-set. His somewhat tall ears are somewhat narrow. His hair is copper. His skin is copper. + +#### Personality: +He has an amazing memory, but he has a questionable spatial sense and poor focus. + +He doesn't generally think before acting. He feels a strong need to reciprocate any favor done for him. He enjoys the company of others. He does not easily hate or develop negative feelings. He generally finds himself quite hopeful about the future. He tends to be swayed by the emotions of others. He finds obligations confining, though he is conflicted by this for more than one reason. He doesn't tend to hold on to grievances. He has an active imagination. + +He needs alcohol to get through the working day. + +--- ]====] -local args = {...} +local utils = require('utils') +local gui = require('gui') +-- Argument processing +local args = {...} if args[1] == 'help' then print(helpstr) return end -local writemode = 'a' +-- Determine file write mode and filename +local writemode = 'a' -- append (default) +local filename +local worldName = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name)):gsub(" ", "_") --- check if we want to append to an existing file (default) or overwrite previous contents if args[1] == '-n' or args[1] == '/n' then - writemode = 'w' + writemode = 'w' -- overwrite table.remove(args, 1) end -local filename - if args[1] ~= nil then - filename = 'md_' .. table.remove(args, 1) .. '.md' + filename = 'markdown_' .. table.remove(args, 1) .. '.md' else - filename = 'md_export.md' + filename = 'markdown_' .. worldName .. '_export.md' end -local utils = require 'utils' -local gui = require 'gui' -local dialog = require 'gui.dialogs' - -local scrn = dfhack.gui.getCurViewscreen() -local flerb = dfhack.gui.getFocusString(scrn) - -local months = { - [1] = 'Granite', - [2] = 'Slate', - [3] = 'Felsite', - [4] = 'Hematite', - [5] = 'Malachite', - [6] = 'Galena', - [7] = 'Limestone', - [8] = 'Sandstone', - [9] = 'Timber', - [10] = 'Moonstone', - [11] = 'Opal', - [12] = 'Obsidian', -} - +-- Utility functions local function getFileHandle() - return io.open(filename, writemode) + return assert(io.open(filename, writemode), "Error opening file: " .. filename) end local function closeFileHandle(handle) - handle:write('\n***\n\n') + handle:write('\n---\n\n') handle:close() - print ('Data exported to "' .. filename .. '"') + print ('\nData exported to "' .. filename .. '"') end -local function reformat(strin) - local strout = strin - - -- [P] tags seem to indicate a new paragraph - local newline_idx = string.find(strout, '[P]', 1, true) - while newline_idx ~= nil do - strout = string.sub(strout, 1, newline_idx - 1) .. '\n***\n\n' .. string.sub(strout, newline_idx + 3) - newline_idx = string.find(strout, '[P]', 1, true) - end - - -- [R] tags seem to indicate a new 'section'. Let's mark it with a horizontal line. - newline_idx = string.find(strout, '[R]', 1, true) - while newline_idx ~= nil do - strout = string.sub(strout, 1, newline_idx - 1) .. '\n***\n\n' .. string.sub(strout,newline_idx + 3) - newline_idx = string.find(strout, '[R]', 1, true) - end - - -- No idea what [B] tags might indicate. Just removing them seems to work fine - newline_idx = string.find(strout, '[B]', 1, true) - while newline_idx ~= nil do - strout = string.sub(strout, 1, newline_idx - 1) .. string.sub(strout,newline_idx + 3) - newline_idx = string.find(strout, '[B]', 1, true) - end - - -- Reddit doesn't support custom colors in markdown. We need to remove all color information :( - local color_idx = string.find(strout, '[C:', 1, true) - while color_idx ~= nil do - strout = string.sub(strout, 1, color_idx - 1) .. string.sub(strout, color_idx + 9) - color_idx = string.find(strout, '[C:', 1, true) - end - - return strout +local function reformat(str) + -- [B] tags seem to indicate a new paragraph + -- [R] tags seem to indicate a sub-blocks of text.Treat them as paragraphs. + -- [P] tags seem to be redundant + -- [C] tags indicate color. Remove all color information + return str:gsub('%[B%]', '\n\n') + :gsub('%[R%]', '\n\n') + :gsub('%[P%]', '') + :gsub('%[C:%d+:%d+:%d+%]', '') + :gsub('\n\n+', '\n\n') end -local function formattime(year, ticks) - -- Dwarf Mode month is 33600 ticks long - local month = math.floor(ticks / 33600) - local dayRemainder = ticks - month * 33600 - - -- Dwarf Mode day is 1200 ticks long - local day = math.floor(dayRemainder / 1200) - local timeRemainder = dayRemainder - day * 1200 - - -- Assuming a 24h day each Dwarf Mode tick corresponds to 72 seconds - local seconds = timeRemainder * 72 - - local H = string.format("%02.f", math.floor(seconds / 3600)); - local m = string.format("%02.f", math.floor(seconds / 60 - (H * 60))); - local i = string.format("%02.f", math.floor(seconds - H * 3600 - m * 60)); - - day = day + 1 - if (day == 1 or day == 21) then - day = day .. 'st' --luacheck: retype - elseif (day == 2 or day == 22) then - day = day .. 'nd' --luacheck: retype - elseif (day == 3 or day == 23) then - day = day .. 'rd' --luacheck: retype - else - day = day .. 'th' --luacheck: retype - end - - return (day .. " " .. months[month + 1] .. " " .. year .. " " .. H .. ":" .. m..":" .. i) +local function getNameRaceAgeProf(unit) + --%s is a placeholder for a string, and %d is a placeholder for a number. + return string.format("%s, %d years old %s.", dfhack.units.getReadableName(unit), df.global.cur_year - unit.birth_year, dfhack.units.getProfessionName(unit)) end -if flerb == 'textviewer' then - local scrn = scrn --as:df.viewscreen_textviewerst - - local lines = scrn.src_text - - if lines ~= nil then - - local log = getFileHandle() - log:write('### ' .. dfhack.df2utf(scrn.title) .. '\n') +-- Main logic for item and unit processing +local item = dfhack.gui.getSelectedItem(true) +local unit = dfhack.gui.getSelectedUnit(true) - print('Exporting ' .. dfhack.df2console(scrn.title) .. '\n') +if not item and not unit then + print([[ +Error: No unit or item is currently selected. +- To select a unit, click on it. +- For items that are installed as buildings (like statues or beds), +open the building's interface in the game and click the magnifying glass icon. - for n,x in ipairs(lines) do - log:write(reformat(dfhack.df2utf(x.value)).." ") --- debug output --- print(x.value) - end - closeFileHandle(log) - end - -elseif flerb == 'announcelist' then - local scrn = scrn --as:df.viewscreen_announcelistst - - local lines = scrn.reports - - if lines ~= nil then - local log = getFileHandle() - local lastTime = "" - - for n,x in ipairs(lines) do - local currentTime = formattime(x.year, x.time) - if (currentTime ~= lastTime) then - lastTime = currentTime - log:write('\n***\n\n') - log:write('## ' .. currentTime .. '\n') - end --- debug output --- print(x.text) - log:write(x.text .. '\n') - end - closeFileHandle(log) - end - - -elseif flerb == 'topicmeeting' then - local lines = scrn.text --hint:df.viewscreen_topicmeetingst - - if lines ~= nil then - local log = getFileHandle() +Please select a valid target in the game and try running the script again.]]) + -- Early return to avoid proceeding further + return +end - for n,x in ipairs(lines) do --- debug output --- print(x.value) - log:write(x.value .. '\n') +local log = getFileHandle() + +if item then + -- Item processing + local item_raw_name = dfhack.items.getDescription(item, 0, true) + local item_raw_description = df.global.game.main_interface.view_sheets.raw_description + log:write('### ' .. dfhack.df2utf(item_raw_name) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(item_raw_description)) .. '\n') + print('Exporting description of the ' .. item_raw_name) + +elseif unit then + -- Unit processing + -- Simulate UI interactions to load data into memory (click through tabs) + local screen = dfhack.gui.getDFViewscreen() + -- Click "Personality" + df.global.gps.mouse_x = 145 + df.global.gps.mouse_y = 11 + gui.simulateInput(screen, '_MOUSE_L') + + -- Click "Health" + df.global.gps.mouse_x = 118 + df.global.gps.mouse_y = 13 + gui.simulateInput(screen, '_MOUSE_L') + + -- Click "Health/Description" + df.global.gps.mouse_x = 142 + df.global.gps.mouse_y = 15 + gui.simulateInput(screen, '_MOUSE_L') + + local unit_description_raw = df.global.game.main_interface.view_sheets.unit_health_raw_str[0].value + local unit_personality_raw = df.global.game.main_interface.view_sheets.personality_raw_str + + if unit_description_raw or unit_personality_raw then + log:write('### ' .. dfhack.df2utf(getNameRaceAgeProf(unit)) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(unit_description_raw)) .. '\n\n#### Personality: \n') + for _, unit_personality in ipairs(unit_personality_raw) do + log:write(reformat(dfhack.df2utf(unit_personality.value)) .. '\n') end - closeFileHandle(log) + print('Exporting Health/Description & Personality/Traits data for: \n' .. dfhack.df2console(getNameRaceAgeProf(unit))) + else + print("Unit has no data in Description & Personality tabs") end -else - print 'This is not a textview, announcelist or topicmeeting screen. Can\'t export data, sorry.' +else end + +closeFileHandle(log) \ No newline at end of file From acf0692e7f9b4c63c1f1c9dcb7578ffeba096734 Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 18:24:14 +0100 Subject: [PATCH 02/10] - Moved helpstring from ``markdown.lua`` to ``markdown.rst``. - Improved docs --- docs/markdown.rst | 129 ++++++++++++++++++++++++++++++++-------------- markdown.lua | 75 +-------------------------- 2 files changed, 91 insertions(+), 113 deletions(-) diff --git a/docs/markdown.rst b/docs/markdown.rst index bffc5cfba6..98718205af 100644 --- a/docs/markdown.rst +++ b/docs/markdown.rst @@ -2,56 +2,105 @@ markdown ======== .. dfhack-tool:: - :summary: Exports the text you see on the screen for posting online. - :tags: unavailable - -This tool saves a copy of a text screen, formatted in markdown, for posting to -Reddit (among other places). See `forum-dwarves` if you want to export BBCode -for posting to the Bay 12 forums. - -This script will attempt to read the current screen, and if it is a text -viewscreen (such as the dwarf 'thoughts' screen or an item 'description') then -append a marked-down version of this text to the output file. Previous entries -in the file are not overwritten, so you may use the ``markdown`` command -multiple times to create a single document containing the text from multiple -screens, like thoughts from several dwarves or descriptions from multiple -artifacts. - -The screens which have been tested and known to function properly with this -script are: - -#. dwarf/unit 'thoughts' screen -#. item/art 'description' screen -#. individual 'historical item/figure' screens -#. manual pages -#. announcements screen -#. combat reports screen -#. latest news (when meeting with liaison) - -There may be other screens to which the script applies. It should be safe to -attempt running the script with any screen active. An error message will inform -you when the selected screen is not appropriate for this script. + :summary: Save descriptions of selected units/items in markdown format (e.g., for Reddit). + :tags: fort | inspection | units + +Saves descriptions of selected units or items to a markdown file. + + +For units, the script retrieves: +- Name, race, age, profession +- Description from the Unit/Health/Description screen +- Traits from the Unit/Personality/Traits screen +It works for all units with text in the Description &/or Personality/Traits tabs, +such as dwarves, dogs, elves, goblins, and beasts. + +For items, it retrieves: +- Decorated name (e.g., "☼«☼Chalk Statue of Dakas☼»☼") +- Full description from the item's view sheet +It works for most items with in-game descriptions and names, including those in storage, +on the ground, installed as a building, or worn/carried by units. + +The script appends a markdown-formatted version of the text to a target file +for easy sharing, e.g., on Reddit. + +By default, entries are appended, not overwritten, allowing the ``markdown`` command +to compile descriptions of multiple items & units in a single document. + +By default, data is stored in markdown_{YourWorldName}_export.md. + +See `forum-dwarves` for BBCode export (e.g., for the Bay12 Forums). + Usage ----- :: - markdown [-n] [] + markdown [-o] [] + +Appends the description of the selected unit/item +to ``markdown_{world_name}_export.md`` file by default. +Specifying a filename will append to ``markdown_{filename}.md`` instead, +which is useful for organizing data by category or topic. +The [-o] argument tells the script to overwrite the output file. + +Options +------- -The output is appended to the ``md_export.md`` file by default. If an alternate -name is specified, then a file named like ``md_{name}.md`` is used instead. +``-o`` + Overwrite the output file, deleting previous entries. +``help`` + Show help. Examples -------- -``markdown`` - Appends the contents of the current screen to the ``md_export.md`` file. -``markdown artifacts`` - Appends the contents of the current screen to the ``md_artifacts.md`` file. +:: -Options -------- + ``markdown`` + Appends the description of the selected unit/item + to the default ``markdown_{world_name}_export.md``. + The script trims in-game world names, replacing spaces with underscores. + +Example output for a selected chalk statue in the world "Orid Tamun", +appended to the default ``markdown_Orid_Tamun_export.md`` file: + + [...previous entries...] + + ### ☼Chalk Statue of Bìlalo Bandbeach☼ + + #### Description: + This is a well-crafted chalk statue of Bìlalo Bandbeach. The item is an image of + Bìlalo Bandbeach the elf and Lani Lyricmonks the Learned the ettin in chalk by + Domas Uthmiklikot. Lani Lyricmonks the Learned is striking down Bìlalo Bandbeach. + The artwork relates to the killing of the elf Bìlalo Bandbeach by the + ettin Lani Lyricmonks the Learned with Hailbite in The Forest of Indignation in 147. + + --- +:: + + ``markdown -n descriptions`` + Writes the description of the selected unit/item + to the ``markdown_descriptions.md`` file instead of the default. + +Example output for a selected unit Lokum Alnisendok, appended to the + ``markdown_descriptions.md`` file:: + + ### Lokum Alnisendok, dwarf, 27 years old Presser. + + #### Description: + A short, sturdy creature fond of drink and industry. + + He is very quick to tire. + + His very long beard is neatly combed. His very long sideburns are braided. His very long moustache is neatly combed. His hair is clean-shaven. He is average in size. His nose is sharply hooked. His nose bridge is convex. His gold eyes are slightly wide-set. His somewhat tall ears are somewhat narrow. His hair is copper. His skin is copper. + + #### Personality: + He has an amazing memory, but he has a questionable spatial sense and poor focus. + + He doesn't generally think before acting. He feels a strong need to reciprocate any favor done for him. He enjoys the company of others. He does not easily hate or develop negative feelings. He generally finds himself quite hopeful about the future. He tends to be swayed by the emotions of others. He finds obligations confining, though he is conflicted by this for more than one reason. He doesn't tend to hold on to grievances. He has an active imagination. + + He needs alcohol to get through the working day. -``-n`` - Overwrite the contents of output file instead of appending. + --- \ No newline at end of file diff --git a/markdown.lua b/markdown.lua index 46c834fde9..ff3baf51c8 100644 --- a/markdown.lua +++ b/markdown.lua @@ -4,84 +4,13 @@ -- Adapted for markdown by Mchl https://github.com/Mchl -- Updated to work with Steam version by Glotov4 https://github.com/glotov4 -local helpstr = [====[ - -markdown -=========== -Tags: fort | inspection | units - -Save a description of selected unit or item to a markdown file. - -This script will attempt to get description of selected unit or item. -For units, script will collect: -- Name, race, age, profession -- Description, as seen at the Unit/Health/Description screen -- Traits, as seen at the Unit/Personality/Traits - -For items: -- Decorated name ("☼«☼Chalk Statue of Dakas☼»☼") -- Full description, as seen when clicking "View this item's sheet" - -Then the script will append marked-down version of this data -to the target file (for easy pasting on reddit for example). - -This script doesn't work with the data from other screens. - -Previous entries in the file are not overwritten, so you -may use the ``markdown`` command multiple times to create a single -document containing the description of multiple items & units. - -By default, data is stored in markdown_/YourWorldName/_export.md - -See `forum-dwarves` for BBCode export (for e.g. the Bay12 Forums). - -Usage ------ - - markdown [-n] [filename] - -:-n: overwrites contents of output file -:filename: - if provided, save to :file:`markdown_{filename}.md` instead - of the default :file:`markdown_/worldName/_export.md` -:help: show help - -Examples ------ - -### -chalk statue of Bìlalo Bandbeach- - -#### Description: -This is a well-crafted chalk statue of Bìlalo Bandbeach. The item is a well-designed image of Bìlalo Bandbeach the elf and Lani Lyricmonks the Learned the ettin in chalk by Domas Uthmiklikot. Lani Lyricmonks the Learned is striking down Bìlalo Bandbeach. The artwork relates to the killing of the elf Bìlalo Bandbeach by the ettin Lani Lyricmonks the Learned with Hailbite in The Forest of Indignation in 147. - ---- - -### Lokum Alnisendok, dwarf, 27 years old Presser. - -#### Description: -A short, sturdy creature fond of drink and industry. - -He is very quick to tire. - -His very long beard is neatly combed. His very long sideburns are braided. His very long moustache is neatly combed. His hair is clean-shaven. He is average in size. His nose is sharply hooked. His nose bridge is convex. His gold eyes are slightly wide-set. His somewhat tall ears are somewhat narrow. His hair is copper. His skin is copper. - -#### Personality: -He has an amazing memory, but he has a questionable spatial sense and poor focus. - -He doesn't generally think before acting. He feels a strong need to reciprocate any favor done for him. He enjoys the company of others. He does not easily hate or develop negative feelings. He generally finds himself quite hopeful about the future. He tends to be swayed by the emotions of others. He finds obligations confining, though he is conflicted by this for more than one reason. He doesn't tend to hold on to grievances. He has an active imagination. - -He needs alcohol to get through the working day. - ---- -]====] - local utils = require('utils') local gui = require('gui') -- Argument processing local args = {...} if args[1] == 'help' then - print(helpstr) + print(dfhack.script_help()) return end @@ -90,7 +19,7 @@ local writemode = 'a' -- append (default) local filename local worldName = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name)):gsub(" ", "_") -if args[1] == '-n' or args[1] == '/n' then +if args[1] == '-o' or args[1] == '/n' then writemode = 'w' -- overwrite table.remove(args, 1) end From d1874e95ba68fecab96a996177fbff18e3a09437 Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 18:25:38 +0100 Subject: [PATCH 03/10] - Updated docs to reflect replacement of "-n" argument with "-o" argument for overwrite operation --- docs/markdown.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/markdown.rst b/docs/markdown.rst index 98718205af..72ca08feb3 100644 --- a/docs/markdown.rst +++ b/docs/markdown.rst @@ -80,7 +80,7 @@ appended to the default ``markdown_Orid_Tamun_export.md`` file: --- :: - ``markdown -n descriptions`` + ``markdown -o descriptions`` Writes the description of the selected unit/item to the ``markdown_descriptions.md`` file instead of the default. From 701af5f1c02d0cc4f46c47d47f0252e129737bb0 Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 19:01:58 +0100 Subject: [PATCH 04/10] - Clicks on tabs now use relative coordinates - Replacing whitespaces from user input with underscores - Removed redundant check "if unit or item" --- markdown.lua | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/markdown.lua b/markdown.lua index ff3baf51c8..a55acdc27f 100644 --- a/markdown.lua +++ b/markdown.lua @@ -25,7 +25,9 @@ if args[1] == '-o' or args[1] == '/n' then end if args[1] ~= nil then - filename = 'markdown_' .. table.remove(args, 1) .. '.md' + local userProvidedName = table.remove(args, 1) + userProvidedName = string.gsub(userProvidedName, " ", "_") + filename = 'markdown_' .. userProvidedName .. '.md' else filename = 'markdown_' .. worldName .. '_export.md' end @@ -105,16 +107,9 @@ elseif unit then local unit_description_raw = df.global.game.main_interface.view_sheets.unit_health_raw_str[0].value local unit_personality_raw = df.global.game.main_interface.view_sheets.personality_raw_str - if unit_description_raw or unit_personality_raw then log:write('### ' .. dfhack.df2utf(getNameRaceAgeProf(unit)) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(unit_description_raw)) .. '\n\n#### Personality: \n') for _, unit_personality in ipairs(unit_personality_raw) do log:write(reformat(dfhack.df2utf(unit_personality.value)) .. '\n') - end print('Exporting Health/Description & Personality/Traits data for: \n' .. dfhack.df2console(getNameRaceAgeProf(unit))) - else - print("Unit has no data in Description & Personality tabs") - end -else -end - +else end closeFileHandle(log) \ No newline at end of file From 4c3bbcb5f88b34d1efc6be0f4479f39476d15dcb Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 19:13:02 +0100 Subject: [PATCH 05/10] - Improved the formatting of the docs file --- docs/markdown.rst | 15 ++++------- markdown.lua | 66 +++++++++++++++++++++++++++++------------------ 2 files changed, 46 insertions(+), 35 deletions(-) diff --git a/docs/markdown.rst b/docs/markdown.rst index 72ca08feb3..86b7390519 100644 --- a/docs/markdown.rst +++ b/docs/markdown.rst @@ -58,12 +58,9 @@ Examples :: - ``markdown`` - Appends the description of the selected unit/item - to the default ``markdown_{world_name}_export.md``. - The script trims in-game world names, replacing spaces with underscores. + markdown -Example output for a selected chalk statue in the world "Orid Tamun", +#### Example output for a selected chalk statue in the world "Orid Tamun", appended to the default ``markdown_Orid_Tamun_export.md`` file: [...previous entries...] @@ -81,11 +78,9 @@ appended to the default ``markdown_Orid_Tamun_export.md`` file: :: ``markdown -o descriptions`` - Writes the description of the selected unit/item - to the ``markdown_descriptions.md`` file instead of the default. - -Example output for a selected unit Lokum Alnisendok, appended to the - ``markdown_descriptions.md`` file:: + +#### Example output for a selected unit Lokum Alnisendok, appended to the ``markdown_descriptions.md`` file +:: ### Lokum Alnisendok, dwarf, 27 years old Presser. diff --git a/markdown.lua b/markdown.lua index a55acdc27f..ee6d5aedb5 100644 --- a/markdown.lua +++ b/markdown.lua @@ -9,15 +9,18 @@ local gui = require('gui') -- Argument processing local args = {...} -if args[1] == 'help' then - print(dfhack.script_help()) - return +if args[1] ~= nil then + local userProvidedName = table.remove(args, 1) + userProvidedName = string.gsub(userProvidedName, " ", "_") + filename = 'markdown_' .. userProvidedName .. '.md' +else + filename = 'markdown_' .. worldName .. '_export.md' end -- Determine file write mode and filename local writemode = 'a' -- append (default) local filename -local worldName = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name)):gsub(" ", "_") +local worldname = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name)):gsub(" ", "_") if args[1] == '-o' or args[1] == '/n' then writemode = 'w' -- overwrite @@ -25,11 +28,9 @@ if args[1] == '-o' or args[1] == '/n' then end if args[1] ~= nil then - local userProvidedName = table.remove(args, 1) - userProvidedName = string.gsub(userProvidedName, " ", "_") - filename = 'markdown_' .. userProvidedName .. '.md' + filename = 'markdown_' .. table.remove(args, 1) .. '.md' else - filename = 'markdown_' .. worldName .. '_export.md' + filename = 'markdown_' .. worldname .. '_export.md' end -- Utility functions @@ -72,7 +73,7 @@ Error: No unit or item is currently selected. open the building's interface in the game and click the magnifying glass icon. Please select a valid target in the game and try running the script again.]]) - -- Early return to avoid proceeding further + -- Early return to avoid proceeding further if no unit or item is selected return end @@ -80,36 +81,51 @@ local log = getFileHandle() if item then -- Item processing - local item_raw_name = dfhack.items.getDescription(item, 0, true) - local item_raw_description = df.global.game.main_interface.view_sheets.raw_description - log:write('### ' .. dfhack.df2utf(item_raw_name) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(item_raw_description)) .. '\n') - print('Exporting description of the ' .. item_raw_name) + local itemRawName = dfhack.items.getDescription(item, 0, true) + local itemRawDescription = df.global.game.main_interface.view_sheets.raw_description + log:write('### ' .. dfhack.df2utf(itemRawName) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(itemRawDescription)) .. '\n') + print('Exporting description of the ' .. itemRawName) elseif unit then -- Unit processing - -- Simulate UI interactions to load data into memory (click through tabs) + -- Simulate UI interactions to load data into memory (click through tabs). Note: Constant might change with DF updates/patches local screen = dfhack.gui.getDFViewscreen() - -- Click "Personality" - df.global.gps.mouse_x = 145 - df.global.gps.mouse_y = 11 + local windowSize = dfhack.screen.getWindowSize() + + -- Click "Personality" + local personalityWidthConstant = 48 + local personalityHeightConstant = 11 + + df.global.gps.mouse_x = windowSize - personalityWidthConstant + df.global.gps.mouse_y = personalityHeightConstant + gui.simulateInput(screen, '_MOUSE_L') -- Click "Health" - df.global.gps.mouse_x = 118 - df.global.gps.mouse_y = 13 + local healthWidthConstant = 74 + local healthHeightConstant = 13 + + df.global.gps.mouse_x = windowSize - healthWidthConstant + df.global.gps.mouse_y = healthHeightConstant + gui.simulateInput(screen, '_MOUSE_L') -- Click "Health/Description" - df.global.gps.mouse_x = 142 - df.global.gps.mouse_y = 15 + local healthDescriptionWidthConstant = 51 + local healthDescriptionHeightConstant = 15 + + df.global.gps.mouse_x = windowSize - healthDescriptionWidthConstant + df.global.gps.mouse_y = healthDescriptionHeightConstant + gui.simulateInput(screen, '_MOUSE_L') local unit_description_raw = df.global.game.main_interface.view_sheets.unit_health_raw_str[0].value local unit_personality_raw = df.global.game.main_interface.view_sheets.personality_raw_str - log:write('### ' .. dfhack.df2utf(getNameRaceAgeProf(unit)) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(unit_description_raw)) .. '\n\n#### Personality: \n') - for _, unit_personality in ipairs(unit_personality_raw) do - log:write(reformat(dfhack.df2utf(unit_personality.value)) .. '\n') - print('Exporting Health/Description & Personality/Traits data for: \n' .. dfhack.df2console(getNameRaceAgeProf(unit))) + log:write('### ' .. dfhack.df2utf(getNameRaceAgeProf(unit)) .. '\n\n#### Description: \n' .. reformat(dfhack.df2utf(unit_description_raw)) .. '\n\n#### Personality: \n') + for _, unit_personality in ipairs(unit_personality_raw) do + log:write(reformat(dfhack.df2utf(unit_personality.value)) .. '\n') + end + print('Exporting Health/Description & Personality/Traits data for: \n' .. dfhack.df2console(getNameRaceAgeProf(unit))) else end closeFileHandle(log) \ No newline at end of file From af1b1032ac36354a1c8dccdf519bc8a1b3101136 Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 19:19:51 +0100 Subject: [PATCH 06/10] - Fixed a bug with worldName/worldname variable --- docs/markdown.rst | 16 +++++++++++----- markdown.lua | 4 ++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/markdown.rst b/docs/markdown.rst index 86b7390519..668720d294 100644 --- a/docs/markdown.rst +++ b/docs/markdown.rst @@ -60,8 +60,7 @@ Examples markdown -#### Example output for a selected chalk statue in the world "Orid Tamun", -appended to the default ``markdown_Orid_Tamun_export.md`` file: +Example output for a selected chalk statue in the world "Orid Tamun", appended to the default ``markdown_Orid_Tamun_export.md`` file: [...previous entries...] @@ -79,7 +78,7 @@ appended to the default ``markdown_Orid_Tamun_export.md`` file: ``markdown -o descriptions`` -#### Example output for a selected unit Lokum Alnisendok, appended to the ``markdown_descriptions.md`` file +Example output for a selected unit Lokum Alnisendok, written to the newly overwritten ``markdown_descriptions.md`` file: :: ### Lokum Alnisendok, dwarf, 27 years old Presser. @@ -89,12 +88,19 @@ appended to the default ``markdown_Orid_Tamun_export.md`` file: He is very quick to tire. - His very long beard is neatly combed. His very long sideburns are braided. His very long moustache is neatly combed. His hair is clean-shaven. He is average in size. His nose is sharply hooked. His nose bridge is convex. His gold eyes are slightly wide-set. His somewhat tall ears are somewhat narrow. His hair is copper. His skin is copper. + His very long beard is neatly combed. His very long sideburns are braided. + His very long moustache is neatly combed. His hair is clean-shaven. He is average in size. + His nose is sharply hooked. His nose bridge is convex. His gold eyes are slightly wide-set. + His somewhat tall ears are somewhat narrow. His hair is copper. His skin is copper. #### Personality: He has an amazing memory, but he has a questionable spatial sense and poor focus. - He doesn't generally think before acting. He feels a strong need to reciprocate any favor done for him. He enjoys the company of others. He does not easily hate or develop negative feelings. He generally finds himself quite hopeful about the future. He tends to be swayed by the emotions of others. He finds obligations confining, though he is conflicted by this for more than one reason. He doesn't tend to hold on to grievances. He has an active imagination. + He doesn't generally think before acting. He feels a strong need to reciprocate any favor done for him. + He enjoys the company of others. He does not easily hate or develop negative feelings. He generally + finds himself quite hopeful about the future. He tends to be swayed by the emotions of others. + He finds obligations confining, though he is conflicted by this for more than one reason. He doesn't + tend to hold on to grievances. He has an active imagination. He needs alcohol to get through the working day. diff --git a/markdown.lua b/markdown.lua index ee6d5aedb5..c433703b43 100644 --- a/markdown.lua +++ b/markdown.lua @@ -6,6 +6,7 @@ local utils = require('utils') local gui = require('gui') +local worldName = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name)):gsub(" ", "_") -- Argument processing local args = {...} @@ -20,7 +21,6 @@ end -- Determine file write mode and filename local writemode = 'a' -- append (default) local filename -local worldname = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name)):gsub(" ", "_") if args[1] == '-o' or args[1] == '/n' then writemode = 'w' -- overwrite @@ -30,7 +30,7 @@ end if args[1] ~= nil then filename = 'markdown_' .. table.remove(args, 1) .. '.md' else - filename = 'markdown_' .. worldname .. '_export.md' + filename = 'markdown_' .. worldName .. '_export.md' end -- Utility functions From 49dea76253d46cdbd32c7df37cdc1b862d1a4c2c Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 19:21:02 +0100 Subject: [PATCH 07/10] - Minor text changes --- markdown.lua | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/markdown.lua b/markdown.lua index c433703b43..2ad099c268 100644 --- a/markdown.lua +++ b/markdown.lua @@ -70,9 +70,9 @@ if not item and not unit then Error: No unit or item is currently selected. - To select a unit, click on it. - For items that are installed as buildings (like statues or beds), -open the building's interface in the game and click the magnifying glass icon. +open the building's interface and click the magnifying glass icon. -Please select a valid target in the game and try running the script again.]]) +Please select a valid target and try running the script again.]]) -- Early return to avoid proceeding further if no unit or item is selected return end From c032570537697b338d2ae50e2a5b5dedf3049f7e Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 19:34:39 +0100 Subject: [PATCH 08/10] - Fixed the processing of custom filenames - Option "-o" now can be passed before or after filename - Formatted the docs --- docs/markdown.rst | 14 +++++++------- markdown.lua | 31 +++++++++++++++---------------- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/docs/markdown.rst b/docs/markdown.rst index 668720d294..94a764b284 100644 --- a/docs/markdown.rst +++ b/docs/markdown.rst @@ -9,16 +9,16 @@ Saves descriptions of selected units or items to a markdown file. For units, the script retrieves: -- Name, race, age, profession -- Description from the Unit/Health/Description screen -- Traits from the Unit/Personality/Traits screen -It works for all units with text in the Description &/or Personality/Traits tabs, +#. Name, race, age, profession +#. Description from the Unit/Health/Description screen +#. Traits from the Unit/Personality/Traits screen +The script works for all units with text in the Description &/or Personality/Traits tabs, such as dwarves, dogs, elves, goblins, and beasts. For items, it retrieves: -- Decorated name (e.g., "☼«☼Chalk Statue of Dakas☼»☼") -- Full description from the item's view sheet -It works for most items with in-game descriptions and names, including those in storage, +#. Decorated name (e.g., "☼«☼Chalk Statue of Dakas☼»☼") +#. Full description from the item's view sheet +The script works for most items with in-game descriptions and names, including those in storage, on the ground, installed as a building, or worn/carried by units. The script appends a markdown-formatted version of the text to a target file diff --git a/markdown.lua b/markdown.lua index 2ad099c268..064a7de85e 100644 --- a/markdown.lua +++ b/markdown.lua @@ -10,25 +10,24 @@ local worldName = dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data. -- Argument processing local args = {...} -if args[1] ~= nil then - local userProvidedName = table.remove(args, 1) - userProvidedName = string.gsub(userProvidedName, " ", "_") - filename = 'markdown_' .. userProvidedName .. '.md' -else - filename = 'markdown_' .. worldName .. '_export.md' -end - --- Determine file write mode and filename -local writemode = 'a' -- append (default) +local writemode = 'a' -- default to append mode +local overwriteFlag = '-o' local filename - -if args[1] == '-o' or args[1] == '/n' then - writemode = 'w' -- overwrite - table.remove(args, 1) +local userProvidedNameParts = {} + +-- Check for the overwrite flag and remove it from the arguments if found +for i = #args, 1, -1 do + if args[i] == overwriteFlag then + writemode = 'w' -- set to overwrite mode + table.remove(args, i) -- remove the overwrite flag from the arguments + break -- remove only the first occurrence of the overwrite flag + end end -if args[1] ~= nil then - filename = 'markdown_' .. table.remove(args, 1) .. '.md' +-- Join remaining arguments with underscores to create the user-provided filename +if #args > 0 then + local userProvidedName = table.concat(args, "_") + filename = 'markdown_' .. userProvidedName .. '.md' else filename = 'markdown_' .. worldName .. '_export.md' end From 5dabb00a0475863dd7fa249ebe4f6f903693aa4d Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 19:40:03 +0100 Subject: [PATCH 09/10] - Changed success message based on writemode --- markdown.lua | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/markdown.lua b/markdown.lua index 064a7de85e..cc9a00c0ad 100644 --- a/markdown.lua +++ b/markdown.lua @@ -40,7 +40,15 @@ end local function closeFileHandle(handle) handle:write('\n---\n\n') handle:close() - print ('\nData exported to "' .. filename .. '"') + local function closeFileHandle(handle) + handle:write('\n---\n\n') + handle:close() + if writemode == 'a' then + print('\nData appended to "' .. filename .. '"') + elseif writemode == 'w' then + print('\nData overwritten in "' .. filename .. '"') + end + end end local function reformat(str) From 48bcdd7a91ba1f02966604114b9e4cfb4b674491 Mon Sep 17 00:00:00 2001 From: Glotov4 Date: Mon, 20 Nov 2023 20:23:00 +0100 Subject: [PATCH 10/10] - Added empty line at the end --- markdown.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.lua b/markdown.lua index cc9a00c0ad..f191c5cdca 100644 --- a/markdown.lua +++ b/markdown.lua @@ -135,4 +135,4 @@ elseif unit then end print('Exporting Health/Description & Personality/Traits data for: \n' .. dfhack.df2console(getNameRaceAgeProf(unit))) else end -closeFileHandle(log) \ No newline at end of file +closeFileHandle(log)