From 502f48f3cd50ef00d085eccc4d9e70b47559d7ee Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Fri, 27 Nov 2026 14:30:48 +0100 Subject: [PATCH 1/7] Rename LABEL keys title/subtitle to main/sub Frees 'title' from colliding with the upcoming TITLE clause keyword: 'TITLE title => ...' would lex the second word as the keyword. 'main' and 'sub' read naturally beside 'caption'. --- AGENTS.md | 2 +- README.md | 2 +- doc/faq.qmd | 2 +- doc/gallery/examples/bar-chart.qmd | 6 ++-- doc/gallery/examples/faceted.qmd | 6 ++-- doc/gallery/examples/histogram.qmd | 8 +++--- doc/gallery/examples/line-chart.qmd | 4 +-- doc/gallery/examples/minard.qmd | 4 +-- doc/gallery/examples/multi-layer.qmd | 6 ++-- doc/gallery/examples/scatterplot.qmd | 8 +++--- doc/get_started/first_plot.qmd | 2 +- doc/get_started/the_rest.qmd | 6 ++-- doc/index.qmd | 2 +- doc/syntax/clause/label-tabulate.qmd | 12 ++++---- doc/syntax/clause/label.qmd | 6 ++-- doc/vendor/SKILL.md | 8 +++--- ggsql-jupyter/README.md | 6 ++-- .../tests/fixtures/sample_notebook.ipynb | 10 +++---- ggsql-jupyter/tests/fixtures/test_queries.sql | 14 +++++----- ggsql-vscode/README.md | 2 +- ggsql-vscode/examples/sample.gsql | 28 +++++++++---------- ggsql-vscode/src/test/grammar/highlight.gsql | 2 +- ggsql-wasm/demo/src/examples.ts | 6 ++-- src/execute/table/layout.rs | 18 ++++++------ src/lib.rs | 2 +- src/parser/builder.rs | 4 +-- src/parser/mod.rs | 6 ++-- src/plot/main.rs | 4 +-- src/table/layout.rs | 10 +++---- src/writer/hephaestus/compose.rs | 6 ++-- src/writer/hephaestus/mod.rs | 20 ++++++------- src/writer/vegalite/mod.rs | 10 +++---- .../bindings/node/binding_test.js | 2 +- tree-sitter-ggsql/test/corpus/basic.txt | 6 ++-- 34 files changed, 120 insertions(+), 120 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4765be596..f42a3c0d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ A SQL extension for declarative data visualization based on the Grammar of Graph SELECT date, revenue, region FROM sales WHERE year = 2024 VISUALISE date AS x, revenue AS y, region AS color DRAW line -LABEL title => 'Sales by Region' +LABEL main => 'Sales by Region' ``` The user-facing site is at . The README at [`README.md`](README.md) is the public introduction. diff --git a/README.md b/README.md index 892964f34..ffa1cc414 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ VISUALISE date AS x, revenue AS y, region AS color DRAW line SCALE x SETTING breaks => 'month' -LABEL title => 'Sales by Region' +LABEL main => 'Sales by Region' ``` ## Why? diff --git a/doc/faq.qmd b/doc/faq.qmd index 3a3dbb8ad..7dc79f5bc 100644 --- a/doc/faq.qmd +++ b/doc/faq.qmd @@ -67,7 +67,7 @@ SELECT date, revenue FROM sales VISUALISE date AS x, revenue AS y DRAW line LABEL - title => 'Sales Over Time', + main => 'Sales Over Time', x => 'Date', y => 'Revenue (USD)' ``` diff --git a/doc/gallery/examples/bar-chart.qmd b/doc/gallery/examples/bar-chart.qmd index 528cc0e9c..c246206fa 100644 --- a/doc/gallery/examples/bar-chart.qmd +++ b/doc/gallery/examples/bar-chart.qmd @@ -16,7 +16,7 @@ GROUP BY species VISUALISE species AS x, count AS y, species AS fill DRAW bar LABEL - title => 'Penguin Count by Species', + main => 'Penguin Count by Species', x => 'Species', y => 'Count' ``` @@ -42,7 +42,7 @@ VISUALISE species AS x, count AS y, species AS fill DRAW bar PROJECT y, x TO cartesian LABEL - title => 'Penguin Count by Species', + main => 'Penguin Count by Species', x => 'Species', y => 'Count' ``` @@ -56,7 +56,7 @@ SELECT species FROM ggsql:penguins VISUALISE species AS x DRAW bar LABEL - title => 'Penguin Distribution', + main => 'Penguin Distribution', x => 'Species', y => 'Count' ``` diff --git a/doc/gallery/examples/faceted.qmd b/doc/gallery/examples/faceted.qmd index 00afd5684..23cbf0306 100644 --- a/doc/gallery/examples/faceted.qmd +++ b/doc/gallery/examples/faceted.qmd @@ -16,7 +16,7 @@ VISUALISE bill_len AS x, bill_dep AS y DRAW point FACET species LABEL - title => 'Bill Dimensions by Species', + main => 'Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` @@ -39,7 +39,7 @@ VISUALISE bill_len AS x, bill_dep AS y DRAW point FACET species BY island LABEL - title => 'Bill Dimensions by Species and Island', + main => 'Bill Dimensions by Species and Island', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` @@ -54,7 +54,7 @@ VISUALISE bill_len AS x, bill_dep AS y DRAW point FACET species SETTING free => 'y' LABEL - title => 'Bill Dimensions (Free Y Scale)', + main => 'Bill Dimensions (Free Y Scale)', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` diff --git a/doc/gallery/examples/histogram.qmd b/doc/gallery/examples/histogram.qmd index fa0b6697a..03f677ccd 100644 --- a/doc/gallery/examples/histogram.qmd +++ b/doc/gallery/examples/histogram.qmd @@ -15,7 +15,7 @@ SELECT Temp FROM ggsql:airquality VISUALISE Temp AS x DRAW histogram LABEL - title => 'Temperature Distribution', + main => 'Temperature Distribution', x => 'Temperature (F)', y => 'Count' ``` @@ -38,7 +38,7 @@ VISUALISE Temp AS x DRAW histogram SETTING bins => 15 LABEL - title => 'Temperature Distribution (15 bins)', + main => 'Temperature Distribution (15 bins)', x => 'Temperature (F)', y => 'Count' ``` @@ -53,7 +53,7 @@ VISUALISE Temp AS x DRAW histogram SETTING binwidth => 5 LABEL - title => 'Temperature Distribution (5 degree bins)', + main => 'Temperature Distribution (5 degree bins)', x => 'Temperature (F)', y => 'Count' ``` @@ -68,7 +68,7 @@ VISUALISE Temp AS x DRAW histogram REMAPPING density AS y LABEL - title => 'Temperature Density', + main => 'Temperature Density', x => 'Temperature (F)', y => 'Density' ``` diff --git a/doc/gallery/examples/line-chart.qmd b/doc/gallery/examples/line-chart.qmd index 0558336e8..12f5be631 100644 --- a/doc/gallery/examples/line-chart.qmd +++ b/doc/gallery/examples/line-chart.qmd @@ -16,7 +16,7 @@ VISUALISE Date AS x, Temp AS y DRAW line SCALE x VIA date LABEL - title => 'Daily Temperature', + main => 'Daily Temperature', x => 'Date', y => 'Temperature (F)' ``` @@ -41,7 +41,7 @@ VISUALISE Day AS x, Temp AS y, Month AS color DRAW line SCALE ORDINAL color LABEL - title => 'Daily Temperature by Month', + main => 'Daily Temperature by Month', x => 'Date', y => 'Temperature (F)' ``` diff --git a/doc/gallery/examples/minard.qmd b/doc/gallery/examples/minard.qmd index 4a9e1e2a2..f30054260 100644 --- a/doc/gallery/examples/minard.qmd +++ b/doc/gallery/examples/minard.qmd @@ -176,8 +176,8 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' RENAMING 'A' => 'Advance', 'R' => 'Retreat' SCALE linewidth FROM (0, null) TO (0, 20) LABEL - title => 'Napoleon\'s Russian Campaign', - subtitle => 'Inspired by the graphic of C.J. Minard', + main => 'Napoleon\'s Russian Campaign', + sub => 'Inspired by the graphic of C.J. Minard', linewidth => 'Troops', stroke => 'Direction', x => null, diff --git a/doc/gallery/examples/multi-layer.qmd b/doc/gallery/examples/multi-layer.qmd index bdc99ee23..fc297f4e1 100644 --- a/doc/gallery/examples/multi-layer.qmd +++ b/doc/gallery/examples/multi-layer.qmd @@ -19,7 +19,7 @@ DRAW point SETTING size => 4, color => 'darkblue' SCALE x VIA date LABEL - title => 'Temperature with Line and Points', + main => 'Temperature with Line and Points', x => 'Date', y => 'Temperature (F)' ``` @@ -46,7 +46,7 @@ DRAW line MAPPING Ozone AS y, 'Ozone' AS color SCALE x VIA date LABEL - title => 'Temperature and Ozone Over Time', + main => 'Temperature and Ozone Over Time', x => 'Date', y => 'Value' ``` @@ -70,7 +70,7 @@ DRAW point SETTING size => 3 SCALE x VIA date LABEL - title => 'Temperature vs Ozone', + main => 'Temperature vs Ozone', x => 'Date', y => 'Value' ``` diff --git a/doc/gallery/examples/scatterplot.qmd b/doc/gallery/examples/scatterplot.qmd index 2cc33f771..c48f29586 100644 --- a/doc/gallery/examples/scatterplot.qmd +++ b/doc/gallery/examples/scatterplot.qmd @@ -15,7 +15,7 @@ This is one of the most fundamental visualization types for exploring correlatio VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point LABEL - title => 'Penguin Bill Dimensions', + main => 'Penguin Bill Dimensions', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` @@ -37,7 +37,7 @@ We're adding `species AS color` to the mapping to colour the points by species. VISUALISE bill_len AS x, bill_dep AS y, species AS color FROM ggsql:penguins DRAW point LABEL - title => 'Penguin Bill Dimensions by Species', + main => 'Penguin Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` @@ -49,7 +49,7 @@ VISUALISE bill_len AS x, bill_dep AS y, species AS color FROM ggsql:penguins DRAW point SCALE color TO ('DeepSkyBlue', 'Fuchsia', 'Lime') LABEL - title => 'Penguin Bill Dimensions by Species', + main => 'Penguin Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` @@ -67,7 +67,7 @@ VISUALISE FROM ggsql:penguins DRAW point LABEL - title => 'Penguin Bill Dimensions by Species', + main => 'Penguin Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' ``` diff --git a/doc/get_started/first_plot.qmd b/doc/get_started/first_plot.qmd index 39219973e..6b6ae08a5 100644 --- a/doc/get_started/first_plot.qmd +++ b/doc/get_started/first_plot.qmd @@ -10,7 +10,7 @@ DRAW point SCALE x RENAMING * => '{} mm' LABEL - title => 'Relationship between bill dimensions in 3 species of penguins', + main => 'Relationship between bill dimensions in 3 species of penguins', x => 'Bill length', y => 'Bill depth' ``` diff --git a/doc/get_started/the_rest.qmd b/doc/get_started/the_rest.qmd index 4bdfa7894..7e8079866 100644 --- a/doc/get_started/the_rest.qmd +++ b/doc/get_started/the_rest.qmd @@ -49,7 +49,7 @@ aesthetic you have mapped. A `LABEL` clause may end up looking like this: ```ggsql LABEL - title => "Average wingspan of a cartoon owl" + main => "Average wingspan of a cartoon owl" x => "Radius of first circle (cm)" y => "Wingspan (cm)" ``` @@ -115,8 +115,8 @@ FACET island SETTING free => 'angle' SCALE panel FROM ('Biscoe', 'Dream') LABEL - title => 'Distribution of penguin species between islands', - subtitle => 'Compared across 344 penguins', + main => 'Distribution of penguin species between islands', + sub => 'Compared across 344 penguins', fill => 'Species' ``` diff --git a/doc/index.qmd b/doc/index.qmd index 789aef19e..0005569bd 100644 --- a/doc/index.qmd +++ b/doc/index.qmd @@ -48,7 +48,7 @@ PLACE rule SETTING slope => 0.4, y => -1 SCALE BINNED fill LABEL - title => 'Relationship between bill dimensions in 3 species of penguins', + main => 'Relationship between bill dimensions in 3 species of penguins', x => 'Bill length (mm)', y => 'Bill depth (mm)' ``` diff --git a/doc/syntax/clause/label-tabulate.qmd b/doc/syntax/clause/label-tabulate.qmd index 210ab5f0a..85e3e4edc 100644 --- a/doc/syntax/clause/label-tabulate.qmd +++ b/doc/syntax/clause/label-tabulate.qmd @@ -21,8 +21,8 @@ On the left hand side of the arrow, the following keys can be used: * Column names as they occur in the data * Reserved keywords for special labels: - * `title` as the main title - * `subtitle` as the subtitle + * `main` as the main title + * `sub` as the subtitle * `caption` as the table caption * Spanner IDs declared by `SPAN` clauses. @@ -54,8 +54,8 @@ Adding titles to a table. ```{ggsql} TABULATE * FROM my_data LABEL - title => 'Penguins!', - subtitle => 'Structural size measurements', + main => 'Penguins!', + sub => 'Structural size measurements', caption => 'Source: Palmer station, Antarctica' ``` @@ -68,7 +68,7 @@ SELECT * FROM (VALUES (1, 'a'), (2, 'b'), (3, 'c')) AS t(id, title) TABULATE * FROM title_data LABEL - title => 'Overrules column' + main => 'Overrules column' ``` You can target an aliased column instead. @@ -76,6 +76,6 @@ You can target an aliased column instead. ```{ggsql} TABULATE *, title AS title_col FROM title_data LABEL - title => 'Main title', + main => 'Main title', title_col => 'Column title' ``` \ No newline at end of file diff --git a/doc/syntax/clause/label.qmd b/doc/syntax/clause/label.qmd index 766f3d4b8..ebe7e8763 100644 --- a/doc/syntax/clause/label.qmd +++ b/doc/syntax/clause/label.qmd @@ -20,12 +20,12 @@ If an `aesthetic` is given, then the title will be used for the relevant axis or There are a few additional labels beside the aesthetics that govern the different titles of the plot and can be given instead of an aesthetic name: -* `title`: The main title of the plot -* `subtitle`: An additional, often longer and more descriptive, title beneath the main title +* `main`: The main title of the plot +* `sub`: An additional, often longer and more descriptive, title beneath the main title * `caption`: A string placed below the plot, often used to add additional information about the data source etc. Supported by every writer except Vega-Lite, which has no equivalent. ## Rich text -Every writer except Vega-Lite interprets the strings you provide here as markdown, so `LABEL title => 'Sales in **2024**'` renders the year in bold. +Every writer except Vega-Lite interprets the strings you provide here as markdown, so `LABEL main => 'Sales in **2024**'` renders the year in bold. This applies to the plot title, subtitle and caption, to the axis and legend titles, and to break labels (axis tick labels and legend keys). The Vega-Lite writer has no rich-text support at all and draws every label exactly as given. diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index c7afd5d17..ed52e47cd 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -138,9 +138,9 @@ PROJECT TO polar SETTING inner => 0.5 -- donut chart ## LABEL clause -Overrides axis/legend labels & titles: `title`, `subtitle`, `caption`, or any aesthetic name; `null` suppresses. +Overrides axis/legend labels & titles: `main`, `sub`, `caption`, or any aesthetic name; `null` suppresses. ```ggsql -LABEL title => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null +LABEL main => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null ``` --- @@ -160,7 +160,7 @@ Renders the query result as a table instead of a plot — the plain-table counte ### LABEL (table) -Keyed by column name, not aesthetic. Reserved keys: `title`, `subtitle`, `caption`. `null` blanks a header; if all headers are blank the header row is omitted. Also labels spanners via their SPAN id: `LABEL q1 => 'Q1 Totals'`. No automatic labelling and no markdown — a column without a `LABEL` keeps its name. +Keyed by column name, not aesthetic. Reserved keys: `main`, `sub`, `caption`. `null` blanks a header; if all headers are blank the header row is omitted. Also labels spanners via their SPAN id: `LABEL q1 => 'Q1 Totals'`. No automatic labelling and no markdown — a column without a `LABEL` keeps its name. ### SPAN @@ -188,7 +188,7 @@ Configures cell display and column placement. ```ggsql SELECT * FROM ggsql:penguins LIMIT 5 TABULATE * - LABEL title => 'Penguins!', bill_len => 'Length', bill_dep => 'Depth' + LABEL main => 'Penguins!', bill_len => 'Length', bill_dep => 'Depth' SPAN Bill OVER bill_len, bill_dep FORMAT STUB species FORMAT body_mass SETTING hjust => 'right' RENAMING null => '-', * => '{:num %.0f}g' diff --git a/ggsql-jupyter/README.md b/ggsql-jupyter/README.md index 2efde0168..46aee85bd 100644 --- a/ggsql-jupyter/README.md +++ b/ggsql-jupyter/README.md @@ -139,7 +139,7 @@ VISUALISE date AS x, revenue AS y DRAW line SCALE x SETTING type => 'date' -LABEL title => 'Revenue Growth', x => 'Date', y => 'Revenue ($)' +LABEL main => 'Revenue Growth', x => 'Date', y => 'Revenue ($)' ``` #### Multi-Layer Plot with Global Mapping @@ -153,7 +153,7 @@ DRAW line MAPPING y AS y DRAW line MAPPING z AS y -LABEL title => 'Polynomial Functions' +LABEL main => 'Polynomial Functions' ``` #### Pure SQL (Data Tables) @@ -183,5 +183,5 @@ Cell 2: SELECT * FROM products VISUALISE name AS x, price AS y DRAW bar -LABEL title => 'Product Prices', y => 'Price ($)' +LABEL main => 'Product Prices', y => 'Price ($)' ``` diff --git a/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb b/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb index 0fb078109..37f9d14e8 100644 --- a/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb +++ b/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb @@ -101,7 +101,7 @@ "FROM generate_series(1, 10) as t(n)\n", "VISUALISE x, y\n", "DRAW point\n", - "LABEL title => 'Quadratic Function', x => 'X Value', y => 'Y Value'" + "LABEL main => 'Quadratic Function', x => 'X Value', y => 'Y Value'" ] }, { @@ -123,7 +123,7 @@ "VISUALISE date AS x, revenue AS y, product AS color\n", "DRAW line\n", "SCALE x SETTING type => 'date'\n", - "LABEL title => 'Sales Revenue Over Time', x => 'Date', y => 'Revenue ($)'" + "LABEL main => 'Sales Revenue Over Time', x => 'Date', y => 'Revenue ($)'" ] }, { @@ -146,7 +146,7 @@ "DRAW line\n", "DRAW point\n", "SCALE x SETTING type => 'date'\n", - "LABEL title => 'Sales with Data Points', x => 'Date', y => 'Revenue ($)'" + "LABEL main => 'Sales with Data Points', x => 'Date', y => 'Revenue ($)'" ] }, { @@ -167,7 +167,7 @@ "GROUP BY product\n", "VISUALISE product AS x, total_revenue AS y\n", "DRAW bar\n", - "LABEL title => 'Total Revenue by Product', x => 'Product', y => 'Total Revenue ($)'" + "LABEL main => 'Total Revenue by Product', x => 'Product', y => 'Total Revenue ($)'" ] }, { @@ -190,7 +190,7 @@ "DRAW line\n", "FACET region\n", "SCALE x SETTING type => 'date'\n", - "LABEL title => 'Revenue by Region', x => 'Date', y => 'Revenue ($)'" + "LABEL main => 'Revenue by Region', x => 'Date', y => 'Revenue ($)'" ] } ], diff --git a/ggsql-jupyter/tests/fixtures/test_queries.sql b/ggsql-jupyter/tests/fixtures/test_queries.sql index ed818e455..15198b53b 100644 --- a/ggsql-jupyter/tests/fixtures/test_queries.sql +++ b/ggsql-jupyter/tests/fixtures/test_queries.sql @@ -20,7 +20,7 @@ SELECT n as x, n * n as y FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW line -LABEL title => 'Quadratic Function', x AS 'X', y AS 'Y'; +LABEL main => 'Quadratic Function', x AS 'X', y AS 'Y'; -- Multi-layer visualization with global mapping SELECT n as x, n * n as y @@ -28,7 +28,7 @@ FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW line DRAW point -LABEL title => 'Line with Points'; +LABEL main => 'Line with Points'; -- Date-based visualization with global mapping SELECT @@ -39,7 +39,7 @@ FROM generate_series(0, 30) as t(n) VISUALISE date AS x, value AS y, category AS color DRAW line SCALE x SETTING type => 'date' -LABEL title => 'Time Series', x => 'Date', y => 'Value'; +LABEL main => 'Time Series', x => 'Date', y => 'Value'; -- Bar chart with global mapping SELECT @@ -48,7 +48,7 @@ SELECT FROM generate_series(0, 4) as t(n) VISUALISE category AS x, value AS y DRAW bar -LABEL title => 'Bar Chart', x AS 'Category', y AS 'Value'; +LABEL main => 'Bar Chart', x AS 'Category', y AS 'Value'; -- Faceted visualization with global mapping SELECT @@ -59,7 +59,7 @@ FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW point FACET group -LABEL title => 'Faceted Plot'; +LABEL main => 'Faceted Plot'; -- Visualization with FILTER clause - global mapping with layer filter SELECT @@ -69,7 +69,7 @@ FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW line DRAW point FILTER y > 25 -LABEL title => 'Filtered Points'; +LABEL main => 'Filtered Points'; -- Visualization with SETTING parameters SELECT @@ -78,7 +78,7 @@ SELECT FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW point SETTING size => 10, opacity => 0.5 -LABEL title => 'Points with Parameters'; +LABEL main => 'Points with Parameters'; -- Error case: invalid table SELECT * FROM nonexistent_table; diff --git a/ggsql-vscode/README.md b/ggsql-vscode/README.md index 13e92a642..31969cead 100644 --- a/ggsql-vscode/README.md +++ b/ggsql-vscode/README.md @@ -18,7 +18,7 @@ VISUALISE date AS x, revenue AS y, region AS color DRAW line SCALE x SETTING breaks => 'month' -LABEL title => 'Sales by Region' +LABEL main => 'Sales by Region' ``` ## Installation diff --git a/ggsql-vscode/examples/sample.gsql b/ggsql-vscode/examples/sample.gsql index 26159ef5c..03b135e5d 100644 --- a/ggsql-vscode/examples/sample.gsql +++ b/ggsql-vscode/examples/sample.gsql @@ -6,7 +6,7 @@ -- ============================================================================ VISUALISE hp AS x, mpg AS y, cyl AS color FROM 'mtcars.csv' DRAW point -LABEL title => 'Horsepower vs Fuel Efficiency', +LABEL main => 'Horsepower vs Fuel Efficiency', x => 'Horsepower', y => 'Miles per Gallon' @@ -29,7 +29,7 @@ DRAW point SETTING size => 3 SCALE x SETTING type => 'date' SCALE color TO viridis FACET region SETTING scales => 'free_y' -LABEL title => 'Sales Trends by Region', +LABEL main => 'Sales Trends by Region', x => 'Month', y => 'Total Quantity', caption => 'Data from 2024' @@ -46,7 +46,7 @@ LIMIT 10 VISUALISE category AS x, total AS y, category AS fill DRAW bar PROJECT y, x TO cartesian -LABEL title => 'Top 10 Product Categories', +LABEL main => 'Top 10 Product Categories', x => 'Category', y => 'Total Sales' @@ -59,7 +59,7 @@ GROUP BY region VISUALISE region AS x, count AS y, region AS fill DRAW bar PROJECT TO polar -LABEL title => 'Customer Distribution by Region' +LABEL main => 'Customer Distribution by Region' -- ============================================================================ -- Example 5: Faceted Histogram @@ -71,7 +71,7 @@ VISUALISE age AS x, gender AS fill DRAW histogram SCALE x SETTING type => 'linear', limits => (18, 80) FACET gender SETTING scales => 'fixed' -LABEL title => 'Age Distribution by Gender', +LABEL main => 'Age Distribution by Gender', x => 'Age', y => 'Count' @@ -100,7 +100,7 @@ DRAW line SCALE x SETTING type => 'date' SCALE x FROM ('2024-01-01', '2024-12-31') SCALE y SETTING type => 'linear', limits => (0, 100) -LABEL title => 'Temperature Range (Last 30 Days)', +LABEL main => 'Temperature Range (Last 30 Days)', x => 'Date', y => 'Temperature (°C)', caption => 'Source: Weather Station Alpha' @@ -125,7 +125,7 @@ SCALE x SETTING type => 'date' SCALE y SETTING type => 'log10' SCALE DISCRETE color FROM ('Electronics', 'Clothing', 'Food', 'Books') FACET category BY employee_name SETTING scales => 'free_y' -LABEL title => 'Sales Performance Analysis', +LABEL main => 'Sales Performance Analysis', x => 'Sale Date', y => 'Revenue (log scale)', color => 'Product Category', @@ -147,10 +147,10 @@ VISUALISE quarter AS x, revenue AS y, category AS fill FROM quarterly_breakdown DRAW area SETTING opacity => 0.7 SCALE x SETTING type => 'date' SCALE DISCRETE fill FROM ('A', 'B', 'C', 'D') TO plasma -LABEL title => 'Quarterly Revenue by Category', +LABEL main => 'Quarterly Revenue by Category', x => 'Quarter', y => 'Revenue ($)', - subtitle => 'Stacked Area Chart' + sub => 'Stacked Area Chart' -- ============================================================================ -- Example 9: Boxplot with Violin Overlay @@ -162,7 +162,7 @@ VISUALISE category AS x, price AS y DRAW boxplot DRAW violin SETTING opacity => 0.3 SCALE y FROM (0, 500) -LABEL title => 'Price Distribution by Category', +LABEL main => 'Price Distribution by Category', x => 'Product Category', y => 'Price ($)' @@ -186,7 +186,7 @@ SCALE color TO viridis SCALE size SETTING limits => (0, 10000) SCALE x FROM (0, 1000) SCALE y FROM (0, 5) -LABEL title => 'Featured Products: Price vs Rating', +LABEL main => 'Featured Products: Price vs Rating', x => 'Price ($)', y => 'Customer Rating', size => 'Total Sales' @@ -202,12 +202,12 @@ WITH sales_summary AS ( -- First visualization: by region VISUALISE region AS x, total AS y, region AS fill FROM sales_summary DRAW bar -LABEL title => 'Sales by Region' +LABEL main => 'Sales by Region' -- Second visualization: by category VISUALISE category AS x, total AS y, category AS fill FROM sales_summary DRAW bar PROJECT y, x TO cartesian -LABEL title => 'Sales by Category' +LABEL main => 'Sales by Category' -- ============================================================================ -- Example 12: FILTER clause for layer-specific filtering @@ -218,7 +218,7 @@ VISUALISE date AS x, value AS y, category AS color DRAW line DRAW point FILTER value > 50 SCALE x SETTING type => 'date' -LABEL title => 'Metrics with Highlighted Points Above 50' +LABEL main => 'Metrics with Highlighted Points Above 50' -- ============================================================================ -- Comments and String Handling diff --git a/ggsql-vscode/src/test/grammar/highlight.gsql b/ggsql-vscode/src/test/grammar/highlight.gsql index 6b2e64d3b..4288a699d 100644 --- a/ggsql-vscode/src/test/grammar/highlight.gsql +++ b/ggsql-vscode/src/test/grammar/highlight.gsql @@ -34,7 +34,7 @@ SCALE DISCRETE color TO viridis SCALE y VIA log10 -- ^^^^^ constant.language.scale-type.ggsql -LABEL title => 'Sales by Region', x => 'Date', y => 'Revenue' +LABEL main => 'Sales by Region', x => 'Date', y => 'Revenue' -- <---- keyword.other.ggsql -- ^^^^^ support.type.property.ggsql -- ^^ keyword.operator.fatarrow.ggsql diff --git a/ggsql-wasm/demo/src/examples.ts b/ggsql-wasm/demo/src/examples.ts index b65779477..5dd6d1d19 100644 --- a/ggsql-wasm/demo/src/examples.ts +++ b/ggsql-wasm/demo/src/examples.ts @@ -69,7 +69,7 @@ DRAW line query: `SELECT * FROM ggsql:penguins VISUALISE DRAW point MAPPING bill_len AS x, bill_dep AS y, body_mass AS size, species AS color -LABEL title => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, +LABEL main => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, }, { section: "Layers", @@ -210,7 +210,7 @@ SCALE shape TO ['star', 'bowtie', 'square-plus']`, query: `SELECT * FROM ggsql:penguins VISUALISE DRAW point MAPPING bill_len AS x, bill_dep AS y, body_mass AS size -LABEL title => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, +LABEL main => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, }, // === Spatial === @@ -234,7 +234,7 @@ DRAW spatial MAPPING population AS fill SETTING opacity => 1 SCALE fill TO viridis VIA log -LABEL title => 'Population by country', fill => 'Population'`, +LABEL main => 'Population by country', fill => 'Population'`, }, { section: "Spatial", diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 243dfc779..60563333e 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -789,11 +789,11 @@ mod tests { table .labels .labels - .insert("title".to_string(), Some("Title".to_string())); + .insert("main".to_string(), Some("Title".to_string())); table .labels .labels - .insert("subtitle".to_string(), Some("Subtitle".to_string())); + .insert("sub".to_string(), Some("Subtitle".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -835,7 +835,7 @@ mod tests { table .labels .labels - .insert("subtitle".to_string(), Some("Subtitle only".to_string())); + .insert("sub".to_string(), Some("Subtitle only".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -888,11 +888,11 @@ mod tests { table .labels .labels - .insert("title".to_string(), Some("Title".to_string())); + .insert("main".to_string(), Some("Title".to_string())); table .labels .labels - .insert("subtitle".to_string(), Some("Subtitle".to_string())); + .insert("sub".to_string(), Some("Subtitle".to_string())); let layout = resolve_layout(&frame, &table).unwrap(); @@ -912,18 +912,18 @@ mod tests { #[test] fn reserved_label_keys_always_win_over_a_same_named_column() { - // A column literally named "title" can't get a header override via + // A column literally named "main" can't get a header override via // LABEL — the reserved key always wins, and the column just keeps // its own name, exactly as if no LABEL entry existed for it. let frame = df! { - "title" => vec![1i32], + "main" => vec![1i32], } .unwrap(); let mut table = Table::new(); table .labels .labels - .insert("title".to_string(), Some("The Table's Title".to_string())); + .insert("main".to_string(), Some("The Table's Title".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -936,6 +936,6 @@ mod tests { .iter() .find(|c| c.kind == TableCellKind::ColumnLabel) .unwrap(); - assert_eq!(column_label.content, "title"); + assert_eq!(column_label.content, "main"); } } diff --git a/src/lib.rs b/src/lib.rs index c859f9bf5..c6d5e058e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ FROM sales WHERE year = 2024 VISUALISE date AS x, revenue AS y, region AS color DRAW line -LABEL title => 'Sales by Region' +LABEL main => 'Sales by Region' ``` ## Architecture diff --git a/src/parser/builder.rs b/src/parser/builder.rs index 9328a3334..9f2e5513e 100644 --- a/src/parser/builder.rs +++ b/src/parser/builder.rs @@ -1998,7 +1998,7 @@ mod tests { visualise draw point MAPPING x AS x, y AS y project to cartesian - label title => 'Test Chart' + label main => 'Test Chart' "#; let result = parse_test_query(query); @@ -4017,7 +4017,7 @@ mod tests { #[test] fn test_parse_string_node() { - let source = make_source("VISUALISE DRAW point LABEL title => 'hello world'"); + let source = make_source("VISUALISE DRAW point LABEL main => 'hello world'"); let root = source.root(); let string_node = source.find_node(&root, "(string) @s").unwrap(); diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 701af0ea4..e2bfde3ff 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -26,7 +26,7 @@ let query = r#" VISUALISE date AS x, revenue AS y, region AS color DRAW line LABEL - title => 'Sales by Region' + main => 'Sales by Region' "#; let specs = parse_query(query)?; @@ -210,7 +210,7 @@ mod tests { SELECT x, y FROM data VISUALISE x, y DRAW point - LABEL title => 'Scatter Plot' + LABEL main => 'Scatter Plot' VISUALIZE DRAW bar MAPPING x AS x, y AS y "#; @@ -255,7 +255,7 @@ mod tests { DRAW line DRAW line MAPPING cost AS y SCALE x VIA date - LABEL title => 'Revenue and Cost Trends' + LABEL main => 'Revenue and Cost Trends' VISUALIZE DRAW bar MAPPING date AS x, revenue AS y VISUALISE diff --git a/src/plot/main.rs b/src/plot/main.rs index ff45cf5b7..f19274733 100644 --- a/src/plot/main.rs +++ b/src/plot/main.rs @@ -830,7 +830,7 @@ mod tests { spec.project = Some(Projection::cartesian()); spec.labels = Labels { labels: HashMap::from([ - ("title".to_string(), Some("My Chart".to_string())), + ("main".to_string(), Some("My Chart".to_string())), ("color".to_string(), Some("Category".to_string())), ("x".to_string(), Some("X Axis".to_string())), ]), @@ -842,7 +842,7 @@ mod tests { let labels = &spec.labels; // Material labels should remain unchanged assert_eq!( - labels.labels.get("title"), + labels.labels.get("main"), Some(&Some("My Chart".to_string())) ); assert_eq!( diff --git a/src/table/layout.rs b/src/table/layout.rs index 46e5f1a14..74e41491e 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -32,9 +32,9 @@ pub enum TableCellKind { /// A spanner cell, grouping several columns under one label (`TABULATE /// SPAN`). Spanner, - /// The table's title (`LABEL title => ...`, gt's `gt_title`). + /// The table's title (`LABEL main => ...`, gt's `gt_title`). Title, - /// The table's subtitle (`LABEL subtitle => ...`, gt's `gt_subtitle`). + /// The table's subtitle (`LABEL sub => ...`, gt's `gt_subtitle`). Subtitle, /// The table's caption (`LABEL caption => ...`, gt's `tab_caption()`). /// Full-width like `Title`/`Subtitle`, but rendered outside the normal @@ -978,14 +978,14 @@ pub(crate) struct TableTitles { pub caption: Option, } -/// Pop the reserved `title`/`subtitle`/`caption` keys out of a `TABULATE` +/// Pop the reserved `main`/`sub`/`caption` keys out of a `TABULATE` /// `LABEL` clause's resolved map into `TableTitles`, leaving only genuine /// column-name overrides behind. `.flatten()` treats "key absent" and "key /// present but NULL" the same: neither produces a title/subtitle/caption. pub(crate) fn extract_table_titles(labels: &mut Labels) -> TableTitles { TableTitles { - title: labels.labels.remove("title").flatten(), - subtitle: labels.labels.remove("subtitle").flatten(), + title: labels.labels.remove("main").flatten(), + subtitle: labels.labels.remove("sub").flatten(), caption: labels.labels.remove("caption").flatten(), } } diff --git a/src/writer/hephaestus/compose.rs b/src/writer/hephaestus/compose.rs index 3ef549384..a90d72cda 100644 --- a/src/writer/hephaestus/compose.rs +++ b/src/writer/hephaestus/compose.rs @@ -94,13 +94,13 @@ pub fn build_composition( .shape_registry(ShapeRegistry::with_builtins()) .theme(wiring::ggsql_theme()); - // LABEL title/subtitle/caption live on the composition rather than the + // LABEL main/sub/caption live on the composition rather than the // panels, so one label spans the whole figure — also correct unfaceted, // where a panel-level title would resolve to the same layout row. - if let Some(text) = wiring::plot_label(spec, "title") { + if let Some(text) = wiring::plot_label(spec, "main") { view = view.title(text); } - if let Some(text) = wiring::plot_label(spec, "subtitle") { + if let Some(text) = wiring::plot_label(spec, "sub") { view = view.subtitle(text); } if let Some(text) = wiring::plot_label(spec, "caption") { diff --git a/src/writer/hephaestus/mod.rs b/src/writer/hephaestus/mod.rs index 2db7bdeb4..21a79c244 100644 --- a/src/writer/hephaestus/mod.rs +++ b/src/writer/hephaestus/mod.rs @@ -436,7 +436,7 @@ mod tests { assert_renders( "SELECT 1 AS x, 2 AS y UNION ALL SELECT 2, 3 \ VISUALISE x AS x, y AS y DRAW point \ - LABEL title => 'A **bold** title', subtitle => '{.red red} subtitle', \ + LABEL main => 'A **bold** title', sub => '{.red red} subtitle', \ caption => '*italic* caption', x => 'axis *italic*'", ); } @@ -1294,18 +1294,18 @@ mod tests { assert_renders( "SELECT 1 AS x, 2 AS y UNION ALL SELECT 2, 3 UNION ALL SELECT 3, 1 \ VISUALISE x AS x, y AS y DRAW point \ - LABEL title => 'Sales by Region', subtitle => 'FY 2024', \ + LABEL main => 'Sales by Region', sub => 'FY 2024', \ caption => 'Source: internal'", ); } #[test] fn renders_suppressed_title() { - // `LABEL title => NULL` suppresses; the subtitle still renders. + // `LABEL main => NULL` suppresses; the subtitle still renders. assert_renders( "SELECT 1 AS x, 2 AS y UNION ALL SELECT 2, 3 \ VISUALISE x AS x, y AS y DRAW point \ - LABEL title => NULL, subtitle => 'no title above me'", + LABEL main => NULL, sub => 'no title above me'", ); } @@ -1317,7 +1317,7 @@ mod tests { "SELECT x, y, g FROM (VALUES (1,1,'a'),(2,2,'a'),(1,2,'b'),(2,3,'b'),\ (1,3,'c'),(2,1,'c')) t(x,y,g) \ VISUALISE x AS x, y AS y DRAW point FACET g \ - LABEL title => 'One title for all panels'", + LABEL main => 'One title for all panels'", ); } @@ -1529,7 +1529,7 @@ mod svg_text { fn every_plot_label_reaches_the_output() { let labelled = svg("SELECT x, y FROM (VALUES (1,2),(2,3)) t(x,y) \ VISUALISE x AS x, y AS y DRAW point \ - LABEL title => 'The title', subtitle => 'The subtitle', \ + LABEL main => 'The title', sub => 'The subtitle', \ caption => 'The caption', x => 'Across', y => 'Up'"); for label in ["The title", "The subtitle", "The caption", "Across", "Up"] { assert!(contains(&labelled, label), "missing label '{label}'"); @@ -1539,7 +1539,7 @@ mod svg_text { #[test] fn markdown_in_a_label_is_parsed_rather_than_printed() { let emphasised = svg("SELECT x, y FROM (VALUES (1,2),(2,3)) t(x,y) \ - VISUALISE x AS x, y AS y DRAW point LABEL title => 'A *bold* title'"); + VISUALISE x AS x, y AS y DRAW point LABEL main => 'A *bold* title'"); // The words survive, the markers do not. assert!(contains(&emphasised, "A bold title")); assert!( @@ -1579,7 +1579,7 @@ mod svg_text { #[test] fn outline_mode_turns_text_into_paths() { let query = "SELECT x, y FROM (VALUES (1,2),(2,3)) t(x,y) \ - VISUALISE x AS x, y AS y DRAW point LABEL title => 'Outlined'"; + VISUALISE x AS x, y AS y DRAW point LABEL main => 'Outlined'"; let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); let spec = reader.execute(query).unwrap().into_plot().unwrap(); @@ -1671,7 +1671,7 @@ mod pdf_structure { reader .execute( "SELECT x, y FROM (VALUES (1,2),(2,3),(3,1)) t(x,y) \ - VISUALISE x AS x, y AS y DRAW point LABEL title => 'A page'", + VISUALISE x AS x, y AS y DRAW point LABEL main => 'A page'", ) .unwrap() .into_plot() @@ -1751,7 +1751,7 @@ mod hep_roundtrip { "faceted scatter with a legend", "VISUALISE bill_len AS x, bill_dep AS y, species AS color \ FROM ggsql:penguins DRAW point FACET island \ - LABEL title => 'Penguin *bills*', caption => 'From ggsql:penguins'", + LABEL main => 'Penguin *bills*', caption => 'From ggsql:penguins'", ), ( "multi-layer with a colorbar", diff --git a/src/writer/vegalite/mod.rs b/src/writer/vegalite/mod.rs index e4fabc4a2..2cc36acea 100644 --- a/src/writer/vegalite/mod.rs +++ b/src/writer/vegalite/mod.rs @@ -1115,8 +1115,8 @@ impl Writer for VegaLiteWriter { } { - let title = spec.labels.get("title"); - let subtitle = spec.labels.get("subtitle"); + let title = spec.labels.get("main"); + let subtitle = spec.labels.get("sub"); match (title, subtitle) { (Some(t), Some(st)) => { // Vega-Lite uses an object for title + subtitle @@ -1549,7 +1549,7 @@ mod tests { spec.labels .labels - .insert("title".to_string(), Some("My Chart".to_string())); + .insert("main".to_string(), Some("My Chart".to_string())); let df = df! { "date" => vec!["2024-01-01", "2024-01-02"], @@ -1586,8 +1586,8 @@ mod tests { VISUALISE x, y, category AS stroke DRAW point LABEL - title => 'Multi-line\nChart Title', - subtitle => 'Line 1\nLine 2\nLine 3', + main => 'Multi-line\nChart Title', + sub => 'Line 1\nLine 2\nLine 3', x => 'X Axis\nWith Newline', y => 'Single Line', stroke => 'Category\nMulti-line Legend' diff --git a/tree-sitter-ggsql/bindings/node/binding_test.js b/tree-sitter-ggsql/bindings/node/binding_test.js index 322cd8066..606d9e27e 100644 --- a/tree-sitter-ggsql/bindings/node/binding_test.js +++ b/tree-sitter-ggsql/bindings/node/binding_test.js @@ -36,7 +36,7 @@ try { DRAW line DRAW point SETTING size => 3 SCALE x SETTING type => 'date' - LABEL title => 'Revenue Analysis' + LABEL main => 'Revenue Analysis' THEME minimal `; diff --git a/tree-sitter-ggsql/test/corpus/basic.txt b/tree-sitter-ggsql/test/corpus/basic.txt index f0c6f62f1..3d5f3d46e 100644 --- a/tree-sitter-ggsql/test/corpus/basic.txt +++ b/tree-sitter-ggsql/test/corpus/basic.txt @@ -596,7 +596,7 @@ Plot with labels VISUALISE x, y DRAW point -LABEL title => 'My Plot', x => 'X Axis', y => 'Y Axis' +LABEL main => 'My Plot', x => 'X Axis', y => 'Y Axis' -------------------------------------------------------------------------------- @@ -4948,7 +4948,7 @@ Line comment (double slash) between clauses VISUALISE x, y // trailing comment on the same line DRAW point // comment before a clause -LABEL title => 'My Plot' // and one at the end +LABEL main => 'My Plot' // and one at the end -------------------------------------------------------------------------------- @@ -5011,7 +5011,7 @@ VISUALISE /* inline block */ x, y DRAW point /* a multi-line block comment */ -LABEL title => 'My Plot' +LABEL main => 'My Plot' -------------------------------------------------------------------------------- From 586c7148a9b946663e4c7ec532548f1776609ac5 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Fri, 27 Nov 2026 15:10:07 +0100 Subject: [PATCH 2/7] Rename the LABEL clause to TITLE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The LABEL clause sets (sub)titles, captions and axis/legend titles, so TITLE is the more natural name — freeing LABEL for a future clause that actually sets break labels. Grammar nodes rename accordingly (title_clause, title_assignment, title_type), the shared Labels struct becomes Titles (src/titles.rs, Plot.titles, Table.titles), and the doc pages move to syntax/clause/title.qmd and title-tabulate.qmd. --- AGENTS.md | 4 +- README.md | 2 +- doc/_quarto.yml | 16 +-- doc/faq.qmd | 4 +- doc/gallery/examples/bar-chart.qmd | 6 +- doc/gallery/examples/faceted.qmd | 6 +- doc/gallery/examples/histogram.qmd | 8 +- doc/gallery/examples/line-chart.qmd | 6 +- doc/gallery/examples/minard.qmd | 4 +- doc/gallery/examples/multi-layer.qmd | 6 +- doc/gallery/examples/scatterplot.qmd | 10 +- doc/get_started/first_plot.qmd | 2 +- doc/get_started/grammar.qmd | 2 +- doc/get_started/the_rest.qmd | 12 +- doc/ggsql.xml | 30 ++--- doc/index.qmd | 2 +- doc/syntax/clause/facet-tabulate.qmd | 4 +- doc/syntax/clause/format.qmd | 6 +- doc/syntax/clause/scale.qmd | 2 +- doc/syntax/clause/span.qmd | 8 +- doc/syntax/clause/tabulate.qmd | 6 +- ...{label-tabulate.qmd => title-tabulate.qmd} | 34 ++--- doc/syntax/clause/{label.qmd => title.qmd} | 16 +-- doc/syntax/index.qmd | 4 +- doc/syntax/scale/aesthetic/0_position.qmd | 2 +- doc/vendor/SKILL.md | 18 +-- ggsql-jupyter/README.md | 6 +- ggsql-jupyter/src/kernel.rs | 2 +- ggsql-jupyter/src/plot/comm.rs | 2 +- .../tests/fixtures/sample_notebook.ipynb | 10 +- ggsql-jupyter/tests/fixtures/test_queries.sql | 14 +- ggsql-vscode/README.md | 2 +- ggsql-vscode/examples/sample.gsql | 26 ++-- ggsql-vscode/src/test/grammar/highlight.gsql | 2 +- ggsql-vscode/syntaxes/ggsql.tmLanguage.json | 22 ++-- ggsql-wasm/demo/src/examples.ts | 6 +- ggsql-wasm/demo/src/quarto/links.ts | 4 +- src/AGENTS.md | 4 +- src/execute/table/layout.rs | 96 +++++++------- src/execute/table/mod.rs | 18 +-- src/labels.rs | 40 ------ src/lib.rs | 4 +- src/parser/builder.rs | 70 +++++----- src/parser/mod.rs | 18 +-- src/plot/AGENTS.md | 6 +- src/plot/main.rs | 122 +++++++++--------- src/plot/mod.rs | 2 +- src/table/layout.rs | 20 +-- src/table/mod.rs | 20 +-- src/table/spanner.rs | 14 +- src/tests/e2e.rs | 12 +- src/titles.rs | 40 ++++++ src/writer/hephaestus/AGENTS.md | 2 +- src/writer/hephaestus/compose.rs | 2 +- src/writer/hephaestus/mod.rs | 24 ++-- src/writer/hephaestus/wiring.rs | 10 +- src/writer/html.rs | 2 +- src/writer/vegalite/encoding.rs | 4 +- src/writer/vegalite/mod.rs | 12 +- .../bindings/node/binding_test.js | 2 +- tree-sitter-ggsql/grammar.js | 24 ++-- tree-sitter-ggsql/queries/highlights.scm | 2 +- tree-sitter-ggsql/test/corpus/basic.txt | 68 +++++----- 63 files changed, 477 insertions(+), 477 deletions(-) rename doc/syntax/clause/{label-tabulate.qmd => title-tabulate.qmd} (67%) rename doc/syntax/clause/{label.qmd => title.qmd} (81%) delete mode 100644 src/labels.rs create mode 100644 src/titles.rs diff --git a/AGENTS.md b/AGENTS.md index f42a3c0d2..b962fd4c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,14 +6,14 @@ A SQL extension for declarative data visualization based on the Grammar of Graph SELECT date, revenue, region FROM sales WHERE year = 2024 VISUALISE date AS x, revenue AS y, region AS color DRAW line -LABEL main => 'Sales by Region' +TITLE main => 'Sales by Region' ``` The user-facing site is at . The README at [`README.md`](README.md) is the public introduction. ## Authoritative docs -**Anything about ggsql syntax or semantics belongs in [`doc/`](doc/), not in any AGENTS.md file.** That includes clause behaviour (`VISUALISE`, `DRAW`, `PLACE`, `SCALE`, `FACET`, `PROJECT`, `LABEL`), layer types, scales, aesthetics, and coordinate systems. AGENTS.md files describe the implementation around those features — they should link to `doc/syntax/` rather than restate. +**Anything about ggsql syntax or semantics belongs in [`doc/`](doc/), not in any AGENTS.md file.** That includes clause behaviour (`VISUALISE`, `DRAW`, `PLACE`, `SCALE`, `FACET`, `PROJECT`, `TITLE`), layer types, scales, aesthetics, and coordinate systems. AGENTS.md files describe the implementation around those features — they should link to `doc/syntax/` rather than restate. **Writing ggsql queries:** when you need to author or modify a ggsql query, use the vendored skill at [`doc/vendor/SKILL.md`](doc/vendor/SKILL.md). It is the source of truth for the syntax Claude should produce; do not invent clauses, settings, aesthetics, or layer types beyond what it documents. diff --git a/README.md b/README.md index ffa1cc414..10b72ddfe 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ VISUALISE date AS x, revenue AS y, region AS color DRAW line SCALE x SETTING breaks => 'month' -LABEL main => 'Sales by Region' +TITLE main => 'Sales by Region' ``` ## Why? diff --git a/doc/_quarto.yml b/doc/_quarto.yml index fb298d88c..a3296ce46 100644 --- a/doc/_quarto.yml +++ b/doc/_quarto.yml @@ -51,13 +51,13 @@ website: href: syntax/clause/facet.qmd - text: "`PROJECT`" href: syntax/clause/project.qmd - - text: "`LABEL`" - href: syntax/clause/label.qmd + - text: "`TITLE`" + href: syntax/clause/title.qmd - text: "---" - text: "`TABULATE`" href: syntax/clause/tabulate.qmd - - text: "`LABEL`" - href: syntax/clause/label-tabulate.qmd + - text: "`TITLE`" + href: syntax/clause/title-tabulate.qmd - text: "`SPAN`" href: syntax/clause/span.qmd - text: "`FORMAT`" @@ -117,14 +117,14 @@ website: href: syntax/clause/facet.qmd - text: "`PROJECT`" href: syntax/clause/project.qmd - - text: "`LABEL`" - href: syntax/clause/label.qmd + - text: "`TITLE`" + href: syntax/clause/title.qmd - section: "Tabulate clauses" contents: - text: "`TABULATE`" href: syntax/clause/tabulate.qmd - - text: "`LABEL`" - href: syntax/clause/label-tabulate.qmd + - text: "`TITLE`" + href: syntax/clause/title-tabulate.qmd - text: "`SPAN`" href: syntax/clause/span.qmd - text: "`FORMAT`" diff --git a/doc/faq.qmd b/doc/faq.qmd index 7dc79f5bc..3bb561ba8 100644 --- a/doc/faq.qmd +++ b/doc/faq.qmd @@ -60,13 +60,13 @@ DRAW point ::: {.callout-note collapse="true"} ## How do I set axis labels and a title? -Use the `LABEL` clause: +Use the `TITLE` clause: ```ggsql SELECT date, revenue FROM sales VISUALISE date AS x, revenue AS y DRAW line -LABEL +TITLE main => 'Sales Over Time', x => 'Date', y => 'Revenue (USD)' diff --git a/doc/gallery/examples/bar-chart.qmd b/doc/gallery/examples/bar-chart.qmd index c246206fa..d67e325f5 100644 --- a/doc/gallery/examples/bar-chart.qmd +++ b/doc/gallery/examples/bar-chart.qmd @@ -15,7 +15,7 @@ SELECT species, COUNT(*) as count FROM ggsql:penguins GROUP BY species VISUALISE species AS x, count AS y, species AS fill DRAW bar -LABEL +TITLE main => 'Penguin Count by Species', x => 'Species', y => 'Count' @@ -41,7 +41,7 @@ GROUP BY species VISUALISE species AS x, count AS y, species AS fill DRAW bar PROJECT y, x TO cartesian -LABEL +TITLE main => 'Penguin Count by Species', x => 'Species', y => 'Count' @@ -55,7 +55,7 @@ When you don't specify a y aesthetic, ggsql automatically counts occurrences: SELECT species FROM ggsql:penguins VISUALISE species AS x DRAW bar -LABEL +TITLE main => 'Penguin Distribution', x => 'Species', y => 'Count' diff --git a/doc/gallery/examples/faceted.qmd b/doc/gallery/examples/faceted.qmd index 23cbf0306..8a59822f0 100644 --- a/doc/gallery/examples/faceted.qmd +++ b/doc/gallery/examples/faceted.qmd @@ -15,7 +15,7 @@ SELECT bill_len, bill_dep, species FROM ggsql:penguins VISUALISE bill_len AS x, bill_dep AS y DRAW point FACET species -LABEL +TITLE main => 'Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' @@ -38,7 +38,7 @@ SELECT bill_len, bill_dep, species, island FROM ggsql:penguins VISUALISE bill_len AS x, bill_dep AS y DRAW point FACET species BY island -LABEL +TITLE main => 'Bill Dimensions by Species and Island', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' @@ -53,7 +53,7 @@ SELECT bill_len, bill_dep, species FROM ggsql:penguins VISUALISE bill_len AS x, bill_dep AS y DRAW point FACET species SETTING free => 'y' -LABEL +TITLE main => 'Bill Dimensions (Free Y Scale)', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' diff --git a/doc/gallery/examples/histogram.qmd b/doc/gallery/examples/histogram.qmd index 03f677ccd..4700ec1e2 100644 --- a/doc/gallery/examples/histogram.qmd +++ b/doc/gallery/examples/histogram.qmd @@ -14,7 +14,7 @@ Histograms show the distribution of a numeric variable by grouping values into b SELECT Temp FROM ggsql:airquality VISUALISE Temp AS x DRAW histogram -LABEL +TITLE main => 'Temperature Distribution', x => 'Temperature (F)', y => 'Count' @@ -37,7 +37,7 @@ SELECT Temp FROM ggsql:airquality VISUALISE Temp AS x DRAW histogram SETTING bins => 15 -LABEL +TITLE main => 'Temperature Distribution (15 bins)', x => 'Temperature (F)', y => 'Count' @@ -52,7 +52,7 @@ SELECT Temp FROM ggsql:airquality VISUALISE Temp AS x DRAW histogram SETTING binwidth => 5 -LABEL +TITLE main => 'Temperature Distribution (5 degree bins)', x => 'Temperature (F)', y => 'Count' @@ -67,7 +67,7 @@ SELECT Temp FROM ggsql:airquality VISUALISE Temp AS x DRAW histogram REMAPPING density AS y -LABEL +TITLE main => 'Temperature Density', x => 'Temperature (F)', y => 'Density' diff --git a/doc/gallery/examples/line-chart.qmd b/doc/gallery/examples/line-chart.qmd index 12f5be631..e03a6f3e4 100644 --- a/doc/gallery/examples/line-chart.qmd +++ b/doc/gallery/examples/line-chart.qmd @@ -15,7 +15,7 @@ SELECT Date, Temp FROM ggsql:airquality VISUALISE Date AS x, Temp AS y DRAW line SCALE x VIA date -LABEL +TITLE main => 'Daily Temperature', x => 'Date', y => 'Temperature (F)' @@ -27,7 +27,7 @@ LABEL - `VISUALISE Date AS x, Temp AS y` maps the date column to x and temperature to y - `DRAW line` connects data points with lines - `SCALE x VIA date` ensures the x-axis is formatted as dates with appropriate tick marks (happens automatically if your database has a dedicated date type) -- `LABEL` provides descriptive titles for the chart and axes +- `TITLE` provides descriptive titles for the chart and axes ## Variations @@ -40,7 +40,7 @@ SELECT Day, Temp, Month FROM ggsql:airquality VISUALISE Day AS x, Temp AS y, Month AS color DRAW line SCALE ORDINAL color -LABEL +TITLE main => 'Daily Temperature by Month', x => 'Date', y => 'Temperature (F)' diff --git a/doc/gallery/examples/minard.qmd b/doc/gallery/examples/minard.qmd index f30054260..40dca7fba 100644 --- a/doc/gallery/examples/minard.qmd +++ b/doc/gallery/examples/minard.qmd @@ -159,7 +159,7 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' ``` An additional obvious way to polish your graphic is to add nicer titles for all your variables. -We can use the `LABEL` statement to add custom labels for our plot. +We can use the `TITLE` statement to add custom labels for our plot. In the title, we escape the single quote mark by using `\'` so that we know it is not the end of the string yet. Moreover, we can use `null` to note that a title should be removed. In that way we can hide the `long` and `lat` labels from the position mapping. @@ -175,7 +175,7 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' SCALE stroke TO ('burlywood', 'black') RENAMING 'A' => 'Advance', 'R' => 'Retreat' SCALE linewidth FROM (0, null) TO (0, 20) - LABEL + TITLE main => 'Napoleon\'s Russian Campaign', sub => 'Inspired by the graphic of C.J. Minard', linewidth => 'Troops', diff --git a/doc/gallery/examples/multi-layer.qmd b/doc/gallery/examples/multi-layer.qmd index fc297f4e1..824ca8fd8 100644 --- a/doc/gallery/examples/multi-layer.qmd +++ b/doc/gallery/examples/multi-layer.qmd @@ -18,7 +18,7 @@ DRAW line DRAW point SETTING size => 4, color => 'darkblue' SCALE x VIA date -LABEL +TITLE main => 'Temperature with Line and Points', x => 'Date', y => 'Temperature (F)' @@ -45,7 +45,7 @@ DRAW line DRAW line MAPPING Ozone AS y, 'Ozone' AS color SCALE x VIA date -LABEL +TITLE main => 'Temperature and Ozone Over Time', x => 'Date', y => 'Value' @@ -69,7 +69,7 @@ DRAW point MAPPING Date AS x, value AS y, 'Ozone' AS color FROM ozone SETTING size => 3 SCALE x VIA date -LABEL +TITLE main => 'Temperature vs Ozone', x => 'Date', y => 'Value' diff --git a/doc/gallery/examples/scatterplot.qmd b/doc/gallery/examples/scatterplot.qmd index c48f29586..c48b4c806 100644 --- a/doc/gallery/examples/scatterplot.qmd +++ b/doc/gallery/examples/scatterplot.qmd @@ -14,7 +14,7 @@ This is one of the most fundamental visualization types for exploring correlatio ```{ggsql} VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point -LABEL +TITLE main => 'Penguin Bill Dimensions', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' @@ -25,7 +25,7 @@ LABEL - `VISUALISE ... FROM ggsql:penguins` loads the built-in penguins dataset - `bill_len AS x, bill_dep AS y` maps bill length to the x-axis and bill depth to the y-axis - `DRAW point` creates a scatter plot using points -- `LABEL` adds descriptive axis labels and a title +- `TITLE` adds descriptive axis labels and a title ## Variations @@ -36,7 +36,7 @@ We're adding `species AS color` to the mapping to colour the points by species. ```{ggsql} VISUALISE bill_len AS x, bill_dep AS y, species AS color FROM ggsql:penguins DRAW point -LABEL +TITLE main => 'Penguin Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' @@ -48,7 +48,7 @@ The color palette can be changed by detailing the `SCALE color` clause. VISUALISE bill_len AS x, bill_dep AS y, species AS color FROM ggsql:penguins DRAW point SCALE color TO ('DeepSkyBlue', 'Fuchsia', 'Lime') -LABEL +TITLE main => 'Penguin Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' @@ -66,7 +66,7 @@ VISUALISE island AS shape FROM ggsql:penguins DRAW point -LABEL +TITLE main => 'Penguin Bill Dimensions by Species', x => 'Bill Length (mm)', y => 'Bill Depth (mm)' diff --git a/doc/get_started/first_plot.qmd b/doc/get_started/first_plot.qmd index 6b6ae08a5..0a89427aa 100644 --- a/doc/get_started/first_plot.qmd +++ b/doc/get_started/first_plot.qmd @@ -9,7 +9,7 @@ VISUALISE bill_len AS x, bill_dep AS y, species AS fill FROM ggsql:penguins DRAW point SCALE x RENAMING * => '{} mm' -LABEL +TITLE main => 'Relationship between bill dimensions in 3 species of penguins', x => 'Bill length', y => 'Bill depth' diff --git a/doc/get_started/grammar.qmd b/doc/get_started/grammar.qmd index b760f7138..4798386d3 100644 --- a/doc/get_started/grammar.qmd +++ b/doc/get_started/grammar.qmd @@ -33,7 +33,7 @@ Then you'll use `VISUALIZE` (or `VISUALISE` 🇬🇧) to switch from creating a Then you'll `DRAW` a layer that maps columns in your data to aesthetics (visual properties), like position, colour, and shape. Then you tweak the `SCALE`s, the mappings between the data and the visual properties, to make the plot easier to read. Then you `FACET` the plot to show how the relationships differ across subsets of the data. -Finally you finish up by adding `LABEL`s to explain your plot to others. +Finally you finish up by adding `TITLE`s to explain your plot to others. This allows you to produce graphics using the same structured thinking that you already use to design a SQL query. In the end of this tutorial we will revisit the duality of the syntax and the grammar and also provide a [handy table](wrap_up.qmd#from-grammar-to-syntax) that shows how they relate to each other. diff --git a/doc/get_started/the_rest.qmd b/doc/get_started/the_rest.qmd index 7e8079866..d134cdc20 100644 --- a/doc/get_started/the_rest.qmd +++ b/doc/get_started/the_rest.qmd @@ -43,12 +43,12 @@ Faceting is applied with the [`FACET`](../syntax/clause/facet.qmd) clause. It al There is an alternative to using the `FACET` variable, which is to map the variables directly to the facet aesthetics. There are three of these: `panel` is used when faceting by a single variable and `row` and `column` is used when faceting by two variables. `FACET var` is thus equivalent to `VISUALISE var AS panel`. Whichever you choose to use is thus a matter of personal preference, as well as whether you also need to modify faceting behavior (in which case you'd need a `FACET` clause anyway). -### `LABEL` -ggsql automatically labels the axes and legends in your plot by the column name of the data mapped to it. However, you often want to provide more descriptive names as well as a title to give context to the plot. All of this is accomplished with the [`LABEL`](../syntax/clause/label.qmd) clause by setting the label text for both titles, subtitles, etc. as well as any -aesthetic you have mapped. A `LABEL` clause may end up looking like this: +### `TITLE` +ggsql automatically labels the axes and legends in your plot by the column name of the data mapped to it. However, you often want to provide more descriptive names as well as a title to give context to the plot. All of this is accomplished with the [`TITLE`](../syntax/clause/title.qmd) clause by setting the label text for both titles, subtitles, etc. as well as any +aesthetic you have mapped. A `TITLE` clause may end up looking like this: ```ggsql -LABEL +TITLE main => "Average wingspan of a cartoon owl" x => "Radius of first circle (cm)" y => "Wingspan (cm)" @@ -105,7 +105,7 @@ SCALE panel FROM ('Biscoe', 'Dream') Above, we use the `free` parameter of facet to allow each facet to have their own angle scale. Further, we use `SCALE` on the panel aesthetic to only show panels for the Biscoe and Dream islands. -We can use `LABEL` to add a bit more context to our final plot: +We can use `TITLE` to add a bit more context to our final plot: ```{ggsql} VISUALISE species AS fill FROM ggsql:penguins @@ -114,7 +114,7 @@ PROJECT TO polar FACET island SETTING free => 'angle' SCALE panel FROM ('Biscoe', 'Dream') -LABEL +TITLE main => 'Distribution of penguin species between islands', sub => 'Compared across 344 penguins', fill => 'Species' diff --git a/doc/ggsql.xml b/doc/ggsql.xml index b7376fe7b..f97063ac0 100644 --- a/doc/ggsql.xml +++ b/doc/ggsql.xml @@ -249,8 +249,8 @@ - title - subtitle + main + sub caption tag @@ -389,7 +389,7 @@ - + @@ -437,7 +437,7 @@ - + @@ -478,7 +478,7 @@ - + @@ -518,7 +518,7 @@ - + @@ -565,7 +565,7 @@ - + @@ -609,7 +609,7 @@ - + @@ -638,8 +638,8 @@ - - + + @@ -652,7 +652,7 @@ - + @@ -687,7 +687,7 @@ - + @@ -725,7 +725,7 @@ - + @@ -766,7 +766,7 @@ - + @@ -818,7 +818,7 @@ - + diff --git a/doc/index.qmd b/doc/index.qmd index 0005569bd..6d7110caf 100644 --- a/doc/index.qmd +++ b/doc/index.qmd @@ -47,7 +47,7 @@ DRAW point PLACE rule SETTING slope => 0.4, y => -1 SCALE BINNED fill -LABEL +TITLE main => 'Relationship between bill dimensions in 3 species of penguins', x => 'Bill length (mm)', y => 'Bill depth (mm)' diff --git a/doc/syntax/clause/facet-tabulate.qmd b/doc/syntax/clause/facet-tabulate.qmd index 841eaa427..f6f1e1a17 100644 --- a/doc/syntax/clause/facet-tabulate.qmd +++ b/doc/syntax/clause/facet-tabulate.qmd @@ -99,11 +99,11 @@ FACET species, island SETTING separator => ' - ' ``` -When group labels are placed in the stub, the labels can be controlled by `LABEL`. +When group labels are placed in the stub, the labels can be controlled by `TITLE`. In case of `separator`-joined labels, the first variable (`species` in the example) displays the label. ```{ggsql} TABULATE * FROM my_data FACET species, island -LABEL island => 'Place', species => 'Type' +TITLE island => 'Place', species => 'Type' ``` diff --git a/doc/syntax/clause/format.qmd b/doc/syntax/clause/format.qmd index ac657c6b5..9678c4003 100644 --- a/doc/syntax/clause/format.qmd +++ b/doc/syntax/clause/format.qmd @@ -88,7 +88,7 @@ RENAMING => , ... The `RENAMING` clause is *the* place to format the cell contents. It works the same as the namesake in the [`SCALE`](scale.qmd#renaming) clause. -Generally, it works not unlike the [`LABEL`](label-tabulate.qmd) clause in the sense that you specify a cell's content on the left and a replacement value on the right. +Generally, it works not unlike the [`TITLE`](title-tabulate.qmd) clause in the sense that you specify a cell's content on the left and a replacement value on the right. Alternatively, you can use a formatter with the `* => '...'` syntax. Specifically see the [break formatting](scale.qmd#break-formatting) section for a list of formatters. @@ -115,12 +115,12 @@ TABULATE * FROM my_data ``` Stubheads, the column labels for stub columns, are hidden by default. -To display these, you can use the `LABEL` clause. +To display these, you can use the `TITLE` clause. ```{ggsql} TABULATE * FROM my_data FORMAT STUB island - LABEL island => 'Island' + TITLE island => 'Island' ``` Stub columns cannot be targetted by spans. The boundary between stub and body is un-spannable. diff --git a/doc/syntax/clause/scale.qmd b/doc/syntax/clause/scale.qmd index b5b1450b3..864330b85 100644 --- a/doc/syntax/clause/scale.qmd +++ b/doc/syntax/clause/scale.qmd @@ -57,7 +57,7 @@ This clause behaves much like the `SETTINGS` clause in `DRAW`, in that it allows RENAMING => , ... ``` -This clause works much like the `LABEL` clause but works on the break names of the scale. The general syntax is that you provide the name of the break on the left and what it should appear as on the right, e.g `'adelie' => 'Pygoscelis adeliae'`. The clause is understood as a look-up table in the sense that if you provide a renaming for a break that doesn't appear in the scale then nothing will happen and if a break exists but doesn't have a renaming defined it will go through unaltered. To suppress the label of a specific break you can rename it to `null`, e.g. `'adelie' => null`. This will not remove the break, only the label. +This clause works much like the `TITLE` clause but works on the break names of the scale. The general syntax is that you provide the name of the break on the left and what it should appear as on the right, e.g `'adelie' => 'Pygoscelis adeliae'`. The clause is understood as a look-up table in the sense that if you provide a renaming for a break that doesn't appear in the scale then nothing will happen and if a break exists but doesn't have a renaming defined it will go through unaltered. To suppress the label of a specific break you can rename it to `null`, e.g. `'adelie' => null`. This will not remove the break, only the label. #### Break formatting Apart from the direct renaming described above it is also possible to provide a formatting function to be applied to all breaks. The syntax for this is `* => '...'` with the content of the string on the right being a string interpolation format. The basic syntax for this is that the break value will be inserted into any place where `{}` appears. This means that e.g. `* => '{} species'` will result in the label "adelie species" for the break "adelie". Besides simply inserting the value as-is, it is also possible to apply a formatter to the label before insertion by naming a formatter inside the curly braces prefixed with `:`. Known formatters are: diff --git a/doc/syntax/clause/span.qmd b/doc/syntax/clause/span.qmd index aa1d990a6..2f46c7845 100644 --- a/doc/syntax/clause/span.qmd +++ b/doc/syntax/clause/span.qmd @@ -37,11 +37,11 @@ The identifier can be these values: * An identifier with double-quotes or backtick-quotes, depending on the backend * `null` -A spanner can also be labelled using the [`LABEL`](label-tabulate.qmd) clause, using the span identifier as key. +A spanner can also be labelled using the [`TITLE`](title-tabulate.qmd) clause, using the span identifier as key. This is the preferred method if the label contains exotic symbols that are not allowed in identifiers. A spanner identifier can **not** be the same as a column name. -If you want to display the same label as a column name, you can use the [`LABEL`](label-tabulate.qmd) clause too. +If you want to display the same label as a column name, you can use the [`TITLE`](title-tabulate.qmd) clause too. Giving `null` as identifier makes an anonymous spanner for the side-effect of ordering columns. Anonymous spanners do not render labels. @@ -107,12 +107,12 @@ TABULATE * FROM my_data SPAN Lengths OVER Bill, flipper_len ``` -The `LABEL` clause can be used for complex labels. +The `TITLE` clause can be used for complex labels. ```{ggsql} TABULATE * FROM my_data SPAN Bill OVER bill_len, bill_dep - LABEL Bill => '🐧 bills' + TITLE Bill => '🐧 bills' ``` Anonymous spanners can be used to reorder columns. diff --git a/doc/syntax/clause/tabulate.qmd b/doc/syntax/clause/tabulate.qmd index 2a370e021..388e6bab5 100644 --- a/doc/syntax/clause/tabulate.qmd +++ b/doc/syntax/clause/tabulate.qmd @@ -32,9 +32,9 @@ The columns can be selected in (a mixture of) one of three forms: Without the `*` wildcard, only the listed columns are kept. The wildcard can be combined with explicit columns to partially order columns, where the wildcard becomes all implicit columns. -When a column is renamed using the `AS` keyword, other table clauses --- like `LABEL`, `SPAN` and `FORMAT` --- use the *new* name. +When a column is renamed using the `AS` keyword, other table clauses --- like `TITLE`, `SPAN` and `FORMAT` --- use the *new* name. Please note that renaming a column consumes the original, to avoid unintentional duplication. -It is discouraged to name column `title`, `subtitle` or `caption` as these are keywords in the [`LABEL`](label-tabulate.qmd) clause. +It is discouraged to name column `main`, `sub` or `caption` as these are keywords in the [`TITLE`](title-tabulate.qmd) clause. ```ggsql -- Select all columns @@ -92,7 +92,7 @@ Reordering columns TABULATE island, *, species FROM my_data ``` -Renaming columns on the fly. For order-preserving renames, see [`LABEL`](label-tabulate.qmd) clause. +Renaming columns on the fly. For order-preserving renames, see [`TITLE`](title-tabulate.qmd) clause. ```{ggsql} TABULATE diff --git a/doc/syntax/clause/label-tabulate.qmd b/doc/syntax/clause/title-tabulate.qmd similarity index 67% rename from doc/syntax/clause/label-tabulate.qmd rename to doc/syntax/clause/title-tabulate.qmd index 85e3e4edc..f57ce8658 100644 --- a/doc/syntax/clause/label-tabulate.qmd +++ b/doc/syntax/clause/title-tabulate.qmd @@ -1,20 +1,20 @@ --- -title: "Define different titles with `LABEL`" +title: "Define different titles with `TITLE`" --- ::: {.callout-note} -This page is about the `TABULATE` usage of the `LABEL` clause. -For the `VISUALISE` usage, see [this page](label.qmd). +This page is about the `TABULATE` usage of the `TITLE` clause. +For the `VISUALISE` usage, see [this page](title.qmd). ::: -The `LABEL` clause is a straightforward clause allowing you to override the default naming of column labels, spans, (sub)titles and captions. +The `TITLE` clause is a straightforward clause allowing you to override the default naming of column labels, spans, (sub)titles and captions. Unlike `VISUALISE`'s usage, there is no automatic labelling: a column with no label keeps its name as header. ## Clause syntax -The `LABEL` clause requires a comma-separated list of key-value pairs +The `TITLE` clause requires a comma-separated list of key-value pairs ```ggsql -LABEL => , ... +TITLE => , ... ``` On the left hand side of the arrow, the following keys can be used: @@ -33,27 +33,27 @@ The support of rich text in tables is planned but not yet implemented. ## Examples -Unlike using aliases in `TABULATE`, the `LABEL` clause lets you change column labels without changing column order +Unlike using aliases in `TABULATE`, the `TITLE` clause lets you change column labels without changing column order ```{ggsql} CREATE TEMP TABLE my_data AS SELECT * FROM ggsql:penguins LIMIT 5 TABULATE * FROM my_data - LABEL bill_len => 'Bill length', bill_dep => 'Bill depth' + TITLE bill_len => 'Bill length', bill_dep => 'Bill depth' ``` Hiding labels. ```{ggsql} TABULATE * FROM my_data - LABEL island => null, species => null + TITLE island => null, species => null ``` Adding titles to a table. ```{ggsql} TABULATE * FROM my_data - LABEL + TITLE main => 'Penguins!', sub => 'Structural size measurements', caption => 'Source: Palmer station, Antarctica' @@ -62,20 +62,20 @@ TABULATE * FROM my_data When column names and reserved keywords compete for a label, the reserved keyword wins. ```{ggsql} --- data has column named 'title' +-- data has column named 'main' CREATE TEMP TABLE title_data AS -SELECT * FROM (VALUES (1, 'a'), (2, 'b'), (3, 'c')) AS t(id, title) +SELECT * FROM (VALUES (1, 'a'), (2, 'b'), (3, 'c')) AS t(id, main) TABULATE * FROM title_data - LABEL + TITLE main => 'Overrules column' ``` You can target an aliased column instead. ```{ggsql} -TABULATE *, title AS title_col FROM title_data - LABEL +TABULATE *, main AS main_col FROM title_data + TITLE main => 'Main title', - title_col => 'Column title' -``` \ No newline at end of file + main_col => 'Column title' +``` diff --git a/doc/syntax/clause/label.qmd b/doc/syntax/clause/title.qmd similarity index 81% rename from doc/syntax/clause/label.qmd rename to doc/syntax/clause/title.qmd index ebe7e8763..24a072325 100644 --- a/doc/syntax/clause/label.qmd +++ b/doc/syntax/clause/title.qmd @@ -1,19 +1,19 @@ --- -title: "Define different titles with `LABEL`" +title: "Define different titles with `TITLE`" --- ::: {.callout-note} -This page is about the `VISUALISE` usage of the `LABEL` clause. -For the `TABULATE` usage, see [this page](label-tabulate.qmd). +This page is about the `VISUALISE` usage of the `TITLE` clause. +For the `TABULATE` usage, see [this page](title-tabulate.qmd). ::: -The `LABEL` clause is one of the simpler clauses in ggsql and allows you to override the default naming of axes and legends, as well as adding titles to the plot. +The `TITLE` clause is one of the simpler clauses in ggsql and allows you to override the default naming of axes and legends, as well as adding titles to the plot. ## Clause syntax -The `LABEL` clause takes one or more labeling settings. +The `TITLE` clause takes one or more labeling settings. ```ggsql -LABEL => , ... +TITLE => , ... ``` If an `aesthetic` is given, then the title will be used for the relevant axis or legend, e.g. `x => 'my x-axis'` will label the x axis, whereas `fill => 'Species'` will label the legend for fill (if any). @@ -25,7 +25,7 @@ There are a few additional labels beside the aesthetics that govern the differen * `caption`: A string placed below the plot, often used to add additional information about the data source etc. Supported by every writer except Vega-Lite, which has no equivalent. ## Rich text -Every writer except Vega-Lite interprets the strings you provide here as markdown, so `LABEL main => 'Sales in **2024**'` renders the year in bold. +Every writer except Vega-Lite interprets the strings you provide here as markdown, so `TITLE main => 'Sales in **2024**'` renders the year in bold. This applies to the plot title, subtitle and caption, to the axis and legend titles, and to break labels (axis tick labels and legend keys). The Vega-Lite writer has no rich-text support at all and draws every label exactly as given. @@ -39,7 +39,7 @@ Axes and legends get an automatic label from the mapping. The logic is as follow 1. Start from the global mapping and then go through the layer mappings as they appear. 2. Collect mappings for each aesthetic in the order they appear 3. For each aesthetic determine the label based on the following priority: - 1. An explicitly provided one with `LABEL` + 1. An explicitly provided one with `TITLE` 2. The name of the first appearing column mapping 3. The name of the aesthetic diff --git a/doc/syntax/index.qmd b/doc/syntax/index.qmd index f00a94101..7f78d5c7a 100644 --- a/doc/syntax/index.qmd +++ b/doc/syntax/index.qmd @@ -11,12 +11,12 @@ ggsql augments the standard SQL syntax with a number of new clauses to describe - [`SCALE`](clause/scale.qmd) specifies how an aesthetic should be scaled - [`FACET`](clause/facet.qmd) describes how data should be split into small multiples - [`PROJECT`](clause/project.qmd) is used for selecting the coordinate system to use -- [`LABEL`](clause/label.qmd) is used to manually add titles to the plot or the various axes and legends +- [`TITLE`](clause/title.qmd) is used to manually add titles to the plot or the various axes and legends ## Table clauses - [`TABULATE`](clause/tabulate.qmd) initialises the table part of the query -- [`LABEL`](clause/label-tabulate.qmd) is used to manually change column labels and titles +- [`TITLE`](clause/title-tabulate.qmd) is used to manually change column labels and titles - [`SPAN`](clause/span.qmd) can be used to group columns and display a label across them - [`FORMAT`](clause/format.qmd) declares formatting for columns - [`FACET`](clause/facet-tabulate.qmd) enables row-grouping operations on tables diff --git a/doc/syntax/scale/aesthetic/0_position.qmd b/doc/syntax/scale/aesthetic/0_position.qmd index 790a9000c..621880651 100644 --- a/doc/syntax/scale/aesthetic/0_position.qmd +++ b/doc/syntax/scale/aesthetic/0_position.qmd @@ -29,4 +29,4 @@ The recognized suffixes are: Which version of an aesthetic to use depends on the layer. All aesthetics within a family use the same scale, which is named after its primary aesthetic. -This means that even when rendering a layer that only uses `xmin` and `xmax`, you will still scale it by writing `SCALE x ...` and label it by writing `LABEL x => ...` +This means that even when rendering a layer that only uses `xmin` and `xmax`, you will still scale it by writing `SCALE x ...` and label it by writing `TITLE x => ...` diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index ed52e47cd..fd8458ab8 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -20,7 +20,7 @@ Optional SQL part + required `VISUALISE`/`VISUALIZE` part. ```ggsql SELECT name, score_a, score_b FROM 'dataset.csv' WHERE value > 50 VISUALISE score_a AS x, score_b AS y - [DRAW / PLACE / SCALE / FACET / PROJECT / LABEL clauses] + [DRAW / PLACE / SCALE / FACET / PROJECT / TITLE clauses] ``` - **VISUALISE FROM**: VISUALISE supplies its own source (table/file/CTE/built-in), no trailing SELECT. ```ggsql @@ -136,11 +136,11 @@ PROJECT , ... TO SETTING => , ... PROJECT TO polar SETTING inner => 0.5 -- donut chart ``` -## LABEL clause +## TITLE clause Overrides axis/legend labels & titles: `main`, `sub`, `caption`, or any aesthetic name; `null` suppresses. ```ggsql -LABEL main => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null +TITLE main => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null ``` --- @@ -150,17 +150,17 @@ LABEL main => 'Sales by Region', x => 'Date', y => 'Revenue (USD)', fill => null Renders the query result as a table instead of a plot — the plain-table counterpart to VISUALISE. Only the HTML writer supports tables. Both data patterns from VISUALISE apply (`SELECT ... TABULATE *` or `TABULATE ... FROM `). -`LABEL`, `SPAN` and `FORMAT` may each appear multiple times, in any order. +`TITLE`, `SPAN` and `FORMAT` may each appear multiple times, in any order. ### Column selection - `` — keep as-is; ` AS ` — rename; `*` — all columns in source order - Order controls display order; `*` can be mixed with named columns: `TABULATE foo, *, baz` -- A rename changes the actual column name, so `LABEL`/`SPAN`/`FORMAT` refer to the new name +- A rename changes the actual column name, so `TITLE`/`SPAN`/`FORMAT` refer to the new name -### LABEL (table) +### TITLE (table) -Keyed by column name, not aesthetic. Reserved keys: `main`, `sub`, `caption`. `null` blanks a header; if all headers are blank the header row is omitted. Also labels spanners via their SPAN id: `LABEL q1 => 'Q1 Totals'`. No automatic labelling and no markdown — a column without a `LABEL` keeps its name. +Keyed by column name, not aesthetic. Reserved keys: `main`, `sub`, `caption`. `null` blanks a header; if all headers are blank the header row is omitted. Also labels spanners via their SPAN id: `TITLE q1 => 'Q1 Totals'`. No automatic labelling and no markdown — a column without a `TITLE` keeps its name. ### SPAN @@ -188,7 +188,7 @@ Configures cell display and column placement. ```ggsql SELECT * FROM ggsql:penguins LIMIT 5 TABULATE * - LABEL main => 'Penguins!', bill_len => 'Length', bill_dep => 'Depth' + TITLE main => 'Penguins!', bill_len => 'Length', bill_dep => 'Depth' SPAN Bill OVER bill_len, bill_dep FORMAT STUB species FORMAT body_mass SETTING hjust => 'right' RENAMING null => '-', * => '{:num %.0f}g' @@ -273,7 +273,7 @@ https://ggsql.org/syntax/index.llms.md — latest syntax docs. ## Instructions for responding 1. Write a complete, valid ggsql query for the request; use SQL/CTEs before VISUALISE for data shaping. -2. Choose the simplest layer types/settings that work; add SCALE for formatting/palettes/ranges and LABEL for titles when warranted. +2. Choose the simplest layer types/settings that work; add SCALE for formatting/palettes/ranges and TITLE for titles when warranted. 3. Briefly explain your choices after the query. Never invent syntax — say so if unsure. 4. Default to `ggsql:penguins`/`ggsql:airquality` when no data is specified. 5. Use `ggsql validate ""` to validate, `ggsql exec "" -v` to run and show output. diff --git a/ggsql-jupyter/README.md b/ggsql-jupyter/README.md index 46aee85bd..3f5b326c0 100644 --- a/ggsql-jupyter/README.md +++ b/ggsql-jupyter/README.md @@ -139,7 +139,7 @@ VISUALISE date AS x, revenue AS y DRAW line SCALE x SETTING type => 'date' -LABEL main => 'Revenue Growth', x => 'Date', y => 'Revenue ($)' +TITLE main => 'Revenue Growth', x => 'Date', y => 'Revenue ($)' ``` #### Multi-Layer Plot with Global Mapping @@ -153,7 +153,7 @@ DRAW line MAPPING y AS y DRAW line MAPPING z AS y -LABEL main => 'Polynomial Functions' +TITLE main => 'Polynomial Functions' ``` #### Pure SQL (Data Tables) @@ -183,5 +183,5 @@ Cell 2: SELECT * FROM products VISUALISE name AS x, price AS y DRAW bar -LABEL main => 'Product Prices', y => 'Price ($)' +TITLE main => 'Product Prices', y => 'Price ($)' ``` diff --git a/ggsql-jupyter/src/kernel.rs b/ggsql-jupyter/src/kernel.rs index c90dcc2b2..92a22df9c 100644 --- a/ggsql-jupyter/src/kernel.rs +++ b/ggsql-jupyter/src/kernel.rs @@ -1037,7 +1037,7 @@ impl KernelServer { let comm_id = uuid::Uuid::new_v4().to_string(); self.plot_seq = self.plot_seq.saturating_add(1); - let title = spec.plot().labels.get("title"); + let title = spec.plot().titles.get("main"); let metadata = PlotMetadata { name: crate::plot::comm::plot_name(title, self.plot_seq), execution_id: parent.header.msg_id.clone(), diff --git a/ggsql-jupyter/src/plot/comm.rs b/ggsql-jupyter/src/plot/comm.rs index 907ad1070..e067ee71e 100644 --- a/ggsql-jupyter/src/plot/comm.rs +++ b/ggsql-jupyter/src/plot/comm.rs @@ -196,7 +196,7 @@ impl PlotMetadata { /// A plot's name for the pane's history list. /// -/// The `LABEL title` if the query set one, else a running count, matching how +/// The `TITLE main` if the query set one, else a running count, matching how /// the other language backends name an untitled figure. pub fn plot_name(title: Option<&str>, sequence: u32) -> String { match title.map(str::trim).filter(|t| !t.is_empty()) { diff --git a/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb b/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb index 37f9d14e8..c08ae4519 100644 --- a/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb +++ b/ggsql-jupyter/tests/fixtures/sample_notebook.ipynb @@ -101,7 +101,7 @@ "FROM generate_series(1, 10) as t(n)\n", "VISUALISE x, y\n", "DRAW point\n", - "LABEL main => 'Quadratic Function', x => 'X Value', y => 'Y Value'" + "TITLE main => 'Quadratic Function', x => 'X Value', y => 'Y Value'" ] }, { @@ -123,7 +123,7 @@ "VISUALISE date AS x, revenue AS y, product AS color\n", "DRAW line\n", "SCALE x SETTING type => 'date'\n", - "LABEL main => 'Sales Revenue Over Time', x => 'Date', y => 'Revenue ($)'" + "TITLE main => 'Sales Revenue Over Time', x => 'Date', y => 'Revenue ($)'" ] }, { @@ -146,7 +146,7 @@ "DRAW line\n", "DRAW point\n", "SCALE x SETTING type => 'date'\n", - "LABEL main => 'Sales with Data Points', x => 'Date', y => 'Revenue ($)'" + "TITLE main => 'Sales with Data Points', x => 'Date', y => 'Revenue ($)'" ] }, { @@ -167,7 +167,7 @@ "GROUP BY product\n", "VISUALISE product AS x, total_revenue AS y\n", "DRAW bar\n", - "LABEL main => 'Total Revenue by Product', x => 'Product', y => 'Total Revenue ($)'" + "TITLE main => 'Total Revenue by Product', x => 'Product', y => 'Total Revenue ($)'" ] }, { @@ -190,7 +190,7 @@ "DRAW line\n", "FACET region\n", "SCALE x SETTING type => 'date'\n", - "LABEL main => 'Revenue by Region', x => 'Date', y => 'Revenue ($)'" + "TITLE main => 'Revenue by Region', x => 'Date', y => 'Revenue ($)'" ] } ], diff --git a/ggsql-jupyter/tests/fixtures/test_queries.sql b/ggsql-jupyter/tests/fixtures/test_queries.sql index 15198b53b..0c99fed36 100644 --- a/ggsql-jupyter/tests/fixtures/test_queries.sql +++ b/ggsql-jupyter/tests/fixtures/test_queries.sql @@ -20,7 +20,7 @@ SELECT n as x, n * n as y FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW line -LABEL main => 'Quadratic Function', x AS 'X', y AS 'Y'; +TITLE main => 'Quadratic Function', x AS 'X', y AS 'Y'; -- Multi-layer visualization with global mapping SELECT n as x, n * n as y @@ -28,7 +28,7 @@ FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW line DRAW point -LABEL main => 'Line with Points'; +TITLE main => 'Line with Points'; -- Date-based visualization with global mapping SELECT @@ -39,7 +39,7 @@ FROM generate_series(0, 30) as t(n) VISUALISE date AS x, value AS y, category AS color DRAW line SCALE x SETTING type => 'date' -LABEL main => 'Time Series', x => 'Date', y => 'Value'; +TITLE main => 'Time Series', x => 'Date', y => 'Value'; -- Bar chart with global mapping SELECT @@ -48,7 +48,7 @@ SELECT FROM generate_series(0, 4) as t(n) VISUALISE category AS x, value AS y DRAW bar -LABEL main => 'Bar Chart', x AS 'Category', y AS 'Value'; +TITLE main => 'Bar Chart', x AS 'Category', y AS 'Value'; -- Faceted visualization with global mapping SELECT @@ -59,7 +59,7 @@ FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW point FACET group -LABEL main => 'Faceted Plot'; +TITLE main => 'Faceted Plot'; -- Visualization with FILTER clause - global mapping with layer filter SELECT @@ -69,7 +69,7 @@ FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW line DRAW point FILTER y > 25 -LABEL main => 'Filtered Points'; +TITLE main => 'Filtered Points'; -- Visualization with SETTING parameters SELECT @@ -78,7 +78,7 @@ SELECT FROM generate_series(1, 10) as t(n) VISUALISE x, y DRAW point SETTING size => 10, opacity => 0.5 -LABEL main => 'Points with Parameters'; +TITLE main => 'Points with Parameters'; -- Error case: invalid table SELECT * FROM nonexistent_table; diff --git a/ggsql-vscode/README.md b/ggsql-vscode/README.md index 31969cead..e47dd0762 100644 --- a/ggsql-vscode/README.md +++ b/ggsql-vscode/README.md @@ -18,7 +18,7 @@ VISUALISE date AS x, revenue AS y, region AS color DRAW line SCALE x SETTING breaks => 'month' -LABEL main => 'Sales by Region' +TITLE main => 'Sales by Region' ``` ## Installation diff --git a/ggsql-vscode/examples/sample.gsql b/ggsql-vscode/examples/sample.gsql index 03b135e5d..00e9db722 100644 --- a/ggsql-vscode/examples/sample.gsql +++ b/ggsql-vscode/examples/sample.gsql @@ -6,7 +6,7 @@ -- ============================================================================ VISUALISE hp AS x, mpg AS y, cyl AS color FROM 'mtcars.csv' DRAW point -LABEL main => 'Horsepower vs Fuel Efficiency', +TITLE main => 'Horsepower vs Fuel Efficiency', x => 'Horsepower', y => 'Miles per Gallon' @@ -29,7 +29,7 @@ DRAW point SETTING size => 3 SCALE x SETTING type => 'date' SCALE color TO viridis FACET region SETTING scales => 'free_y' -LABEL main => 'Sales Trends by Region', +TITLE main => 'Sales Trends by Region', x => 'Month', y => 'Total Quantity', caption => 'Data from 2024' @@ -46,7 +46,7 @@ LIMIT 10 VISUALISE category AS x, total AS y, category AS fill DRAW bar PROJECT y, x TO cartesian -LABEL main => 'Top 10 Product Categories', +TITLE main => 'Top 10 Product Categories', x => 'Category', y => 'Total Sales' @@ -59,7 +59,7 @@ GROUP BY region VISUALISE region AS x, count AS y, region AS fill DRAW bar PROJECT TO polar -LABEL main => 'Customer Distribution by Region' +TITLE main => 'Customer Distribution by Region' -- ============================================================================ -- Example 5: Faceted Histogram @@ -71,7 +71,7 @@ VISUALISE age AS x, gender AS fill DRAW histogram SCALE x SETTING type => 'linear', limits => (18, 80) FACET gender SETTING scales => 'fixed' -LABEL main => 'Age Distribution by Gender', +TITLE main => 'Age Distribution by Gender', x => 'Age', y => 'Count' @@ -100,7 +100,7 @@ DRAW line SCALE x SETTING type => 'date' SCALE x FROM ('2024-01-01', '2024-12-31') SCALE y SETTING type => 'linear', limits => (0, 100) -LABEL main => 'Temperature Range (Last 30 Days)', +TITLE main => 'Temperature Range (Last 30 Days)', x => 'Date', y => 'Temperature (°C)', caption => 'Source: Weather Station Alpha' @@ -125,7 +125,7 @@ SCALE x SETTING type => 'date' SCALE y SETTING type => 'log10' SCALE DISCRETE color FROM ('Electronics', 'Clothing', 'Food', 'Books') FACET category BY employee_name SETTING scales => 'free_y' -LABEL main => 'Sales Performance Analysis', +TITLE main => 'Sales Performance Analysis', x => 'Sale Date', y => 'Revenue (log scale)', color => 'Product Category', @@ -147,7 +147,7 @@ VISUALISE quarter AS x, revenue AS y, category AS fill FROM quarterly_breakdown DRAW area SETTING opacity => 0.7 SCALE x SETTING type => 'date' SCALE DISCRETE fill FROM ('A', 'B', 'C', 'D') TO plasma -LABEL main => 'Quarterly Revenue by Category', +TITLE main => 'Quarterly Revenue by Category', x => 'Quarter', y => 'Revenue ($)', sub => 'Stacked Area Chart' @@ -162,7 +162,7 @@ VISUALISE category AS x, price AS y DRAW boxplot DRAW violin SETTING opacity => 0.3 SCALE y FROM (0, 500) -LABEL main => 'Price Distribution by Category', +TITLE main => 'Price Distribution by Category', x => 'Product Category', y => 'Price ($)' @@ -186,7 +186,7 @@ SCALE color TO viridis SCALE size SETTING limits => (0, 10000) SCALE x FROM (0, 1000) SCALE y FROM (0, 5) -LABEL main => 'Featured Products: Price vs Rating', +TITLE main => 'Featured Products: Price vs Rating', x => 'Price ($)', y => 'Customer Rating', size => 'Total Sales' @@ -202,12 +202,12 @@ WITH sales_summary AS ( -- First visualization: by region VISUALISE region AS x, total AS y, region AS fill FROM sales_summary DRAW bar -LABEL main => 'Sales by Region' +TITLE main => 'Sales by Region' -- Second visualization: by category VISUALISE category AS x, total AS y, category AS fill FROM sales_summary DRAW bar PROJECT y, x TO cartesian -LABEL main => 'Sales by Category' +TITLE main => 'Sales by Category' -- ============================================================================ -- Example 12: FILTER clause for layer-specific filtering @@ -218,7 +218,7 @@ VISUALISE date AS x, value AS y, category AS color DRAW line DRAW point FILTER value > 50 SCALE x SETTING type => 'date' -LABEL main => 'Metrics with Highlighted Points Above 50' +TITLE main => 'Metrics with Highlighted Points Above 50' -- ============================================================================ -- Comments and String Handling diff --git a/ggsql-vscode/src/test/grammar/highlight.gsql b/ggsql-vscode/src/test/grammar/highlight.gsql index 4288a699d..ebb0f1d4e 100644 --- a/ggsql-vscode/src/test/grammar/highlight.gsql +++ b/ggsql-vscode/src/test/grammar/highlight.gsql @@ -34,7 +34,7 @@ SCALE DISCRETE color TO viridis SCALE y VIA log10 -- ^^^^^ constant.language.scale-type.ggsql -LABEL main => 'Sales by Region', x => 'Date', y => 'Revenue' +TITLE main => 'Sales by Region', x => 'Date', y => 'Revenue' -- <---- keyword.other.ggsql -- ^^^^^ support.type.property.ggsql -- ^^ keyword.operator.fatarrow.ggsql diff --git a/ggsql-vscode/syntaxes/ggsql.tmLanguage.json b/ggsql-vscode/syntaxes/ggsql.tmLanguage.json index bb2dbc82d..96c7279a1 100644 --- a/ggsql-vscode/syntaxes/ggsql.tmLanguage.json +++ b/ggsql-vscode/syntaxes/ggsql.tmLanguage.json @@ -12,7 +12,7 @@ { "include": "#scale-clause" }, { "include": "#facet-clause" }, { "include": "#project-clause" }, - { "include": "#label-clause" }, + { "include": "#title-clause" }, { "include": "#sql-keywords" }, { "include": "#visualise-clause" }, { "include": "#operators" } @@ -221,7 +221,7 @@ "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "include": "#comments" }, { "include": "#strings" }, @@ -315,7 +315,7 @@ "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "comment": "Geom types from grammar.js", @@ -330,7 +330,7 @@ "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "name": "support.type.geom.ggsql", @@ -344,7 +344,7 @@ "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "comment": "Scale type identifiers from grammar.js", @@ -373,7 +373,7 @@ "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "name": "support.type.property.ggsql", @@ -395,7 +395,7 @@ "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "comment": "Coord types (currently implemented: cartesian, polar)", @@ -410,17 +410,17 @@ { "include": "#common-clause-patterns" } ] }, - "label-clause": { - "begin": "(?i)\\b(LABEL)\\b", + "title-clause": { + "begin": "(?i)\\b(TITLE)\\b", "beginCaptures": { "1": { "name": "keyword.other.ggsql" } }, - "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|LABEL|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", + "end": "(?i)(?=\\b(DRAW|PLACE|SCALE|PROJECT|FACET|TITLE|VISUALISE|VISUALIZE|SELECT|WHERE|WITH)\\b)", "patterns": [ { "comment": "Label types", "name": "support.type.property.ggsql", - "match": "\\b(title|subtitle|x|y|caption|tag|color|colour|fill|size|shape|linetype)\\b" + "match": "\\b(main|sub|x|y|caption|tag|color|colour|fill|size|shape|linetype)\\b" }, { "include": "#common-clause-patterns" } ] diff --git a/ggsql-wasm/demo/src/examples.ts b/ggsql-wasm/demo/src/examples.ts index 5dd6d1d19..4a3405434 100644 --- a/ggsql-wasm/demo/src/examples.ts +++ b/ggsql-wasm/demo/src/examples.ts @@ -69,7 +69,7 @@ DRAW line query: `SELECT * FROM ggsql:penguins VISUALISE DRAW point MAPPING bill_len AS x, bill_dep AS y, body_mass AS size, species AS color -LABEL main => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, +TITLE main => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, }, { section: "Layers", @@ -210,7 +210,7 @@ SCALE shape TO ['star', 'bowtie', 'square-plus']`, query: `SELECT * FROM ggsql:penguins VISUALISE DRAW point MAPPING bill_len AS x, bill_dep AS y, body_mass AS size -LABEL main => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, +TITLE main => 'Penguin Measurements', x => 'Bill Length (mm)', y => 'Bill Depth (mm)'`, }, // === Spatial === @@ -234,7 +234,7 @@ DRAW spatial MAPPING population AS fill SETTING opacity => 1 SCALE fill TO viridis VIA log -LABEL main => 'Population by country', fill => 'Population'`, +TITLE main => 'Population by country', fill => 'Population'`, }, { section: "Spatial", diff --git a/ggsql-wasm/demo/src/quarto/links.ts b/ggsql-wasm/demo/src/quarto/links.ts index eaab164e0..4dca484f4 100644 --- a/ggsql-wasm/demo/src/quarto/links.ts +++ b/ggsql-wasm/demo/src/quarto/links.ts @@ -27,7 +27,7 @@ const CLAUSE_LINKS: Record = { scale: { url: "syntax/clause/scale", label: "SCALE clause" }, facet: { url: "syntax/clause/facet", label: "FACET clause" }, project: { url: "syntax/clause/project", label: "PROJECT clause" }, - label: { url: "syntax/clause/label", label: "LABEL clause" }, + title: { url: "syntax/clause/title", label: "TITLE clause" }, }; const GEOM_LINKS: Record = { @@ -141,7 +141,7 @@ const POSITION_LINKS: Record = { // --------------------------------------------------------------------------- const CLAUSE_RE = - /\b(VISUALISE|VISUALIZE|DRAW|PLACE|SCALE|FACET|PROJECT|LABEL)\b/gi; + /\b(VISUALISE|VISUALIZE|DRAW|PLACE|SCALE|FACET|PROJECT|TITLE)\b/gi; const GEOM_RE = /\b(?:DRAW|PLACE)\s+(point|line|path|bar|area|tile|polygon|ribbon|histogram|density|smooth|boxplot|violin|text|segment|rule|linear|range)\b/gi; diff --git a/src/AGENTS.md b/src/AGENTS.md index 2f4d92514..c74fdb275 100644 --- a/src/AGENTS.md +++ b/src/AGENTS.md @@ -16,7 +16,7 @@ src/ ├── array_util.rs, compute.rs Arrow array helpers ├── dataframe.rs DataFrame wrapper around arrow RecordBatch ├── format.rs Label/number/date formatting -├── labels.rs Labels from LABEL clauses, shared by plot/ and table/ +├── titles.rs Titles from TITLE clauses, shared by plot/ and table/ ├── naming.rs Internal column-name conventions (__ggsql_*) ├── params.rs SETTING-parameter machinery: values, constraints, validation ├── spec.rs Spec: parse-time result of one VISUALISE/TABULATE statement (Plot or Table) @@ -36,7 +36,7 @@ src/ ### `parser/` -- `mod.rs` exposes `parse_query()` which builds a `Vec` from a query string — one `Spec` per `VISUALISE`/`TABULATE` statement, in source order (`Spec::Table` for `TABULATE`, including its `LABEL`/`SPAN`/`FORMAT` clauses). +- `mod.rs` exposes `parse_query()` which builds a `Vec` from a query string — one `Spec` per `VISUALISE`/`TABULATE` statement, in source order (`Spec::Table` for `TABULATE`, including its `TITLE`/`SPAN`/`FORMAT` clauses). - `source_tree.rs` is the parse-once wrapper: holds the tree-sitter `Tree`, source text, and language; offers a declarative query API (`find_node`, `find_text`, …) plus lazy `extract_sql()` / `extract_spec()` extractors (the latter covers both `VISUALISE` and `TABULATE`). It also handles the `VISUALISE FROM ` shorthand by injecting `SELECT * FROM `. - `builder.rs` walks the CST and produces typed `Spec` values (`Plot`, boxed for size, or `Table`). This is where new grammar nodes become `Plot`/`Table` fields. - `sql.rs` extracts structure from SQL fragments over the parse tree. diff --git a/src/execute/table/layout.rs b/src/execute/table/layout.rs index 60563333e..7fde1b20c 100644 --- a/src/execute/table/layout.rs +++ b/src/execute/table/layout.rs @@ -9,7 +9,7 @@ use super::format::resolve_column_properties; use super::stub::{create_row_labels, create_stubhead}; use crate::array_util::{column_to_strings, value_to_string}; use crate::plot::facet::Facet; -use crate::plot::Labels; +use crate::plot::Titles; use crate::table::{ compose_header, create_caption, create_column_labels, create_heading, create_spanners, groups_are_woven, move_stub_columns, reorder_table_columns, TableCell, TableClass, TableColumn, @@ -26,11 +26,11 @@ use crate::{ColumnSection, DataFrame, Format, GgsqlError, Result, Spanner}; pub(super) fn setup_columns( df: &DataFrame, spans: &[Spanner], - labels: &Labels, + titles: &Titles, formats: &HashMap, facet: Option<&Facet>, ) -> Vec { - let columns = create_table_columns(df, labels, formats, facet); + let columns = create_table_columns(df, titles, formats, facet); let columns = reorder_table_columns(columns, spans); let mut columns = move_stub_columns(columns); let Some(facet) = facet else { @@ -87,7 +87,7 @@ pub(super) fn build_cells( facet: Option<&Facet>, ) -> Result { let spanners = create_spanners(&columns, spans); - // Every label empty means `LABEL col => NULL` (or `=> ''`) on every + // Every label empty means `TITLE col => NULL` (or `=> ''`) on every // column, since an unlabeled column keeps its (non-empty) name — omit // the row rather than render blank header cells. let column_labels = if columns.iter().all(|c| c.label.is_empty()) { @@ -136,13 +136,13 @@ pub(super) fn build_cells( /// Build one `TableColumn` per `DataFrame` column, in the `DataFrame`'s own /// order — `reorder_table_columns` is what may reorder this list -/// afterward, not this function. `labels` is the one authority for an +/// afterward, not this function. `titles` is the one authority for an /// explicit column label; `formats` (already reshaped to one `Format` per /// column by `setup_formats`) is the one authority for its properties. A /// `place => 'left'` facet marks its variables `GroupStub`. fn create_table_columns( df: &DataFrame, - labels: &Labels, + titles: &Titles, formats: &HashMap, facet: Option<&Facet>, ) -> Vec { @@ -166,7 +166,7 @@ fn create_table_columns( .position(|v| *v == name) .map(ColumnSection::GroupStub) .unwrap_or_else(|| format.and_then(|f| f.target).unwrap_or_default()); - let label = match labels.labels.get(&name) { + let label = match titles.titles.get(&name) { // A stub head is a row-label header, not a data column header — // default it blank rather than to the column's own name. None if target.is_stub() => String::new(), @@ -336,14 +336,14 @@ mod tests { /// `Reader`/SQL execution — lets a test build a `Table`'s resolved cells /// directly against a `df!()`-built `DataFrame`. fn resolve_layout(df: &DataFrame, table: &Table) -> Result { - let mut labels = table.labels.clone(); - let titles = extract_table_titles(&mut labels); + let mut titles_map = table.titles.clone(); + let titles = extract_table_titles(&mut titles_map); let column_names = df.get_column_names(); let spans = table - .resolve_spanners(&labels, Some(&column_names)) + .resolve_spanners(&titles_map, Some(&column_names)) .map_err(GgsqlError::ValidationError)?; let formats = setup_formats(df, &table.formats, &spans)?; - let columns = setup_columns(df, &spans, &labels, &formats, None); + let columns = setup_columns(df, &spans, &titles_map, &formats, None); let df = apply_formats(df, &formats)?; let rows = vec![TableRow::body(); df.height()]; build_cells(&df, columns, rows, &spans, &titles, None) @@ -379,14 +379,14 @@ mod tests { } .unwrap(); - let mut labels = Labels::default(); - labels - .labels + let mut titles = Titles::default(); + titles + .titles .insert("id".to_string(), Some("ID".to_string())); - labels.labels.insert("name".to_string(), None); - // "extra" has no entry at all: no LABEL clause mentioned it. + titles.titles.insert("name".to_string(), None); + // "extra" has no entry at all: no TITLE clause mentioned it. - let columns = create_table_columns(&frame, &labels, &HashMap::new(), None); + let columns = create_table_columns(&frame, &titles, &HashMap::new(), None); assert_eq!(columns[0].name, "id"); assert_eq!(columns[0].label, "ID"); // overridden @@ -411,14 +411,14 @@ mod tests { }, )]); - let columns = create_table_columns(&frame, &Labels::default(), &formats, None); + let columns = create_table_columns(&frame, &Titles::default(), &formats, None); assert_eq!(columns[0].label, ""); - let mut labels = Labels::default(); - labels - .labels + let mut titles = Titles::default(); + titles + .titles .insert("region".to_string(), Some("Region".to_string())); - let columns = create_table_columns(&frame, &labels, &formats, None); + let columns = create_table_columns(&frame, &titles, &formats, None); assert_eq!(columns[0].label, "Region"); } @@ -473,7 +473,7 @@ mod tests { let columns = setup_columns( &frame, &[], - &Labels::default(), + &Titles::default(), &HashMap::new(), Some(&facet), ); @@ -492,7 +492,7 @@ mod tests { "name" => vec!["a".to_string(), "b".to_string()], } .unwrap(); - let columns = create_table_columns(&frame, &Labels::default(), &HashMap::new(), None); + let columns = create_table_columns(&frame, &Titles::default(), &HashMap::new(), None); let body = create_body(&frame, &columns); @@ -584,7 +584,7 @@ mod tests { } #[test] - fn build_cells_overrides_a_spanners_default_label_via_labels_clause() { + fn build_cells_overrides_a_spanners_default_label_via_titles_clause() { let frame = df! { "a" => vec![1i32], "b" => vec![2i32], @@ -593,8 +593,8 @@ mod tests { let mut table = Table::new(); table.spans = vec![labeled_spanner(&["a", "b"], "g")]; table - .labels - .labels + .titles + .titles .insert("g".to_string(), Some("Group".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -607,7 +607,7 @@ mod tests { } #[test] - fn build_cells_suppresses_a_named_spanners_cell_via_labels_null() { + fn build_cells_suppresses_a_named_spanners_cell_via_titles_null() { let frame = df! { "a" => vec![1i32], "b" => vec![2i32], @@ -615,7 +615,7 @@ mod tests { .unwrap(); let mut table = Table::new(); table.spans = vec![labeled_spanner(&["a", "b"], "g")]; - table.labels.labels.insert("g".to_string(), None); + table.titles.titles.insert("g".to_string(), None); let cells = resolve_cells(&frame, &table).unwrap(); @@ -767,8 +767,8 @@ mod tests { } .unwrap(); let mut table = Table::new(); - table.labels.labels.insert("id".to_string(), None); - table.labels.labels.insert("name".to_string(), None); + table.titles.titles.insert("id".to_string(), None); + table.titles.titles.insert("name".to_string(), None); let cells = resolve_cells(&frame, &table).unwrap(); @@ -787,12 +787,12 @@ mod tests { .unwrap(); let mut table = Table::new(); table - .labels - .labels + .titles + .titles .insert("main".to_string(), Some("Title".to_string())); table - .labels - .labels + .titles + .titles .insert("sub".to_string(), Some("Subtitle".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -833,8 +833,8 @@ mod tests { .unwrap(); let mut table = Table::new(); table - .labels - .labels + .titles + .titles .insert("sub".to_string(), Some("Subtitle only".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -856,8 +856,8 @@ mod tests { .unwrap(); let mut table = Table::new(); table - .labels - .labels + .titles + .titles .insert("caption".to_string(), Some("Source: test".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); @@ -886,12 +886,12 @@ mod tests { .unwrap(); let mut table = Table::new(); table - .labels - .labels + .titles + .titles .insert("main".to_string(), Some("Title".to_string())); table - .labels - .labels + .titles + .titles .insert("sub".to_string(), Some("Subtitle".to_string())); let layout = resolve_layout(&frame, &table).unwrap(); @@ -911,18 +911,18 @@ mod tests { } #[test] - fn reserved_label_keys_always_win_over_a_same_named_column() { + fn reserved_title_keys_always_win_over_a_same_named_column() { // A column literally named "main" can't get a header override via - // LABEL — the reserved key always wins, and the column just keeps - // its own name, exactly as if no LABEL entry existed for it. + // TITLE — the reserved key always wins, and the column just keeps + // its own name, exactly as if no TITLE entry existed for it. let frame = df! { "main" => vec![1i32], } .unwrap(); let mut table = Table::new(); table - .labels - .labels + .titles + .titles .insert("main".to_string(), Some("The Table's Title".to_string())); let cells = resolve_cells(&frame, &table).unwrap(); diff --git a/src/execute/table/mod.rs b/src/execute/table/mod.rs index 5fcb20db2..f909464d2 100644 --- a/src/execute/table/mod.rs +++ b/src/execute/table/mod.rs @@ -46,8 +46,8 @@ pub fn resolve_table_with_reader(query: &str, reader: &dyn Reader) -> Result Result 'left'` facet keeps its columns as group stubs, so check // for body columns rather than emptiness. if columns.iter().all(|c| c.is_group_stub()) { @@ -416,13 +416,13 @@ mod integration_tests { } #[test] - fn test_tabulate_label_applies_under_the_tab_clause_wrapper() { - // label_clause is nested under tab_clause in the grammar (so LABEL + fn test_tabulate_title_applies_under_the_tab_clause_wrapper() { + // title_clause is nested under tab_clause in the grammar (so TITLE // and SPAN can appear in any order) — build_tabulate_statement must - // unwrap it, not match "label_clause" as a direct child. + // unwrap it, not match "title_clause" as a direct child. let reader = reader_with_sales(); let resolved = - resolve_table_with_reader("TABULATE * FROM sales LABEL id => 'ID'", &reader).unwrap(); + resolve_table_with_reader("TABULATE * FROM sales TITLE id => 'ID'", &reader).unwrap(); let label_cell = resolved .cells() @@ -490,7 +490,7 @@ mod integration_tests { assert_eq!(stub_head.content, ""); let resolved = resolve_table_with_reader( - "TABULATE * FROM sales FORMAT STUB name LABEL name => 'Name'", + "TABULATE * FROM sales FORMAT STUB name TITLE name => 'Name'", &reader, ) .unwrap(); diff --git a/src/labels.rs b/src/labels.rs deleted file mode 100644 index 86a6d3727..000000000 --- a/src/labels.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Text labels from `LABEL` clauses, shared by plots and tables. -//! -//! A `LABEL` clause maps a name — an aesthetic for `VISUALISE`, a column or -//! spanner id for `TABULATE` — to display text. `None` suppresses the label. - -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; - -/// Text labels (from `LABEL` clause) -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] -pub struct Labels { - /// Label assignments (name → text, None = suppress) - pub labels: HashMap>, -} - -impl Labels { - /// Merge another clause's labels into this one; later entries win. - pub fn merge(&mut self, other: Labels) { - self.labels.extend(other.labels); - } - - /// Whether a name has an entry (set or suppressed). - pub fn contains(&self, name: &str) -> bool { - self.labels.contains_key(name) - } - - /// Look up a label's text. - /// Both "not set" and suppressed (`LABEL => NULL`) return `None`. - pub fn get(&self, name: &str) -> Option<&str> { - self.labels.get(name)?.as_deref() - } - - /// Look up a label entry: - /// * `None` means not set, - /// * `Some(None)` means explicitly suppressed (`LABEL => NULL`). - /// * `Some(Some(String))` means typical label - pub fn entry(&self, name: &str) -> Option<&Option> { - self.labels.get(name) - } -} diff --git a/src/lib.rs b/src/lib.rs index c6d5e058e..0301eae00 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ FROM sales WHERE year = 2024 VISUALISE date AS x, revenue AS y, region AS color DRAW line -LABEL main => 'Sales by Region' +TITLE main => 'Sales by Region' ``` ## Architecture @@ -39,7 +39,6 @@ pub mod array_util; pub mod compute; pub mod dataframe; pub mod format; -pub mod labels; pub mod naming; pub mod params; pub mod parser; @@ -47,6 +46,7 @@ pub mod plot; pub mod spec; pub mod sql; pub mod table; +pub mod titles; pub mod util; pub mod reader; diff --git a/src/parser/builder.rs b/src/parser/builder.rs index 9f2e5513e..ea3af8567 100644 --- a/src/parser/builder.rs +++ b/src/parser/builder.rs @@ -22,7 +22,7 @@ use super::SourceTree; /// /// Returns (name_node, value_node) without any interpretation. /// Works for both patterns: -/// - `name => value` (SETTING, PROJECT, LABEL, RENAMING) +/// - `name => value` (SETTING, PROJECT, TITLE, RENAMING) /// - `value AS name` (MAPPING explicit_mapping) /// /// Caller is responsible for interpreting the nodes based on their context. @@ -440,9 +440,9 @@ fn process_tab_clause(node: &Node, source: &SourceTree, table: &mut Table) -> Re let mut cursor = node.walk(); for child in node.children(&mut cursor) { match child.kind() { - "label_clause" => { - let new_labels = build_labels(&child, source)?; - table.labels.merge(new_labels); + "title_clause" => { + let new_titles = build_titles(&child, source)?; + table.titles.merge(new_titles); } "span_clause" => { table @@ -482,7 +482,7 @@ fn build_span_clause(node: &Node, source: &SourceTree, span_idx: usize) -> Resul .child_by_field_name("id") .ok_or_else(|| GgsqlError::ParseError("Missing 'id' field in SPAN clause".to_string()))?; // `id` is unquoted like every other column reference, so it compares - // equal to a later OVER/LABEL reference. `label` is used only for display. + // equal to a later OVER/TITLE reference. `label` is used only for display. let (id, label) = match id_node.kind() { "identifier" => ( naming::unquote_ident(&source.get_text(&id_node)), @@ -617,9 +617,9 @@ fn process_viz_clause(node: &Node, source: &SourceTree, spec: &mut Plot) -> Resu "project_clause" => { spec.project = Some(build_project(&child, source)?); } - "label_clause" => { - let new_labels = build_labels(&child, source)?; - spec.labels.merge(new_labels); + "title_clause" => { + let new_titles = build_titles(&child, source)?; + spec.titles.merge(new_titles); } _ => { // Unknown clause type @@ -1409,41 +1409,41 @@ fn parse_coord_system(name: Option<&str>, properties: &Parameters) -> Result Result { - let mut labels = HashMap::new(); +/// Build Titles from a title_clause node +fn build_titles(node: &Node, source: &SourceTree) -> Result { + let mut titles = HashMap::new(); - // Find all label_assignment nodes - let query = "(label_assignment) @label"; - let label_nodes = source.find_nodes(node, query); + // Find all title_assignment nodes + let query = "(title_assignment) @title"; + let title_nodes = source.find_nodes(node, query); - for label_node in label_nodes { + for title_node in title_nodes { // Extract name and value nodes using field-based queries - let (name_node, value_node) = extract_name_value_nodes(&label_node, "label assignment")?; + let (name_node, value_node) = extract_name_value_nodes(&title_node, "title assignment")?; - // Parse label type (name) - let label_type = naming::unquote_ident(&source.get_text(&name_node)); + // Parse title type (name) + let title_type = naming::unquote_ident(&source.get_text(&name_node)); - // Parse label value (string or null) - let label_value = match value_node.kind() { + // Parse title value (string or null) + let title_value = match value_node.kind() { "string" => Some(parse_string_node(&value_node, source)), "null_literal" => None, _ => { return Err(GgsqlError::ParseError(format!( - "Label '{}' must have a string or null value, got: {}", - label_type, + "Title '{}' must have a string or null value, got: {}", + title_type, value_node.kind() ))); } }; - labels.insert(label_type, label_value); + titles.insert(title_type, title_value); } - Ok(Labels { labels }) + Ok(Titles { titles }) } // ============================================================================ @@ -1665,27 +1665,27 @@ mod tests { } #[test] - fn test_tabulate_repeated_label_clauses_merge_rather_than_overwrite() { - let specs = parse_test_specs("TABULATE * FROM sales LABEL id => 'ID' LABEL name => 'Name'") + fn test_tabulate_repeated_title_clauses_merge_rather_than_overwrite() { + let specs = parse_test_specs("TABULATE * FROM sales TITLE id => 'ID' TITLE name => 'Name'") .unwrap(); let table = specs[0].as_table().expect("expected a Table spec"); - assert_eq!(table.labels.labels.get("id"), Some(&Some("ID".to_string()))); + assert_eq!(table.titles.titles.get("id"), Some(&Some("ID".to_string()))); assert_eq!( - table.labels.labels.get("name"), + table.titles.titles.get("name"), Some(&Some("Name".to_string())) ); } #[test] - fn test_tabulate_multiple_spans_and_label_in_any_order() { + fn test_tabulate_multiple_spans_and_title_in_any_order() { let specs = parse_test_specs( - "TABULATE * FROM sales LABEL id => 'ID' SPAN A OVER foo, bar SPAN B OVER baz", + "TABULATE * FROM sales TITLE id => 'ID' SPAN A OVER foo, bar SPAN B OVER baz", ) .unwrap(); let table = specs[0].as_table().expect("expected a Table spec"); - assert_eq!(table.labels.labels.get("id"), Some(&Some("ID".to_string()))); + assert_eq!(table.titles.titles.get("id"), Some(&Some("ID".to_string()))); assert_eq!(table.spans.len(), 2); assert_eq!(table.spans[0].label, Some("A".to_string())); assert_eq!(table.spans[0].columns, vec!["foo", "bar"]); @@ -1998,7 +1998,7 @@ mod tests { visualise draw point MAPPING x AS x, y AS y project to cartesian - label main => 'Test Chart' + title main => 'Test Chart' "#; let result = parse_test_query(query); @@ -2011,7 +2011,7 @@ mod tests { assert!(specs[0].global_mappings.is_empty()); assert_eq!(specs[0].layers.len(), 1); assert!(specs[0].project.is_some()); - assert!(!specs[0].labels.labels.is_empty()); + assert!(!specs[0].titles.titles.is_empty()); } #[test] @@ -4017,7 +4017,7 @@ mod tests { #[test] fn test_parse_string_node() { - let source = make_source("VISUALISE DRAW point LABEL main => 'hello world'"); + let source = make_source("VISUALISE DRAW point TITLE main => 'hello world'"); let root = source.root(); let string_node = source.find_node(&root, "(string) @s").unwrap(); diff --git a/src/parser/mod.rs b/src/parser/mod.rs index e2bfde3ff..a64a9c291 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -25,7 +25,7 @@ let query = r#" SELECT date, revenue, region FROM sales WHERE year = 2024 VISUALISE date AS x, revenue AS y, region AS color DRAW line - LABEL + TITLE main => 'Sales by Region' "#; @@ -210,7 +210,7 @@ mod tests { SELECT x, y FROM data VISUALISE x, y DRAW point - LABEL main => 'Scatter Plot' + TITLE main => 'Scatter Plot' VISUALIZE DRAW bar MAPPING x AS x, y AS y "#; @@ -218,13 +218,13 @@ mod tests { let specs = parse_query_plots(query).unwrap(); assert_eq!(specs.len(), 2); - // First viz should have layers and labels + // First viz should have layers and titles assert_eq!(specs[0].layers.len(), 1); - assert!(!specs[0].labels.labels.is_empty()); + assert!(!specs[0].titles.titles.is_empty()); - // Second viz should have layer but no labels + // Second viz should have layer but no titles assert_eq!(specs[1].layers.len(), 1); - assert!(specs[1].labels.labels.is_empty()); + assert!(specs[1].titles.titles.is_empty()); } #[test] @@ -255,7 +255,7 @@ mod tests { DRAW line DRAW line MAPPING cost AS y SCALE x VIA date - LABEL main => 'Revenue and Cost Trends' + TITLE main => 'Revenue and Cost Trends' VISUALIZE DRAW bar MAPPING date AS x, revenue AS y VISUALISE @@ -265,10 +265,10 @@ mod tests { let specs = parse_query_plots(query).unwrap(); assert_eq!(specs.len(), 3); - // Plot with 2 layers, scale, labels + // Plot with 2 layers, scale, titles assert_eq!(specs[0].layers.len(), 2); assert_eq!(specs[0].scales.len(), 1); - assert!(!specs[0].labels.labels.is_empty()); + assert!(!specs[0].titles.titles.is_empty()); // Second viz with 1 layer assert_eq!(specs[1].layers.len(), 1); diff --git a/src/plot/AGENTS.md b/src/plot/AGENTS.md index 7df701c18..ce3548dce 100644 --- a/src/plot/AGENTS.md +++ b/src/plot/AGENTS.md @@ -8,12 +8,12 @@ For ggsql language semantics, see [`/doc/syntax/`](../../doc/syntax/). This file Defined in `main.rs` (the `Plot` struct) and `types.rs` (input/value types). All are re-exported through `mod.rs`. The `SETTING`-parameter machinery (`ParameterValue`, `Parameters`, `ArrayElement`, the constraint types, `ParamDefinition::validate`) lives one level up in [`../params.rs`](../params.rs), shared with `table/`; `types.rs` re-exports it, so `plot::` paths keep working. -`Labels` lives in [`../labels.rs`](../labels.rs), likewise shared with `table/` and re-exported from `main.rs`. +`Titles` lives in [`../titles.rs`](../titles.rs), likewise shared with `table/` and re-exported from `main.rs`. | Type | Where | Role | | --- | --- | --- | -| `Plot` | `main.rs` | Root spec: `global_mappings`, optional `source`, `layers`, `scales`, optional `facet`, `project`, `labels`, plus a derived `aesthetic_context`. | -| `Labels` | `../labels.rs` | Title/subtitle/axis/aesthetic labels merged from all `LABEL` clauses. Shared with `table/`. | +| `Plot` | `main.rs` | Root spec: `global_mappings`, optional `source`, `layers`, `scales`, optional `facet`, `project`, `titles`, plus a derived `aesthetic_context`. | +| `Titles` | `../titles.rs` | Title/subtitle/axis/aesthetic labels merged from all `TITLE` clauses. Shared with `table/`. | | `Mappings` | `types.rs` | Unified aesthetic mapping (`wildcard: bool` + `aesthetics: HashMap`); used for both global and per-layer mappings. | | `AestheticValue` | `types.rs` | One side of a mapping: column reference, literal, annotation literal, or null. | | `ParameterValue` | `../params.rs` | Value used in `SETTING` clauses: string / number / boolean / array. | diff --git a/src/plot/main.rs b/src/plot/main.rs index f19274733..201f01abf 100644 --- a/src/plot/main.rs +++ b/src/plot/main.rs @@ -14,10 +14,10 @@ //! ├─ scales: Vec (0+ ScaleNode, one per SCALE clause) //! ├─ facet: Option (optional, from FACET clause) //! ├─ project: Option (optional, from PROJECT clause) -//! └─ labels: Labels (merged from LABEL clauses) +//! └─ titles: Titles (merged from TITLE clauses) //! ``` -pub use crate::labels::Labels; +pub use crate::titles::Titles; use crate::naming; use serde::{Deserialize, Serialize}; @@ -67,9 +67,9 @@ pub struct Plot { pub facet: Option, /// Projection (from PROJECT clause) pub project: Option, - /// Text labels (merged from all LABEL clauses) + /// Text titles (merged from all TITLE clauses) #[serde(default)] - pub labels: Labels, + pub titles: Titles, /// Aesthetic context for coordinate-specific aesthetic names /// Computed from the coord type and facet, used for transformations #[serde(skip)] @@ -85,7 +85,7 @@ impl PartialEq for Plot { && self.scales == other.scales && self.facet == other.facet && self.project == other.project - && self.labels == other.labels + && self.titles == other.titles } } @@ -99,7 +99,7 @@ impl Plot { scales: Vec::new(), facet: None, project: None, - labels: Labels::default(), + titles: Titles::default(), aesthetic_context: None, } } @@ -113,7 +113,7 @@ impl Plot { scales: Vec::new(), facet: None, project: None, - labels: Labels::default(), + titles: Titles::default(), aesthetic_context: None, } } @@ -202,16 +202,16 @@ impl Plot { } } - // Transform label keys + // Transform title keys let mut transformed = HashMap::new(); - for (key, value) in self.labels.labels.drain() { + for (key, value) in self.titles.titles.drain() { let internal_key = ctx .map_user_to_internal(&key) .map(|s| s.to_string()) .unwrap_or(key); transformed.insert(internal_key, value); } - self.labels.labels = transformed; + self.titles.titles = transformed; } /// Check if the spec has any layers @@ -234,7 +234,7 @@ impl Plot { /// Compute aesthetic labels for axes and legends. /// /// For each aesthetic used in any layer, determines the appropriate label: - /// - If user specified a label via LABEL clause, use that + /// - If user specified a label via TITLE clause, use that /// - Otherwise, use the primary aesthetic's column name if mapped /// - Variant aesthetics (xmin, xmax, xend, ymin, ymax, yend) only set the label if /// no primary aesthetic exists in the layer @@ -244,10 +244,10 @@ impl Plot { /// - Primary aesthetics always take precedence over variants for labels /// - Variant aesthetics can still contribute labels when the primary doesn't exist pub fn compute_aesthetic_labels(&mut self) { - // Get aesthetic context before borrowing labels mutably + // Get aesthetic context before borrowing titles mutably let aesthetic_ctx = self.get_aesthetic_context(); - let labels = &mut self.labels; + let titles = &mut self.titles; // Two passes: first primaries, then variants // This ensures primaries always get priority regardless of HashMap iteration order @@ -265,7 +265,7 @@ impl Plot { } // Skip if label already set (user-specified or from earlier) - if labels.contains(primary) { + if titles.contains(primary) { continue; } @@ -290,7 +290,7 @@ impl Plot { label_source.to_string() }; - labels.labels.insert(primary.to_string(), Some(column_name)); + titles.titles.insert(primary.to_string(), Some(column_name)); } } } @@ -587,15 +587,15 @@ mod tests { spec.compute_aesthetic_labels(); - let labels = &spec.labels; + let titles = &spec.titles; // First variant encountered sets the label for the primary aesthetic // Note: HashMap iteration order may vary, so we just check both pos1 and pos2 have labels assert!( - labels.labels.contains_key("pos1"), + titles.titles.contains_key("pos1"), "pos1 label should be set from pos1min or pos1max" ); assert!( - labels.labels.contains_key("pos2"), + titles.titles.contains_key("pos2"), "pos2 label should be set from pos2min or pos2max" ); } @@ -624,20 +624,20 @@ mod tests { spec.layers.push(layer); // Pre-set a user label for pos1 - spec.labels - .labels + spec.titles + .titles .insert("pos1".to_string(), Some("Custom X Label".to_string())); spec.compute_aesthetic_labels(); - let labels = &spec.labels; + let titles = &spec.titles; // User-specified label should be preserved assert_eq!( - labels.labels.get("pos1"), + titles.titles.get("pos1"), Some(&Some("Custom X Label".to_string())) ); // pos2 should still be computed from variants - assert!(labels.labels.contains_key("pos2")); + assert!(titles.titles.contains_key("pos2")); } #[test] @@ -672,9 +672,9 @@ mod tests { spec.compute_aesthetic_labels(); - let labels = &spec.labels; + let titles = &spec.titles; // First layer's pos1 mapping should win - assert_eq!(labels.labels.get("pos1"), Some(&Some("date".to_string()))); + assert_eq!(titles.titles.get("pos1"), Some(&Some("date".to_string()))); } #[test] @@ -697,10 +697,10 @@ mod tests { spec.compute_aesthetic_labels(); - let labels = &spec.labels; + let titles = &spec.titles; // The stroke label should be "stroke" (extracted from __ggsql_aes_stroke__) assert_eq!( - labels.labels.get("stroke"), + titles.titles.get("stroke"), Some(&Some("stroke".to_string())), "Stroke aesthetic should use 'stroke' as label" ); @@ -722,28 +722,28 @@ mod tests { spec.compute_aesthetic_labels(); - let labels = &spec.labels; + let titles = &spec.titles; // The size label should be "size", not "color" assert_eq!( - labels.labels.get("size"), + titles.titles.get("size"), Some(&Some("size".to_string())), "Non-color aesthetic should keep its name" ); } // ======================================== - // Label Transformation Tests + // Title Transformation Tests // ======================================== #[test] - fn test_label_transform_with_default_project() { - // LABEL x/y with default cartesian should transform to pos1/pos2 + fn test_title_transform_with_default_project() { + // TITLE x/y with default cartesian should transform to pos1/pos2 use crate::plot::projection::Projection; let mut spec = Plot::new(); spec.project = Some(Projection::cartesian()); - spec.labels = Labels { - labels: HashMap::from([ + spec.titles = Titles { + titles: HashMap::from([ ("x".to_string(), Some("X Axis".to_string())), ("y".to_string(), Some("Y Axis".to_string())), ]), @@ -752,16 +752,16 @@ mod tests { spec.initialize_aesthetic_context(); spec.transform_aesthetics_to_internal(); - let labels = &spec.labels; - assert_eq!(labels.labels.get("pos1"), Some(&Some("X Axis".to_string()))); - assert_eq!(labels.labels.get("pos2"), Some(&Some("Y Axis".to_string()))); - assert!(!labels.labels.contains_key("x")); - assert!(!labels.labels.contains_key("y")); + let titles = &spec.titles; + assert_eq!(titles.titles.get("pos1"), Some(&Some("X Axis".to_string()))); + assert_eq!(titles.titles.get("pos2"), Some(&Some("Y Axis".to_string()))); + assert!(!titles.titles.contains_key("x")); + assert!(!titles.titles.contains_key("y")); } #[test] - fn test_label_transform_with_flipped_project() { - // LABEL x/y with PROJECT y, x TO cartesian should swap the mappings + fn test_title_transform_with_flipped_project() { + // TITLE x/y with PROJECT y, x TO cartesian should swap the mappings use crate::plot::projection::{Coord, Projection}; let mut spec = Plot::new(); @@ -772,8 +772,8 @@ mod tests { properties: Parameters::new(), computed: Parameters::new(), }); - spec.labels = Labels { - labels: HashMap::from([ + spec.titles = Titles { + titles: HashMap::from([ ("x".to_string(), Some("Category".to_string())), ("y".to_string(), Some("Value".to_string())), ]), @@ -782,18 +782,18 @@ mod tests { spec.initialize_aesthetic_context(); spec.transform_aesthetics_to_internal(); - let labels = &spec.labels; + let titles = &spec.titles; // x maps to pos2 (second position), y maps to pos1 (first position) - assert_eq!(labels.labels.get("pos1"), Some(&Some("Value".to_string()))); + assert_eq!(titles.titles.get("pos1"), Some(&Some("Value".to_string()))); assert_eq!( - labels.labels.get("pos2"), + titles.titles.get("pos2"), Some(&Some("Category".to_string())) ); } #[test] - fn test_label_transform_with_polar_project() { - // LABEL angle/radius with polar should transform to pos1/pos2 + fn test_title_transform_with_polar_project() { + // TITLE angle/radius with polar should transform to pos1/pos2 use crate::plot::projection::{Coord, Projection}; let mut spec = Plot::new(); @@ -803,8 +803,8 @@ mod tests { properties: Parameters::new(), computed: Parameters::new(), }); - spec.labels = Labels { - labels: HashMap::from([ + spec.titles = Titles { + titles: HashMap::from([ ("angle".to_string(), Some("Angle".to_string())), ("radius".to_string(), Some("Distance".to_string())), ]), @@ -813,23 +813,23 @@ mod tests { spec.initialize_aesthetic_context(); spec.transform_aesthetics_to_internal(); - let labels = &spec.labels; - assert_eq!(labels.labels.get("pos1"), Some(&Some("Angle".to_string()))); + let titles = &spec.titles; + assert_eq!(titles.titles.get("pos1"), Some(&Some("Angle".to_string()))); assert_eq!( - labels.labels.get("pos2"), + titles.titles.get("pos2"), Some(&Some("Distance".to_string())) ); } #[test] - fn test_label_transform_preserves_material() { - // LABEL title/color should be preserved unchanged + fn test_title_transform_preserves_material() { + // TITLE main/color should be preserved unchanged use crate::plot::projection::Projection; let mut spec = Plot::new(); spec.project = Some(Projection::cartesian()); - spec.labels = Labels { - labels: HashMap::from([ + spec.titles = Titles { + titles: HashMap::from([ ("main".to_string(), Some("My Chart".to_string())), ("color".to_string(), Some("Category".to_string())), ("x".to_string(), Some("X Axis".to_string())), @@ -839,17 +839,17 @@ mod tests { spec.initialize_aesthetic_context(); spec.transform_aesthetics_to_internal(); - let labels = &spec.labels; + let titles = &spec.titles; // Material labels should remain unchanged assert_eq!( - labels.labels.get("main"), + titles.titles.get("main"), Some(&Some("My Chart".to_string())) ); assert_eq!( - labels.labels.get("color"), + titles.titles.get("color"), Some(&Some("Category".to_string())) ); // Position label should be transformed - assert_eq!(labels.labels.get("pos1"), Some(&Some("X Axis".to_string()))); + assert_eq!(titles.titles.get("pos1"), Some(&Some("X Axis".to_string()))); } } diff --git a/src/plot/mod.rs b/src/plot/mod.rs index d7b29785c..6473f69bf 100644 --- a/src/plot/mod.rs +++ b/src/plot/mod.rs @@ -8,7 +8,7 @@ //! //! The module is organized into submodules: //! -//! - `main` - Main Plot struct and Labels/Theme types +//! - `main` - Main Plot struct and Titles/Theme types //! - `types` - Value types: Mappings, AestheticValue, ParameterValue, etc. //! - `layer` - Layer struct and Geom subsystem //! - `scale` - Scale and Guide types diff --git a/src/table/layout.rs b/src/table/layout.rs index 74e41491e..fad41204a 100644 --- a/src/table/layout.rs +++ b/src/table/layout.rs @@ -7,9 +7,9 @@ use std::collections::BTreeMap; use std::collections::HashSet; use super::ColumnSection; -use crate::labels::Labels; use crate::params::Parameters; use crate::plot::ParameterValue; +use crate::titles::Titles; use crate::{GgsqlError, Result}; /// What role a `TableCell` plays in the table's layout. @@ -32,11 +32,11 @@ pub enum TableCellKind { /// A spanner cell, grouping several columns under one label (`TABULATE /// SPAN`). Spanner, - /// The table's title (`LABEL main => ...`, gt's `gt_title`). + /// The table's title (`TITLE main => ...`, gt's `gt_title`). Title, - /// The table's subtitle (`LABEL sub => ...`, gt's `gt_subtitle`). + /// The table's subtitle (`TITLE sub => ...`, gt's `gt_subtitle`). Subtitle, - /// The table's caption (`LABEL caption => ...`, gt's `tab_caption()`). + /// The table's caption (`TITLE caption => ...`, gt's `tab_caption()`). /// Full-width like `Title`/`Subtitle`, but rendered outside the normal /// row grid entirely — see `HtmlWriter`'s module doc. Caption, @@ -970,7 +970,7 @@ pub(crate) fn create_column_labels(columns: &[TableColumn]) -> Vec { .collect() } -/// A table's resolved `LABEL title`/`subtitle`/`caption` texts. +/// A table's resolved `TITLE main`/`sub`/`caption` texts. #[derive(Debug, Clone, Default)] pub(crate) struct TableTitles { pub title: Option, @@ -979,14 +979,14 @@ pub(crate) struct TableTitles { } /// Pop the reserved `main`/`sub`/`caption` keys out of a `TABULATE` -/// `LABEL` clause's resolved map into `TableTitles`, leaving only genuine +/// `TITLE` clause's resolved map into `TableTitles`, leaving only genuine /// column-name overrides behind. `.flatten()` treats "key absent" and "key /// present but NULL" the same: neither produces a title/subtitle/caption. -pub(crate) fn extract_table_titles(labels: &mut Labels) -> TableTitles { +pub(crate) fn extract_table_titles(titles: &mut Titles) -> TableTitles { TableTitles { - title: labels.labels.remove("main").flatten(), - subtitle: labels.labels.remove("sub").flatten(), - caption: labels.labels.remove("caption").flatten(), + title: titles.titles.remove("main").flatten(), + subtitle: titles.titles.remove("sub").flatten(), + caption: titles.titles.remove("caption").flatten(), } } diff --git a/src/table/mod.rs b/src/table/mod.rs index 5d3f54294..009724bd9 100644 --- a/src/table/mod.rs +++ b/src/table/mod.rs @@ -3,7 +3,7 @@ //! Defines the typed `Table` structure that represents parsed `TABULATE` //! statements, parallel to how `plot` defines `Plot` for `VISUALISE` //! statements: `source` (from `TABULATE FROM`), `selection` (from -//! `TABULATE`'s own column list), `labels` (from `TABULATE LABEL`), `spans` +//! `TABULATE`'s own column list), `titles` (from `TABULATE TITLE`), `spans` //! (from `TABULATE SPAN`), `formats` (from `TABULATE FORMAT`), and `facet` //! (from `TABULATE FACET`) are populated so far. @@ -23,11 +23,11 @@ pub(crate) use spanner::{create_spanners, reorder_table_columns}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; -use crate::labels::Labels; use crate::params::{ DefaultParamValue, NumberConstraint, ParamConstraint, ParamDefinition, Parameters, }; use crate::plot::facet::Facet; +use crate::titles::Titles; use crate::DataSource; /// Complete ggsql table specification. @@ -43,11 +43,11 @@ pub struct Table { /// keyword (e.g. `TABULATE bill_len, bill_dep AS Depth`) — mandatory in /// the grammar. Defaults to `*` for a `Table` built without the parser. pub selection: Vec, - /// Column display labels (from `TABULATE LABEL`). Reuses `labels::Labels` + /// Column display labels (from `TABULATE TITLE`). Reuses `titles::Titles` /// as-is — the same "name → text, None = suppress" shape applies /// unchanged, just keyed by column name instead of aesthetic name. An - /// empty `Labels` means no overrides at all. - pub labels: Labels, + /// empty `Titles` means no overrides at all. + pub titles: Titles, /// Column spanners (from `TABULATE SPAN`), one per `SPAN` clause written /// — a query with several `SPAN` clauses produces one `Spanner` each, /// not one `Spanner` with several groups (`SPAN` itself never bundles @@ -92,7 +92,7 @@ impl Table { Self { source: None, selection: vec![SelectionItem::Wildcard], - labels: Labels::default(), + titles: Titles::default(), spans: Vec::new(), formats: Vec::new(), facet: None, @@ -194,10 +194,10 @@ impl Table { /// Fully resolve this table's spanners for execution: settings /// validated and defaults filled, `OVER` ids folded, feature boundaries /// checked, columns checked against the real schema, and each `label` - /// overlaid with any `LABEL => ...` entry. + /// overlaid with any `TITLE => ...` entry. pub fn resolve_spanners( &self, - labels: &Labels, + titles: &Titles, column_names: Option<&[String]>, ) -> Result, String> { let spans = self.resolve_spanner_ids()?; @@ -216,7 +216,7 @@ impl Table { span.settings = span .resolve_settings() .map_err(|e| format!("SPAN {}: {}", idx + 1, e))?; - span.apply_labels(labels); + span.apply_titles(titles); Ok(span) }) .collect() @@ -287,7 +287,7 @@ pub struct Format { /// Cell display text from the `RENAMING` clause: value-keyed renames /// and suppressions plus the wildcard template, rendered per cell by /// [`crate::format::resolve_column_values`]. Same shape as - /// `Scale::label_spec` — named `renaming` here because `Table::labels` + /// `Scale::label_spec` — named `renaming` here because `Table::titles` /// already uses "label" for column headers, a different concept from a /// cell's value. #[serde(default, with = "crate::format::label_spec_serde")] diff --git a/src/table/spanner.rs b/src/table/spanner.rs index b114617f6..fd4f45ce4 100644 --- a/src/table/spanner.rs +++ b/src/table/spanner.rs @@ -5,22 +5,22 @@ use serde::{Deserialize, Serialize}; use super::layout::{TableCell, TableClass, TableColumn, TableLayout, TableRow}; -use crate::labels::Labels; use crate::params::{ DefaultParamValue, ParamConstraint, ParamDefinition, ParameterValue, Parameters, }; +use crate::titles::Titles; /// One `SPAN` clause: a named group of columns rendered as one spanner cell /// above them. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Spanner { /// This spanner's identifier, unparsed (quotes included, if quoted). - /// Referenced by a later `SPAN`'s `OVER` list or a `LABEL => + /// Referenced by a later `SPAN`'s `OVER` list or a `TITLE => /// ...` override. `SPAN NULL` still gets a real, internally generated /// id here — nothing else can reasonably reference it. pub id: String, /// Dequoted default display text. `None` for `SPAN NULL` — blank cell, - /// columns still group. `LABEL => ...` overrides either way. + /// columns still group. `TITLE => ...` overrides either way. pub label: Option, /// The columns this spanner covers, in the order written. pub columns: Vec, @@ -84,10 +84,10 @@ impl Spanner { Ok(()) } - /// Overlay a `LABEL => ...` entry onto `label`, if the query has + /// Overlay a `TITLE => ...` entry onto `label`, if the query has /// one for this spanner's id; otherwise leaves `label` as-is. - pub fn apply_labels(&mut self, labels: &Labels) { - if let Some(override_label) = labels.entry(&self.id) { + pub fn apply_titles(&mut self, titles: &Titles) { + if let Some(override_label) = titles.entry(&self.id) { self.label = override_label.clone(); } } @@ -212,7 +212,7 @@ pub(crate) fn create_spanners(columns: &[TableColumn], spans: &[Spanner]) -> Tab return TableLayout::new(columns.to_vec(), Vec::new(), Vec::new()); } - // Spanners with no display text (`SPAN NULL`, or `LABEL => NULL`) + // Spanners with no display text (`SPAN NULL`, or `TITLE => NULL`) // contribute no cells, so their level shouldn't affect other levels. let spans: Vec = spans .iter() diff --git a/src/tests/e2e.rs b/src/tests/e2e.rs index 6e5151870..9bbaa5b7a 100644 --- a/src/tests/e2e.rs +++ b/src/tests/e2e.rs @@ -893,14 +893,14 @@ fn test_position_identity_default() { } #[test] -fn test_label_with_flipped_project() { +fn test_title_with_flipped_project() { let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); let query = r#" SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(x, y) VISUALISE DRAW bar MAPPING x AS y, y AS x PROJECT y, x TO cartesian - LABEL x => 'Value', y => 'Category' + TITLE x => 'Value', y => 'Category' "#; let spec = reader.execute(query).unwrap(); @@ -917,26 +917,26 @@ fn test_label_with_flipped_project() { assert_eq!( x_title, Some("Category"), - "x-axis should have 'Category' title (from LABEL y). Got encoding: {}", + "x-axis should have 'Category' title (from TITLE y). Got encoding: {}", serde_json::to_string_pretty(encoding).unwrap() ); assert_eq!( y_title, Some("Value"), - "y-axis should have 'Value' title (from LABEL x). Got encoding: {}", + "y-axis should have 'Value' title (from TITLE x). Got encoding: {}", serde_json::to_string_pretty(encoding).unwrap() ); } #[test] -fn test_label_with_polar_project() { +fn test_title_with_polar_project() { let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); let query = r#" SELECT * FROM (VALUES ('A', 10), ('B', 20)) AS t(category, value) VISUALISE value AS angle, category AS fill DRAW bar PROJECT TO polar - LABEL angle => 'Angle', radius => 'Distance' + TITLE angle => 'Angle', radius => 'Distance' "#; let spec = reader.execute(query).unwrap(); diff --git a/src/titles.rs b/src/titles.rs new file mode 100644 index 000000000..bb5bd0834 --- /dev/null +++ b/src/titles.rs @@ -0,0 +1,40 @@ +//! Text titles from `TITLE` clauses, shared by plots and tables. +//! +//! A `TITLE` clause maps a name — an aesthetic for `VISUALISE`, a column or +//! spanner id for `TABULATE` — to display text. `None` suppresses the title. + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +/// Text titles (from `TITLE` clause) +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)] +pub struct Titles { + /// Title assignments (name → text, None = suppress) + pub titles: HashMap>, +} + +impl Titles { + /// Merge another clause's titles into this one; later entries win. + pub fn merge(&mut self, other: Titles) { + self.titles.extend(other.titles); + } + + /// Whether a name has an entry (set or suppressed). + pub fn contains(&self, name: &str) -> bool { + self.titles.contains_key(name) + } + + /// Look up a title's text. + /// Both "not set" and suppressed (`TITLE => NULL`) return `None`. + pub fn get(&self, name: &str) -> Option<&str> { + self.titles.get(name)?.as_deref() + } + + /// Look up a title entry: + /// * `None` means not set, + /// * `Some(None)` means explicitly suppressed (`TITLE => NULL`). + /// * `Some(Some(String))` means typical title + pub fn entry(&self, name: &str) -> Option<&Option> { + self.titles.get(name) + } +} diff --git a/src/writer/hephaestus/AGENTS.md b/src/writer/hephaestus/AGENTS.md index 780d84328..34f2c57ed 100644 --- a/src/writer/hephaestus/AGENTS.md +++ b/src/writer/hephaestus/AGENTS.md @@ -600,7 +600,7 @@ and titles ggsql resolved can be read back out of it. only against `build_panels`, never against rendered output. - `RENAMING` reaches both an axis rail and a legend key. - A binned scale's resolved edges reach the colorbar. -- Every `LABEL` slot appears, and markdown is **parsed** — no literal `*`, and +- Every `TITLE` slot appears, and markdown is **parsed** — no literal `*`, and the emphasised run carries a style. - `text=outline` → zero `` and more ``; `id-prefix` rewrites every id *and* every `url(#…)` reference. diff --git a/src/writer/hephaestus/compose.rs b/src/writer/hephaestus/compose.rs index a90d72cda..836482cb1 100644 --- a/src/writer/hephaestus/compose.rs +++ b/src/writer/hephaestus/compose.rs @@ -94,7 +94,7 @@ pub fn build_composition( .shape_registry(ShapeRegistry::with_builtins()) .theme(wiring::ggsql_theme()); - // LABEL main/sub/caption live on the composition rather than the + // TITLE main/sub/caption live on the composition rather than the // panels, so one label spans the whole figure — also correct unfaceted, // where a panel-level title would resolve to the same layout row. if let Some(text) = wiring::plot_label(spec, "main") { diff --git a/src/writer/hephaestus/mod.rs b/src/writer/hephaestus/mod.rs index 21a79c244..3d42f2124 100644 --- a/src/writer/hephaestus/mod.rs +++ b/src/writer/hephaestus/mod.rs @@ -429,14 +429,14 @@ mod tests { ); } - /// Markdown chrome: a `LABEL` string is rich text too, so the title, subtitle, + /// Markdown chrome: a `TITLE` string is rich text too, so the title, subtitle, /// caption and axis titles all shape through the rich pipeline. #[test] fn renders_markdown_chrome() { assert_renders( "SELECT 1 AS x, 2 AS y UNION ALL SELECT 2, 3 \ VISUALISE x AS x, y AS y DRAW point \ - LABEL main => 'A **bold** title', sub => '{.red red} subtitle', \ + TITLE main => 'A **bold** title', sub => '{.red red} subtitle', \ caption => '*italic* caption', x => 'axis *italic*'", ); } @@ -844,7 +844,7 @@ mod tests { assert_eq!( axis_titles(&format!( "{FACET_DATA} VISUALISE v AS x, y AS y DRAW point FACET g \ - LABEL x => 'Value', y => 'Count'" + TITLE x => 'Value', y => 'Count'" )), vec![ (AxisSide::Bottom, "Value".to_string()), @@ -1294,18 +1294,18 @@ mod tests { assert_renders( "SELECT 1 AS x, 2 AS y UNION ALL SELECT 2, 3 UNION ALL SELECT 3, 1 \ VISUALISE x AS x, y AS y DRAW point \ - LABEL main => 'Sales by Region', sub => 'FY 2024', \ + TITLE main => 'Sales by Region', sub => 'FY 2024', \ caption => 'Source: internal'", ); } #[test] fn renders_suppressed_title() { - // `LABEL main => NULL` suppresses; the subtitle still renders. + // `TITLE main => NULL` suppresses; the subtitle still renders. assert_renders( "SELECT 1 AS x, 2 AS y UNION ALL SELECT 2, 3 \ VISUALISE x AS x, y AS y DRAW point \ - LABEL main => NULL, sub => 'no title above me'", + TITLE main => NULL, sub => 'no title above me'", ); } @@ -1317,7 +1317,7 @@ mod tests { "SELECT x, y, g FROM (VALUES (1,1,'a'),(2,2,'a'),(1,2,'b'),(2,3,'b'),\ (1,3,'c'),(2,1,'c')) t(x,y,g) \ VISUALISE x AS x, y AS y DRAW point FACET g \ - LABEL main => 'One title for all panels'", + TITLE main => 'One title for all panels'", ); } @@ -1529,7 +1529,7 @@ mod svg_text { fn every_plot_label_reaches_the_output() { let labelled = svg("SELECT x, y FROM (VALUES (1,2),(2,3)) t(x,y) \ VISUALISE x AS x, y AS y DRAW point \ - LABEL main => 'The title', sub => 'The subtitle', \ + TITLE main => 'The title', sub => 'The subtitle', \ caption => 'The caption', x => 'Across', y => 'Up'"); for label in ["The title", "The subtitle", "The caption", "Across", "Up"] { assert!(contains(&labelled, label), "missing label '{label}'"); @@ -1539,7 +1539,7 @@ mod svg_text { #[test] fn markdown_in_a_label_is_parsed_rather_than_printed() { let emphasised = svg("SELECT x, y FROM (VALUES (1,2),(2,3)) t(x,y) \ - VISUALISE x AS x, y AS y DRAW point LABEL main => 'A *bold* title'"); + VISUALISE x AS x, y AS y DRAW point TITLE main => 'A *bold* title'"); // The words survive, the markers do not. assert!(contains(&emphasised, "A bold title")); assert!( @@ -1579,7 +1579,7 @@ mod svg_text { #[test] fn outline_mode_turns_text_into_paths() { let query = "SELECT x, y FROM (VALUES (1,2),(2,3)) t(x,y) \ - VISUALISE x AS x, y AS y DRAW point LABEL main => 'Outlined'"; + VISUALISE x AS x, y AS y DRAW point TITLE main => 'Outlined'"; let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); let spec = reader.execute(query).unwrap().into_plot().unwrap(); @@ -1671,7 +1671,7 @@ mod pdf_structure { reader .execute( "SELECT x, y FROM (VALUES (1,2),(2,3),(3,1)) t(x,y) \ - VISUALISE x AS x, y AS y DRAW point LABEL main => 'A page'", + VISUALISE x AS x, y AS y DRAW point TITLE main => 'A page'", ) .unwrap() .into_plot() @@ -1751,7 +1751,7 @@ mod hep_roundtrip { "faceted scatter with a legend", "VISUALISE bill_len AS x, bill_dep AS y, species AS color \ FROM ggsql:penguins DRAW point FACET island \ - LABEL main => 'Penguin *bills*', caption => 'From ggsql:penguins'", + TITLE main => 'Penguin *bills*', caption => 'From ggsql:penguins'", ), ( "multi-layer with a colorbar", diff --git a/src/writer/hephaestus/wiring.rs b/src/writer/hephaestus/wiring.rs index dabf7d3d7..ae3278c5d 100644 --- a/src/writer/hephaestus/wiring.rs +++ b/src/writer/hephaestus/wiring.rs @@ -698,10 +698,10 @@ fn offset_column(df: &DataFrame, aesthetic: &str) -> Option> { column_to_f64(df, &name).ok() } -/// Resolve a label for an aesthetic: explicit `LABEL` wins (`None` suppresses), +/// Resolve a label for an aesthetic: explicit `TITLE` wins (`None` suppresses), /// else the original mapped column name is the default. pub fn aesthetic_label(spec: &Plot, layer: &Layer, aesthetic: &str) -> Option { - if let Some(entry) = spec.labels.entry(aesthetic) { + if let Some(entry) = spec.titles.entry(aesthetic) { return entry.clone(); } match layer.mappings.get(aesthetic) { @@ -713,13 +713,13 @@ pub fn aesthetic_label(spec: &Plot, layer: &Layer, aesthetic: &str) -> Option => NULL` (suppressed). +/// Resolve a plot-level label (`main`, `sub`, `caption`) from the `TITLE` +/// clause. `None` covers both "not set" and `TITLE => NULL` (suppressed). /// /// Literal `\n` in the SQL string literal becomes a real newline, matching the /// Vega-Lite writer's `split_label_on_newlines`. pub fn plot_label(spec: &Plot, key: &str) -> Option { - let text = spec.labels.get(key)?; + let text = spec.titles.get(key)?; Some(text.replace("\\n", "\n")) } diff --git a/src/writer/html.rs b/src/writer/html.rs index 660c1effc..1cc5a2d44 100644 --- a/src/writer/html.rs +++ b/src/writer/html.rs @@ -1238,7 +1238,7 @@ mod tests { let html = writer.render(&spec).unwrap(); // The stub head renders as a , blank by default (no - // LABEL given); the row labels render as , both + // TITLE given); the row labels render as , both // right-aligned (resolve_column_properties' STUB default). assert!(html.contains("")); assert!(html.contains("north")); diff --git a/src/writer/vegalite/encoding.rs b/src/writer/vegalite/encoding.rs index 00a5077c4..2ca212116 100644 --- a/src/writer/vegalite/encoding.rs +++ b/src/writer/vegalite/encoding.rs @@ -387,7 +387,7 @@ fn apply_title_to_encoding( if is_primary && !titled_families.contains(primary) { // Primary aesthetic: set title from explicit label or original_name - let explicit_label = spec.labels.entry(primary); + let explicit_label = spec.titles.entry(primary); if let Some(label_opt) = explicit_label { match label_opt { @@ -409,7 +409,7 @@ fn apply_title_to_encoding( encoding["title"] = Value::Null; } else if !is_primary && !primary_exists && !titled_families.contains(primary) { // Variant without primary: allow first variant to claim title (for explicit labels) - if let Some(label_opt) = spec.labels.entry(primary) { + if let Some(label_opt) = spec.titles.entry(primary) { match label_opt { Some(label) => { encoding["title"] = super::split_label_on_newlines(label); diff --git a/src/writer/vegalite/mod.rs b/src/writer/vegalite/mod.rs index 2cc36acea..3b5b876c6 100644 --- a/src/writer/vegalite/mod.rs +++ b/src/writer/vegalite/mod.rs @@ -1115,8 +1115,8 @@ impl Writer for VegaLiteWriter { } { - let title = spec.labels.get("main"); - let subtitle = spec.labels.get("sub"); + let title = spec.titles.get("main"); + let subtitle = spec.titles.get("sub"); match (title, subtitle) { (Some(t), Some(st)) => { // Vega-Lite uses an object for title + subtitle @@ -1547,8 +1547,8 @@ mod tests { ); spec.layers.push(layer); - spec.labels - .labels + spec.titles + .titles .insert("main".to_string(), Some("My Chart".to_string())); let df = df! { @@ -1573,7 +1573,7 @@ mod tests { use crate::execute; use crate::reader::DuckDBReader; - // Test that LABEL clause values with newlines are split into arrays + // Test that TITLE clause values with newlines are split into arrays let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); @@ -1585,7 +1585,7 @@ mod tests { FROM generate_series(0, 2) as t(n) VISUALISE x, y, category AS stroke DRAW point - LABEL + TITLE main => 'Multi-line\nChart Title', sub => 'Line 1\nLine 2\nLine 3', x => 'X Axis\nWith Newline', diff --git a/tree-sitter-ggsql/bindings/node/binding_test.js b/tree-sitter-ggsql/bindings/node/binding_test.js index 606d9e27e..42a82b331 100644 --- a/tree-sitter-ggsql/bindings/node/binding_test.js +++ b/tree-sitter-ggsql/bindings/node/binding_test.js @@ -36,7 +36,7 @@ try { DRAW line DRAW point SETTING size => 3 SCALE x SETTING type => 'date' - LABEL main => 'Revenue Analysis' + TITLE main => 'Revenue Analysis' THEME minimal `; diff --git a/tree-sitter-ggsql/grammar.js b/tree-sitter-ggsql/grammar.js index fb2947c9d..189e8a733 100644 --- a/tree-sitter-ggsql/grammar.js +++ b/tree-sitter-ggsql/grammar.js @@ -671,7 +671,7 @@ module.exports = grammar({ // TABULATE — still incomplete, more clauses expected as Table grows. // column_selection and single_source_from are fixed in position, mirroring // VISUALISE's global_mapping + single_source_from ahead of - // repeat($.viz_clause). LABEL/SPAN/FORMAT (tab_clause) repeat, any order, + // repeat($.viz_clause). TITLE/SPAN/FORMAT (tab_clause) repeat, any order, // after that. tabulate_statement: $ => prec.dynamic(1, seq( $.tabulate_keyword, @@ -690,7 +690,7 @@ module.exports = grammar({ // All the TABULATE clauses (mirrors viz_clause's role for VISUALISE). tab_clause: $ => choice( - $.label_clause, + $.title_clause, $.span_clause, $.format_clause, $.facet_clause, @@ -727,7 +727,7 @@ module.exports = grammar({ span_clause: $ => seq( caseInsensitive('SPAN'), // Mandatory: an identifier names this spanner — also its default - // display text, and how a later SPAN's OVER list or a LABEL entry + // display text, and how a later SPAN's OVER list or a TITLE entry // addresses it (quote it to include spaces or other non-identifier // characters). NULL leaves it anonymous: nothing can reference it, // and its cell renders blank, but its columns still group (e.g. for @@ -792,7 +792,7 @@ module.exports = grammar({ $.scale_clause, $.facet_clause, $.project_clause, - $.label_clause, + $.title_clause, ), // DRAW clause - syntax: DRAW geom [MAPPING ...] [REMAPPING ...] [SETTING ...] [FILTER ...] [PARTITION BY ...] [ORDER BY ...] @@ -1144,22 +1144,22 @@ module.exports = grammar({ project_property_name: $ => $.identifier, - // LABEL clause (repeatable) - label_clause: $ => seq( - caseInsensitive('LABEL'), + // TITLE clause (repeatable) + title_clause: $ => seq( + caseInsensitive('TITLE'), optional(seq( - $.label_assignment, - repeat(seq(',', $.label_assignment)) + $.title_assignment, + repeat(seq(',', $.title_assignment)) )) ), - label_assignment: $ => seq( - field('name', $.label_type), + title_assignment: $ => seq( + field('name', $.title_type), '=>', field('value', choice($.string, $.null_literal)) ), - label_type: $ => $.identifier, + title_type: $ => $.identifier, // Basic tokens bare_identifier: $ => token(/[a-zA-Z_][a-zA-Z0-9_]*/), diff --git a/tree-sitter-ggsql/queries/highlights.scm b/tree-sitter-ggsql/queries/highlights.scm index e8319356d..845e5e01d 100644 --- a/tree-sitter-ggsql/queries/highlights.scm +++ b/tree-sitter-ggsql/queries/highlights.scm @@ -107,7 +107,7 @@ ; Property names (project_property_name) @property -(label_type) @property +(title_type) @property ; Operators "=" @operator diff --git a/tree-sitter-ggsql/test/corpus/basic.txt b/tree-sitter-ggsql/test/corpus/basic.txt index 3d5f3d46e..5bf30c68b 100644 --- a/tree-sitter-ggsql/test/corpus/basic.txt +++ b/tree-sitter-ggsql/test/corpus/basic.txt @@ -596,7 +596,7 @@ Plot with labels VISUALISE x, y DRAW point -LABEL main => 'My Plot', x => 'X Axis', y => 'Y Axis' +TITLE main => 'My Plot', x => 'X Axis', y => 'Y Axis' -------------------------------------------------------------------------------- @@ -617,19 +617,19 @@ LABEL main => 'My Plot', x => 'X Axis', y => 'Y Axis' (draw_clause (geom_type))) (viz_clause - (label_clause - (label_assignment - (label_type + (title_clause + (title_assignment + (title_type (identifier (bare_identifier))) (string)) - (label_assignment - (label_type + (title_assignment + (title_type (identifier (bare_identifier))) (string)) - (label_assignment - (label_type + (title_assignment + (title_type (identifier (bare_identifier))) (string)))))) @@ -4579,10 +4579,10 @@ TABULATE * FROM sales (bare_identifier)))))) ================================================================================ -TABULATE LABEL clause +TABULATE TITLE clause ================================================================================ -TABULATE * FROM sales LABEL id => 'ID' +TABULATE * FROM sales TITLE id => 'ID' -------------------------------------------------------------------------------- @@ -4598,9 +4598,9 @@ TABULATE * FROM sales LABEL id => 'ID' (identifier (bare_identifier)))) (tab_clause - (label_clause - (label_assignment - name: (label_type + (title_clause + (title_assignment + name: (title_type (identifier (bare_identifier))) value: (string)))))) @@ -4755,10 +4755,10 @@ TABULATE * FROM sales SPAN foo, bar UNDER baz (bare_identifier)))))) ================================================================================ -TABULATE LABEL then SPAN clause, any order +TABULATE TITLE then SPAN clause, any order ================================================================================ -TABULATE * FROM sales LABEL id => 'ID' SPAN A OVER foo, bar +TABULATE * FROM sales TITLE id => 'ID' SPAN A OVER foo, bar -------------------------------------------------------------------------------- @@ -4774,9 +4774,9 @@ TABULATE * FROM sales LABEL id => 'ID' SPAN A OVER foo, bar (identifier (bare_identifier)))) (tab_clause - (label_clause - (label_assignment - name: (label_type + (title_clause + (title_assignment + name: (title_type (identifier (bare_identifier))) value: (string)))) @@ -4922,7 +4922,7 @@ Label string containing URL with comment-like sequences VISUALISE DRAW point -LABEL caption => 'Data source: -- see appendix' +TITLE caption => 'Data source: -- see appendix' -------------------------------------------------------------------------------- @@ -4933,9 +4933,9 @@ LABEL caption => 'Data source: -- (draw_clause (geom_type))) (viz_clause - (label_clause - (label_assignment - (label_type + (title_clause + (title_assignment + (title_type (identifier (bare_identifier))) (string)))))) @@ -4948,7 +4948,7 @@ Line comment (double slash) between clauses VISUALISE x, y // trailing comment on the same line DRAW point // comment before a clause -LABEL main => 'My Plot' // and one at the end +TITLE main => 'My Plot' // and one at the end -------------------------------------------------------------------------------- @@ -4972,9 +4972,9 @@ LABEL main => 'My Plot' // and one at the end (geom_type))) (comment) (viz_clause - (label_clause - (label_assignment - (label_type + (title_clause + (title_assignment + (title_type (identifier (bare_identifier))) (string))))) @@ -5011,7 +5011,7 @@ VISUALISE /* inline block */ x, y DRAW point /* a multi-line block comment */ -LABEL main => 'My Plot' +TITLE main => 'My Plot' -------------------------------------------------------------------------------- @@ -5034,9 +5034,9 @@ LABEL main => 'My Plot' (geom_type))) (comment) (viz_clause - (label_clause - (label_assignment - (label_type + (title_clause + (title_assignment + (title_type (identifier (bare_identifier))) (string)))))) @@ -5048,7 +5048,7 @@ Comments alongside strings that contain comment-like text -- leading comment VISUALISE DRAW point -LABEL caption => 'see https://example.com -- details' // trailing comment +TITLE caption => 'see https://example.com -- details' // trailing comment -------------------------------------------------------------------------------- @@ -5060,9 +5060,9 @@ LABEL caption => 'see https://example.com -- details' // trailing comment (draw_clause (geom_type))) (viz_clause - (label_clause - (label_assignment - (label_type + (title_clause + (title_assignment + (title_type (identifier (bare_identifier))) (string))))) From 8d4178110f8d65c9591c301e81aa769ae52b1816 Mon Sep 17 00:00:00 2001 From: Teun van den Brand Date: Fri, 27 Nov 2026 15:38:38 +0100 Subject: [PATCH 3/7] Rename the RENAMING subclause to LABEL The SCALE/FORMAT subclause that maps values to display labels is now LABEL, made available by the titles clause taking the TITLE name. The Format AST field follows Scale::label_spec as Format::label_spec. --- doc/gallery/examples/minard.qmd | 10 +- doc/get_started/first_plot.qmd | 2 +- doc/ggsql.xml | 10 +- doc/syntax/clause/facet-tabulate.qmd | 4 +- doc/syntax/clause/facet.qmd | 4 +- doc/syntax/clause/format.qmd | 20 ++-- doc/syntax/clause/scale.qmd | 8 +- doc/syntax/scale/aesthetic/Z_faceting.qmd | 4 +- doc/syntax/scale/type/binned.qmd | 14 +-- doc/syntax/scale/type/continuous.qmd | 16 +-- doc/syntax/scale/type/discrete.qmd | 12 +- doc/syntax/scale/type/ordinal.qmd | 12 +- doc/vendor/SKILL.md | 12 +- ggsql-vscode/syntaxes/ggsql.tmLanguage.json | 6 +- ggsql-wasm/demo/src/examples.ts | 4 +- src/execute/table/format.rs | 44 +++---- src/execute/table/layout.rs | 14 +-- src/execute/table/mod.rs | 10 +- src/format.rs | 10 +- src/parser/builder.rs | 122 ++++++++++---------- src/plot/scale/scale_type/mod.rs | 8 +- src/plot/scale/types.rs | 16 +-- src/table/mod.rs | 32 +++-- src/tests/e2e.rs | 2 +- src/writer/hephaestus/AGENTS.md | 8 +- src/writer/hephaestus/facet.rs | 8 +- src/writer/hephaestus/mod.rs | 28 ++--- src/writer/hephaestus/scales.rs | 6 +- src/writer/vegalite/encoding.rs | 2 +- src/writer/vegalite/mod.rs | 6 +- tree-sitter-ggsql/grammar.js | 24 ++-- tree-sitter-ggsql/test/corpus/basic.txt | 42 +++---- 32 files changed, 258 insertions(+), 262 deletions(-) diff --git a/doc/gallery/examples/minard.qmd b/doc/gallery/examples/minard.qmd index 40dca7fba..c1887aa99 100644 --- a/doc/gallery/examples/minard.qmd +++ b/doc/gallery/examples/minard.qmd @@ -107,7 +107,7 @@ Now that we have all the data included in the ways we want, we can start detaili The first thing we might do is to pick some better colours. Because we have two levels for the `direction` variable —**A**dvance and **R**etreat— we can create a new colour scale for the `stroke` aesthetic. We'll choose the colours to more closely resemble the original graphic by Minard. -We set the palette using the `TO` keyword, and format the labels using `RENAMING`. +We set the palette using the `TO` keyword, and format the labels using `LABEL`. ```{ggsql} VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' @@ -115,7 +115,7 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' MAPPING direction AS stroke, survivors AS linewidth PARTITION BY direction, group SCALE stroke TO ('burlywood', 'black') - RENAMING 'A' => 'Advance', 'R' => 'Retreat' + LABEL 'A' => 'Advance', 'R' => 'Retreat' ``` Now for a slightly more complicated scale, we're going to set one for the `linewidth` variable that represent the number of troops. @@ -130,7 +130,7 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' MAPPING direction AS stroke, survivors AS linewidth PARTITION BY direction, group SCALE stroke TO ('burlywood', 'black') - RENAMING 'A' => 'Advance', 'R' => 'Retreat' + LABEL 'A' => 'Advance', 'R' => 'Retreat' SCALE linewidth FROM (0, null) TO (0, 20) ``` @@ -154,7 +154,7 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' MAPPING city AS label FROM 'minard_cities.csv' SETTING fontsize => 6 SCALE stroke TO ('burlywood', 'black') - RENAMING 'A' => 'Advance', 'R' => 'Retreat' + LABEL 'A' => 'Advance', 'R' => 'Retreat' SCALE linewidth FROM (0, null) TO (0, 30) ``` @@ -173,7 +173,7 @@ VISUALISE long AS x, lat AS y FROM 'minard_troops.csv' MAPPING city AS label FROM 'minard_cities.csv' SETTING fontsize => 6 SCALE stroke TO ('burlywood', 'black') - RENAMING 'A' => 'Advance', 'R' => 'Retreat' + LABEL 'A' => 'Advance', 'R' => 'Retreat' SCALE linewidth FROM (0, null) TO (0, 20) TITLE main => 'Napoleon\'s Russian Campaign', diff --git a/doc/get_started/first_plot.qmd b/doc/get_started/first_plot.qmd index 0a89427aa..288c7b6fe 100644 --- a/doc/get_started/first_plot.qmd +++ b/doc/get_started/first_plot.qmd @@ -8,7 +8,7 @@ The code below shows a simple ggsql example. But it is not just a static piece o VISUALISE bill_len AS x, bill_dep AS y, species AS fill FROM ggsql:penguins DRAW point SCALE x - RENAMING * => '{} mm' + LABEL * => '{} mm' TITLE main => 'Relationship between bill dimensions in 3 species of penguins', x => 'Bill length', diff --git a/doc/ggsql.xml b/doc/ggsql.xml index f97063ac0..a50a5410b 100644 --- a/doc/ggsql.xml +++ b/doc/ggsql.xml @@ -98,7 +98,7 @@ FILTER ORDER PARTITION - RENAMING + LABEL TO VIA OVER @@ -623,7 +623,7 @@ - + @@ -777,9 +777,9 @@ - + - + @@ -792,7 +792,7 @@ - + diff --git a/doc/syntax/clause/facet-tabulate.qmd b/doc/syntax/clause/facet-tabulate.qmd index f6f1e1a17..9e2806881 100644 --- a/doc/syntax/clause/facet-tabulate.qmd +++ b/doc/syntax/clause/facet-tabulate.qmd @@ -73,7 +73,7 @@ Note that `missing => 'drop'` has priority over any relabeling in `FORMAT`. ```{ggsql} TABULATE * FROM my_data FACET sex -FORMAT sex RENAMING null => 'unknown' +FORMAT sex LABEL null => 'unknown' ``` Place grouping labels in rows above their members. @@ -91,7 +91,7 @@ FACET species, island ``` The labels from multiple groups can be collapsed to a single stub column (or single rows) by using the `separator` setting to join the labels. -Labels are joined after `FORMAT RENAMING` is applied. +Labels are joined after `FORMAT LABEL` is applied. ```{ggsql} TABULATE * FROM my_data diff --git a/doc/syntax/clause/facet.qmd b/doc/syntax/clause/facet.qmd index 4db512700..66ee2b1c4 100644 --- a/doc/syntax/clause/facet.qmd +++ b/doc/syntax/clause/facet.qmd @@ -47,12 +47,12 @@ This clause behaves much like the `SETTINGS` clause in `DRAW`, in that it allows When you apply faceting to a plot you are creating new aesthetics you can control. For 1-dimensional faceting (no `BY` clause) the aesthetic is called `panel` and for 2-dimensional faceting the aesthetics are called `row` and `column`. You can read more about these aesthetics in [their documentation](../scale/aesthetic/Z_faceting.qmd) ### Customizing facet strip labels -To customize facet strip labels (e.g., renaming categories), use the `RENAMING` clause on the facet scale: +To customize facet strip labels (e.g., renaming categories), use the `LABEL` subclause on the facet scale: ```ggsql FACET region SCALE panel - RENAMING 'N' => 'North', 'S' => 'South' + LABEL 'N' => 'North', 'S' => 'South' ``` See the [facet scale documentation](../scale/aesthetic/Z_faceting.qmd) for more details on label customization. diff --git a/doc/syntax/clause/format.qmd b/doc/syntax/clause/format.qmd index 9678c4003..350b2c983 100644 --- a/doc/syntax/clause/format.qmd +++ b/doc/syntax/clause/format.qmd @@ -11,7 +11,7 @@ It is the workhorse for column-focussed changes: value formatting, display prope FORMAT [ANY | BODY | STUB] (* | , ...) SETTING => , ... - RENAMING => , ... + LABEL => , ... ``` ## Target @@ -83,24 +83,24 @@ Unset, the default depends on the column: right-aligned for numbers and stub col ## Renaming ```ggsql -RENAMING => , ... +LABEL => , ... ``` -The `RENAMING` clause is *the* place to format the cell contents. -It works the same as the namesake in the [`SCALE`](scale.qmd#renaming) clause. +The `LABEL` subclause is *the* place to format the cell contents. +It works the same as the namesake in the [`SCALE`](scale.qmd#label) clause. Generally, it works not unlike the [`TITLE`](title-tabulate.qmd) clause in the sense that you specify a cell's content on the left and a replacement value on the right. Alternatively, you can use a formatter with the `* => '...'` syntax. Specifically see the [break formatting](scale.qmd#break-formatting) section for a list of formatters. ```ggsql -- Replace a specific piece of content -FORMAT species RENAMING 'adelie' => 'Pygoscelis adeliae' +FORMAT species LABEL 'adelie' => 'Pygoscelis adeliae' -- Suppress/hide a specific piece of content -FORMAT species RENAMING 'adelie' => null +FORMAT species LABEL 'adelie' => null -- Format all cells in the column as lower-case -FORMAT species RENAMING * => '{:lower}' +FORMAT species LABEL * => '{:lower}' ``` ## Examples @@ -162,7 +162,7 @@ Replace null values everywhere by selecting all columns. ```{ggsql} TABULATE * FROM my_data - FORMAT * RENAMING null => '---' + FORMAT * LABEL null => '---' ``` Replacing specific pieces of content. @@ -170,7 +170,7 @@ Replacing specific pieces of content. ```{ggsql} TABULATE * FROM my_data FORMAT body_mass, sex - RENAMING + LABEL null => '?', 'male' => '♂', 'female' => '♀' @@ -181,5 +181,5 @@ Using a formatter to target all cells in a column. ```{ggsql} TABULATE * FROM my_data FORMAT body_mass - RENAMING * => '{:num %.0f}g' + LABEL * => '{:num %.0f}g' ``` diff --git a/doc/syntax/clause/scale.qmd b/doc/syntax/clause/scale.qmd index 864330b85..6b1777c87 100644 --- a/doc/syntax/clause/scale.qmd +++ b/doc/syntax/clause/scale.qmd @@ -8,7 +8,7 @@ Scales are an important concept in ggsql. While DRAW clauses define what to draw The `SCALE` clause takes a number of subclauses, all of them optional: ```ggsql SCALE FROM TO VIA - SETTING => , ... RENAMING => + SETTING => , ... LABEL => , ... ``` The `type` defines the class of scale to use. It can be one of five different types: @@ -52,12 +52,12 @@ SETTING => , ... This clause behaves much like the `SETTINGS` clause in `DRAW`, in that it allows you to fine-tune specific behavior of the scale. Permissible settings depends on the scale type and are documented there. -### `RENAMING` +### `LABEL` ```ggsql -RENAMING => , ... +LABEL => , ... ``` -This clause works much like the `TITLE` clause but works on the break names of the scale. The general syntax is that you provide the name of the break on the left and what it should appear as on the right, e.g `'adelie' => 'Pygoscelis adeliae'`. The clause is understood as a look-up table in the sense that if you provide a renaming for a break that doesn't appear in the scale then nothing will happen and if a break exists but doesn't have a renaming defined it will go through unaltered. To suppress the label of a specific break you can rename it to `null`, e.g. `'adelie' => null`. This will not remove the break, only the label. +This clause works much like the `TITLE` clause but works on the break names of the scale. The general syntax is that you provide the name of the break on the left and what it should appear as on the right, e.g `'adelie' => 'Pygoscelis adeliae'`. The subclause is understood as a look-up table in the sense that if you provide a renaming for a break that doesn't appear in the scale then nothing will happen and if a break exists but doesn't have a renaming defined it will go through unaltered. To suppress the label of a specific break you can rename it to `null`, e.g. `'adelie' => null`. This will not remove the break, only the label. #### Break formatting Apart from the direct renaming described above it is also possible to provide a formatting function to be applied to all breaks. The syntax for this is `* => '...'` with the content of the string on the right being a string interpolation format. The basic syntax for this is that the break value will be inserted into any place where `{}` appears. This means that e.g. `* => '{} species'` will result in the label "adelie species" for the break "adelie". Besides simply inserting the value as-is, it is also possible to apply a formatter to the label before insertion by naming a formatter inside the curly braces prefixed with `:`. Known formatters are: diff --git a/doc/syntax/scale/aesthetic/Z_faceting.qmd b/doc/syntax/scale/aesthetic/Z_faceting.qmd index 7bb4e0a67..478903f7b 100644 --- a/doc/syntax/scale/aesthetic/Z_faceting.qmd +++ b/doc/syntax/scale/aesthetic/Z_faceting.qmd @@ -24,12 +24,12 @@ SCALE x ``` In order to show data where the facet variable is null, it is necessary to explicitly include `null` in the input range of a facet aesthetic scale. -Just like discrete position aesthetics. You can also use `RENAMING` on the scale to customize facet strip labels. +Just like discrete position aesthetics. You can also use `LABEL` on the scale to customize facet strip labels. ```{ggsql} VISUALISE sex AS x FROM ggsql:penguins DRAW bar FACET species SCALE panel FROM ('Adelie', null) - RENAMING null => 'The rest' + LABEL null => 'The rest' ``` diff --git a/doc/syntax/scale/type/binned.qmd b/doc/syntax/scale/type/binned.qmd index 1b35ce686..6e760d43e 100644 --- a/doc/syntax/scale/type/binned.qmd +++ b/doc/syntax/scale/type/binned.qmd @@ -145,18 +145,18 @@ SCALE BINNED x ``` ## Renaming -Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `RENAMING` clause allows you to do that both by directly renaming a specific break or by providing a formatting function. +Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `LABEL` subclause allows you to do that both by directly renaming a specific break or by providing a formatting function. ### Direct renaming -When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding `RENAMING 0 => 'Nil'` will ensure that if there is a break at 0 it will appear as "Nil" on the legend/axis +When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding `LABEL 0 => 'Nil'` will ensure that if there is a break at 0 it will appear as "Nil" on the legend/axis ### Label formatting -Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `RENAMING * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to binned scales are the `:time` and `:num` formatters which lets you control how temporal and numeric values are presented. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) +Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `LABEL * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to binned scales are the `:time` and `:num` formatters which lets you control how temporal and numeric values are presented. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) You can combine formatting with direct renaming in which case the direct renaming has priority over the formatting. ### Labels in binned legends -With some writers the legend for binned scales looks like the standard legend but with the label showing the range of the bin. In these situations the renaming is applied before the range label is being created. For example, if you have a `RENAMING 0 => 'zero'`, then the final label will become "zero – 10" (assuming the upper end of the bin is 10). There is currently no way to take control over the format of the range label. +With some writers the legend for binned scales looks like the standard legend but with the label showing the range of the bin. In these situations the renaming is applied before the range label is being created. For example, if you have a `LABEL 0 => 'zero'`, then the final label will become "zero – 10" (assuming the upper end of the bin is 10). There is currently no way to take control over the format of the range label. If `oob => 'squish'` then the terminal labels are formatted as e.g. "≥ 10" to reflect the terminal bins are open-ended. It still applies that the renaming is applied before constructing the final label @@ -168,7 +168,7 @@ If `oob => 'squish'` then the terminal labels are formatted as e.g. "≥ 10" to VISUALISE bill_dep AS x FROM ggsql:penguins DRAW bar SCALE BINNED x - RENAMING 20 => 'Twenty' + LABEL 20 => 'Twenty' ``` #### Adding suffix to break labels @@ -177,7 +177,7 @@ SCALE BINNED x VISUALISE bill_dep AS x FROM ggsql:penguins DRAW bar SCALE BINNED x - RENAMING * => '{} mm' + LABEL * => '{} mm' ``` #### Using a formatter to control number formats @@ -186,5 +186,5 @@ SCALE BINNED x VISUALISE bill_dep AS x FROM ggsql:penguins DRAW bar SCALE BINNED x - RENAMING * => '{:num %.1f}' + LABEL * => '{:num %.1f}' ``` diff --git a/doc/syntax/scale/type/continuous.qmd b/doc/syntax/scale/type/continuous.qmd index 19cc1fdb6..ee6ac8011 100644 --- a/doc/syntax/scale/type/continuous.qmd +++ b/doc/syntax/scale/type/continuous.qmd @@ -95,7 +95,7 @@ If not provided explicitly by the user the breaks for the scales will be calcula - `pretty => false`: Linear spacing in integer space as close to the requested number of breaks ### Minor breaks -Minor breaks are the unlabelled sub-divisions between two breaks — drawn as shorter ticks and fainter gridlines. They carry no labels, so unlike `breaks` they are never affected by `RENAMING` or a label template. +Minor breaks are the unlabelled sub-divisions between two breaks — drawn as shorter ticks and fainter gridlines. They carry no labels, so unlike `breaks` they are never affected by `LABEL` or a label template. Where `breaks => 5` asks for about five breaks across the whole scale, `minor_breaks => 3` asks for three minor breaks *inside each interval between two breaks*. @@ -207,13 +207,13 @@ SCALE x ``` ## Renaming -Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `RENAMING` clause allows you to do that both by directly renaming a specific break or by providing a formatting function. +Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `LABEL` subclause allows you to do that both by directly renaming a specific break or by providing a formatting function. ### Direct renaming -When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding `RENAMING 0 => 'Nil'` will ensure that if there is a break at 0 it will appear as "Nil" on the legend/axis +When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding `LABEL 0 => 'Nil'` will ensure that if there is a break at 0 it will appear as "Nil" on the legend/axis ### Label formatting -Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `RENAMING * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to continuous scales are the `:time` and `:num` formatters which lets you control how temporal and numeric values are presented. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) +Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `LABEL * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to continuous scales are the `:time` and `:num` formatters which lets you control how temporal and numeric values are presented. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) You can combine formatting with direct renaming in which case the direct renaming has priority over the formatting. @@ -225,7 +225,7 @@ You can combine formatting with direct renaming in which case the direct renamin VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point SCALE x - RENAMING 50 => 'Fifty' + LABEL 50 => 'Fifty' ``` #### Adding suffix to break labels @@ -234,7 +234,7 @@ SCALE x VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point SCALE x - RENAMING * => '{} mm' + LABEL * => '{} mm' ``` #### Using a formatter to control temporal formats @@ -243,7 +243,7 @@ SCALE x VISUALISE Date AS x, Temp AS y FROM ggsql:airquality DRAW line SCALE x - RENAMING * => '{:time %B}' + LABEL * => '{:time %B}' ``` #### Using a formatter to control number formats @@ -252,5 +252,5 @@ SCALE x VISUALISE bill_len AS x, bill_dep AS y FROM ggsql:penguins DRAW point SCALE x - RENAMING * => '{:num %.3e}' + LABEL * => '{:num %.3e}' ``` diff --git a/doc/syntax/scale/type/discrete.qmd b/doc/syntax/scale/type/discrete.qmd index 63d76c9cf..146832fcf 100644 --- a/doc/syntax/scale/type/discrete.qmd +++ b/doc/syntax/scale/type/discrete.qmd @@ -88,13 +88,13 @@ SCALE color FROM ('Adelie', 'Chinstrap', 'Gentoo') ``` ## Renaming -Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `RENAMING` clause allows you to do that both by directly renaming a specific break or by providing a formatting function. +Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `LABEL` subclause allows you to do that both by directly renaming a specific break or by providing a formatting function. ### Direct renaming -When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding RENAMING 'Adelie' => 'Adélie' will ensure that the species name will get the correct diacrit in the label. +When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding LABEL 'Adelie' => 'Adélie' will ensure that the species name will get the correct diacrit in the label. ### Label formatting -Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `RENAMING * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to discrete scales are the `:Title`, `:lower`, and `:UPPER` formatters which lets you control the casing of strings. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) +Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `LABEL * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to discrete scales are the `:Title`, `:lower`, and `:UPPER` formatters which lets you control the casing of strings. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) You can combine formatting with direct renaming in which case the direct renaming has priority over the formatting. @@ -106,7 +106,7 @@ You can combine formatting with direct renaming in which case the direct renamin VISUALISE sex AS x FROM ggsql:penguins DRAW bar SCALE x - RENAMING 'null' => 'missing' + LABEL 'null' => 'missing' SCALE y FROM (0, null) ``` @@ -116,7 +116,7 @@ SCALE y FROM (0, null) VISUALISE species AS x FROM ggsql:penguins DRAW bar SCALE x - RENAMING * => 'Species: {}' + LABEL * => 'Species: {}' SCALE y FROM (0, null) ``` @@ -126,5 +126,5 @@ SCALE y FROM (0, null) VISUALISE bill_len AS x, bill_dep AS y, sex AS color FROM ggsql:penguins DRAW point SCALE color - RENAMING * => '{:Title}' + LABEL * => '{:Title}' ``` diff --git a/doc/syntax/scale/type/ordinal.qmd b/doc/syntax/scale/type/ordinal.qmd index 2440f5e11..8b7dc7daa 100644 --- a/doc/syntax/scale/type/ordinal.qmd +++ b/doc/syntax/scale/type/ordinal.qmd @@ -93,13 +93,13 @@ SCALE ORDINAL color ``` ## Renaming -Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `RENAMING` clause allows you to do that both by directly renaming a specific break or by providing a formatting function. +Breaks are generally named by their value. However, you may wish to rename one, several, or all of these. The `LABEL` subclause allows you to do that both by directly renaming a specific break or by providing a formatting function. ### Direct renaming -When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding RENAMING 6 => 'June' will ensure that a month given as an integer gets the right name. +When you provide a break value on the left and a break exists at that value then it will take on the label specified on the right. For example adding LABEL 6 => 'June' will ensure that a month given as an integer gets the right name. ### Label formatting -Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `RENAMING * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to ordinal scales are the `:Title`, `:lower`, and `:UPPER` formatters which lets you control the casing of strings. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) +Besides direct renaming you can also provide a formatting string if you want the same to happen to all labels, e.g. add a prefix or suffix. The syntax for this is `LABEL * => '... {} ...'`. The current label will be inserted into the `{}` to produce the new label. Besides simply inserting the break value into the string, we can also provide a formatter. Of special interest to ordinal scales are the `:Title`, `:lower`, and `:UPPER` formatters which lets you control the casing of strings. You can read more about these formatters in [the break formatting section of the `SCALE` documentation](../../clause/scale.qmd#break-formatting) You can combine formatting with direct renaming in which case the direct renaming has priority over the formatting. @@ -112,7 +112,7 @@ VISUALISE Ozone AS x, Temp AS y FROM ggsql:airquality DRAW point MAPPING Month AS color SCALE ORDINAL color - RENAMING 6 => 'June' + LABEL 6 => 'June' ``` #### Use string interpolation to add a suffix @@ -122,7 +122,7 @@ VISUALISE Ozone AS x, Temp AS y FROM ggsql:airquality DRAW point MAPPING Month AS color SCALE ORDINAL color - RENAMING * => '{}th month' + LABEL * => '{}th month' ``` #### Use a formatter to make labels shouty @@ -149,5 +149,5 @@ SCALE ORDINAL color 'Moderate Breeze', 'Fresh Breeze' ) - RENAMING * => '{:UPPER}' + LABEL * => '{:UPPER}' ``` diff --git a/doc/vendor/SKILL.md b/doc/vendor/SKILL.md index fd8458ab8..c62e9fdc2 100644 --- a/doc/vendor/SKILL.md +++ b/doc/vendor/SKILL.md @@ -99,7 +99,7 @@ Maps data → aesthetic output; sensible defaults always apply. Only `aesthetic` ``` SCALE FROM TO VIA SETTING => , ... - RENAMING =>