Commit d059576965

d059576965c57af8b476650d2cca862416095a49

parent: e2ffb55e84

Unregistered key

Anand B <anandbiju71@gmail.com> · 2026-10-09 09:43 UTC
committer: <noreply@github.com>

Allow configuring the date and time formats (#789)

Co-authored-by: vaw <git@nlih.de>

Layout: unified · split

config.full.toml +8
@@ -20,6 +20,9 @@ password_file = "/path/to/password"
2020url = "https://matrix-client.matrix.org"
2121
2222[settings]
23# strftime format for the date separator. See
24# https://docs.rs/chrono/latest/chrono/format/strftime/index.html
25# date_format = "%A, %B %d %Y"
2326default_markup = "markdown"
2427default_register = "\""
2528default_room = "#iamb-users:0x.badd.cafe"
@@ -39,6 +42,11 @@ read_receipt_send = true
3942room_labels = ["membership", "muted", "tags"]
4043request_timeout = 10000
4144sync_delay_ms = 1000
45# strftime format for the per-message time gutter (same specifier reference as
46# date_format). This string is the full gutter text, including brackets and
47# spacing. Column width follows the rendered format. An empty string disables
48# the time display.
49# time_format = " [%T]"
4250typing_notice_display = true
4351typing_notice_send = true
4452user_gutter_width = 30
docs/iamb.5 +20
@@ -142,6 +142,13 @@ Specifying this object will replace the upstream defaults and possibly lead to u
142142Possible keys and their effect are documented at:
143143.br
144144.Lk https://docs.rs/matrix-sdk/latest/matrix_sdk/media/struct.MediaRetentionPolicy.html#fields
145.It Sy date_format
146A strftime format string for the date separator between messages from different days.
147See
148.Lk https://docs.rs/chrono/latest/chrono/format/strftime/index.html
149for the conversion specifiers.
150Defaults to
151.Dq "%A, %B %d %Y" .
145152.It Sy default_markup
146153Controls how text in the message bar is interpreted by default.
147154Possible values are
@@ -331,6 +338,19 @@ Subsection for configuring how specific terminal features are used (or not used)
331338See
332339.Sx TERMINAL
333340for more details.
341.It Sy time_format
342A strftime format string for the time shown beside each message.
343See
344.Lk https://docs.rs/chrono/latest/chrono/format/strftime/index.html
345for the conversion specifiers.
346The value is the full gutter text, including any brackets or spacing.
347Its display width, measured by rendering the format for a sample timestamp,
348is the width of the time column and does not change from message to message.
349An empty string disables the time display and reserves no columns.
350Defaults to
351.Dq " [%T]" ,
352which renders as
353.Dq " [HH:MM:SS]" .
334354.It Sy typing_notice_send
335355Defines whether or not the typing state is sent.
336356.It Sy typing_notice_display
src/config/mod.rs +153
@@ -7,6 +7,8 @@ use std::process;
77use std::sync::Arc;
88
99use anyhow::anyhow;
10use chrono::format::{Item, StrftimeItems};
11use chrono::{DateTime, Local};
1012use clap::Parser;
1113use indexmap::IndexMap;
1214use lazy_static::lazy_static;
@@ -90,6 +92,37 @@ const DEFAULT_ICON_UNKNOWN: Cow<'static, str> = Cow::Borrowed("[?] ");
9092
9193const DEFAULT_LOG_LEVEL: &str = "off";
9294
95/// Default date separator, matching the historical hard-coded `"%A, %B %d %Y"`.
96const DEFAULT_DATE_FORMAT: &str = "%A, %B %d %Y";
97
98/// Default time gutter, preserving the historical ` [HH:MM:SS]` rendering.
99const DEFAULT_TIME_FORMAT: &str = " [%T]";
100
101/// Unix seconds of the timestamp used to measure time-gutter width.
102///
103/// 2024-01-17 13:25:30 UTC, so numeric fields have their usual widths.
104const TIME_GUTTER_SAMPLE_UNIX: i64 = 1_705_497_930;
105
106fn time_gutter_sample() -> DateTime<Local> {
107 DateTime::from_timestamp(TIME_GUTTER_SAMPLE_UNIX, 0)
108 .unwrap_or_default()
109 .with_timezone(&Local)
110}
111
112/// Display columns reserved for the per-message time gutter.
113///
114/// The width is the display width of `format` applied to one fixed sample
115/// timestamp, so a configuration keeps a constant column. An empty format
116/// reserves nothing and hides the time.
117pub fn time_gutter_width(format: &str) -> usize {
118 if format.is_empty() {
119 return 0;
120 }
121
122 let rendered = time_gutter_sample().format(format).to_string();
123 UnicodeWidthStr::width(rendered.as_str())
124}
125
93126fn is_profile_char(c: char) -> bool {
94127 c.is_ascii_alphanumeric() || c == '.' || c == '-'
95128}
@@ -170,6 +203,21 @@ where
170203 Ok(Some(r))
171204}
172205
206fn deserialize_strftime<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
207where
208 D: Deserializer<'de>,
209{
210 let value = String::deserialize(deserializer)?;
211
212 // `DelayedFormat`'s `Display` impl returns `fmt::Error` for a bad specifier,
213 // and `.to_string()` then panics. Reject those strings while loading config.
214 if StrftimeItems::new(&value).any(|item| matches!(item, Item::Error)) {
215 return Err(D::Error::custom(format!("invalid strftime format string: {value:?}")));
216 }
217
218 Ok(Some(value))
219}
220
173221/// Load themes from disk, and merge in the configured overrides.
174222fn load_themes(
175223 themes_dir: &Path,
@@ -942,6 +990,11 @@ pub struct TunableValues {
942990 pub ssl_verify: bool,
943991 pub cache_policy: MediaRetentionPolicy,
944992 pub send_on_enter: bool,
993 pub date_format: String,
994 pub time_format: String,
995 /// Display columns reserved for the time gutter, computed from
996 /// `time_format` once when the settings are loaded.
997 pub time_gutter_width: usize,
945998}
946999
9471000#[derive(Clone, Debug, Default, Deserialize)]
@@ -1002,6 +1055,13 @@ pub struct Tunables {
10021055 pub ssl_verify: Option<bool>,
10031056 pub cache_policy: Option<MediaRetentionPolicy>,
10041057 pub send_on_enter: Option<bool>,
1058 #[serde(default, deserialize_with = "deserialize_strftime")]
1059 pub date_format: Option<String>,
1060 /// strftime string for the per-message time gutter, including any brackets
1061 /// or spacing. The column is as wide as a sample rendering of this string.
1062 /// An empty string hides the time.
1063 #[serde(default, deserialize_with = "deserialize_strftime")]
1064 pub time_format: Option<String>,
10051065}
10061066
10071067impl Tunables {
@@ -1062,10 +1122,15 @@ impl Tunables {
10621122 ssl_verify: self.ssl_verify.or(other.ssl_verify),
10631123 cache_policy: self.cache_policy.or(other.cache_policy),
10641124 send_on_enter: self.send_on_enter.or(other.send_on_enter),
1125 date_format: self.date_format.or(other.date_format),
1126 time_format: self.time_format.or(other.time_format),
10651127 }
10661128 }
10671129
10681130 fn values(self) -> TunableValues {
1131 let time_format = self.time_format.unwrap_or_else(|| DEFAULT_TIME_FORMAT.to_owned());
1132 let time_gutter_width = time_gutter_width(&time_format);
1133
10691134 TunableValues {
10701135 encryption: self.encryption.values(),
10711136 proxy: self.proxy.unwrap_or_default().values(),
@@ -1116,6 +1181,9 @@ impl Tunables {
11161181 ssl_verify: self.ssl_verify.unwrap_or(true),
11171182 cache_policy: self.cache_policy.unwrap_or_default(),
11181183 send_on_enter: self.send_on_enter.unwrap_or(true),
1184 date_format: self.date_format.unwrap_or_else(|| DEFAULT_DATE_FORMAT.to_owned()),
1185 time_format,
1186 time_gutter_width,
11191187 }
11201188 }
11211189}
@@ -1806,6 +1874,91 @@ mod tests {
18061874 assert_eq!(res.users, Some(users.into_iter().collect()));
18071875 }
18081876
1877 fn parse_settings_toml(input: &str) -> Result<Tunables, toml::de::Error> {
1878 #[derive(Deserialize)]
1879 struct SettingsToml {
1880 settings: Tunables,
1881 }
1882
1883 toml::from_str::<SettingsToml>(input).map(|doc| doc.settings)
1884 }
1885
1886 #[test]
1887 fn test_parse_tunables_date_time_format() {
1888 let settings = parse_settings_toml(
1889 r#"
1890[settings]
1891date_format = "%Y-%m-%d"
1892time_format = "%H:%M"
1893"#,
1894 )
1895 .unwrap();
1896 assert_eq!(settings.date_format.as_deref(), Some("%Y-%m-%d"));
1897 assert_eq!(settings.time_format.as_deref(), Some("%H:%M"));
1898
1899 let values = settings.values();
1900 assert_eq!(values.date_format, "%Y-%m-%d");
1901 assert_eq!(values.time_format, "%H:%M");
1902 assert_eq!(values.time_gutter_width, 5);
1903
1904 // Absent keys keep today's formats.
1905 let settings = parse_settings_toml("[settings]\n").unwrap();
1906 assert_eq!(settings.date_format, None);
1907 assert_eq!(settings.time_format, None);
1908 let values = settings.values();
1909 assert_eq!(values.date_format, "%A, %B %d %Y");
1910 assert_eq!(values.time_format, " [%T]");
1911 assert_eq!(values.time_gutter_width, 12);
1912
1913 // An empty format is valid and disables the time column.
1914 let settings = parse_settings_toml(
1915 r#"
1916[settings]
1917time_format = ""
1918"#,
1919 )
1920 .unwrap();
1921 assert_eq!(settings.time_format.as_deref(), Some(""));
1922 let values = settings.values();
1923 assert_eq!(values.time_format, "");
1924 assert_eq!(values.time_gutter_width, 0);
1925
1926 // Brackets and spacing are literal gutter text, not added later.
1927 let settings = parse_settings_toml(
1928 r#"
1929[settings]
1930time_format = " [%H:%M]"
1931"#,
1932 )
1933 .unwrap();
1934 let values = settings.values();
1935 assert_eq!(values.time_format, " [%H:%M]");
1936 assert_eq!(values.time_gutter_width, 9);
1937 }
1938
1939 #[test]
1940 fn test_parse_tunables_date_time_format_invalid() {
1941 let err = parse_settings_toml(
1942 r#"
1943[settings]
1944date_format = "%Q"
1945"#,
1946 )
1947 .unwrap_err();
1948 let msg = err.to_string();
1949 assert!(msg.contains("invalid strftime"), "{msg}");
1950
1951 let err = parse_settings_toml(
1952 r#"
1953[settings]
1954time_format = "%"
1955"#,
1956 )
1957 .unwrap_err();
1958 let msg = err.to_string();
1959 assert!(msg.contains("invalid strftime"), "{msg}");
1960 }
1961
18091962 #[test]
18101963 fn test_parse_tunables_username_display() {
18111964 let res: Tunables = serde_json::from_str("{\"username_display\": \"username\"}").unwrap();
src/message/mod.rs +91 −29
@@ -104,26 +104,9 @@ impl Messages {
104104 }
105105}
106106
107const fn span_static(s: &'static str) -> Span<'static> {
108 Span {
109 content: Cow::Borrowed(s),
110 style: Style {
111 fg: None,
112 bg: None,
113 add_modifier: StyleModifier::empty(),
114 sub_modifier: StyleModifier::empty(),
115 underline_color: None,
116 },
117 }
118}
119
120const TIME_GUTTER: usize = 12;
121107const READ_GUTTER: usize = 5;
122108const MIN_MSG_LEN: usize = 30;
123109
124const TIME_GUTTER_EMPTY: &str = " ";
125const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
126
127110const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS;
128111
129112/// Convert the [u64] hash to [usize] as needed.
@@ -221,7 +204,10 @@ impl MessageTimeStamp {
221204 }
222205
223206 fn show_date(self, settings: &ApplicationSettings) -> Span<'static> {
224 let time = self.as_datetime().format("%A, %B %d %Y").to_string();
207 let time = self
208 .as_datetime()
209 .format(settings.tunables.date_format.as_str())
210 .to_string();
225211
226212 Span::styled(time, settings.theme.timeline.date)
227213 }
@@ -232,8 +218,10 @@ impl MessageTimeStamp {
232218 }
233219
234220 fn show_time(self, settings: &ApplicationSettings) -> Span<'static> {
235 let time = self.as_datetime().format("%T");
236 let time = format!(" [{time}]");
221 let time = self
222 .as_datetime()
223 .format(settings.tunables.time_format.as_str())
224 .to_string();
237225
238226 Span::styled(time, settings.theme.timeline.time)
239227 }
@@ -774,7 +762,9 @@ impl<'a> MessageFormatter<'a> {
774762 match self.cols {
775763 MessageColumns::Four => {
776764 let settings = self.settings;
777 let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
765 let time = self.time.take().unwrap_or_else(|| {
766 space_span(settings.tunables.time_gutter_width, Style::default())
767 });
778768
779769 let mut line = vec![user_gutter];
780770 line.extend(prev_line.spans);
@@ -1129,13 +1119,14 @@ impl Message {
11291119 ) -> usize {
11301120 let width = viewctx.get_width();
11311121 let user_gutter = settings.tunables.user_gutter_width;
1122 let time_gutter = settings.tunables.time_gutter_width;
11321123
1133 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
1124 if user_gutter + time_gutter + READ_GUTTER + MIN_MSG_LEN <= width &&
11341125 settings.tunables.read_receipt_display
11351126 {
1136 width - user_gutter - TIME_GUTTER - READ_GUTTER
1137 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1138 width - user_gutter - TIME_GUTTER
1127 width - user_gutter - time_gutter - READ_GUTTER
1128 } else if user_gutter + time_gutter + MIN_MSG_LEN <= width {
1129 width - user_gutter - time_gutter
11391130 } else if user_gutter + MIN_MSG_LEN <= width {
11401131 width - user_gutter
11411132 } else {
@@ -1154,12 +1145,13 @@ impl Message {
11541145 let date = self.show_date(prev).then(|| self.timestamp.show_date(settings));
11551146 let trackbar = self.show_trackbar(prev, info, settings);
11561147 let user_gutter = settings.tunables.user_gutter_width;
1148 let time_gutter = settings.tunables.time_gutter_width;
11571149
1158 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
1150 if user_gutter + time_gutter + READ_GUTTER + MIN_MSG_LEN <= width &&
11591151 settings.tunables.read_receipt_display
11601152 {
11611153 let cols = MessageColumns::Four;
1162 let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
1154 let fill = width - user_gutter - time_gutter - READ_GUTTER;
11631155 let user = self.show_sender(prev, true, info, settings, width);
11641156 let time = Some(self.timestamp.show_time(settings));
11651157
@@ -1190,9 +1182,9 @@ impl Message {
11901182 read,
11911183 info,
11921184 }
1193 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1185 } else if user_gutter + time_gutter + MIN_MSG_LEN <= width {
11941186 let cols = MessageColumns::Three;
1195 let fill = width - user_gutter - TIME_GUTTER;
1187 let fill = width - user_gutter - time_gutter;
11961188 let user = self.show_sender(prev, true, info, settings, width);
11971189 let time = Some(self.timestamp.show_time(settings));
11981190 let read = Vec::new();
@@ -1647,6 +1639,7 @@ pub mod tests {
16471639 };
16481640
16491641 use crate::base::EventLocation;
1642 use crate::config::time_gutter_width;
16501643 use crate::tests::*;
16511644
16521645 #[test]
@@ -2060,4 +2053,73 @@ pub mod tests {
20602053 settings.tunables.message_formatted_display = false;
20612054 assert_eq!(render(&settings), "**hello** <world>");
20622055 }
2056
2057 /// `MessageTimeStamp::as_datetime` converts to the local timezone, so
2058 /// expectations are computed with the same conversion rather than a
2059 /// hard-coded wall clock.
2060 fn sample_stamp() -> (MessageTimeStamp, DateTime<LocalTz>) {
2061 let millis = MilliSecondsSinceUnixEpoch(UInt::try_from(1_705_325_130_000u64).unwrap());
2062 let ts = MessageTimeStamp::from(millis);
2063 (ts, ts.as_datetime())
2064 }
2065
2066 #[test]
2067 fn test_show_time_and_date_defaults() {
2068 let (ts, dt) = sample_stamp();
2069 let settings = mock_settings();
2070
2071 let date = ts.show_date(&settings);
2072 assert_eq!(date.content.as_ref(), dt.format("%A, %B %d %Y").to_string());
2073
2074 let time = ts.show_time(&settings);
2075 assert_eq!(time.content.as_ref(), format!(" [{}]", dt.format("%T")));
2076 assert_eq!(UnicodeWidthStr::width(time.content.as_ref()), 12);
2077 assert_eq!(settings.tunables.time_gutter_width, 12);
2078 }
2079
2080 #[test]
2081 fn test_time_gutter_width_follows_format() {
2082 let (ts, dt) = sample_stamp();
2083 let mut settings = mock_settings();
2084 let view = ViewportContext { dimensions: (120, 10), ..Default::default() };
2085 let default_cols = Message::message_column_width(&view, &settings);
2086
2087 // "%H:%M" is five columns and is not padded out to the old gutter.
2088 settings.tunables.time_format = "%H:%M".to_string();
2089 settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format);
2090 let time = ts.show_time(&settings);
2091 let rendered = dt.format("%H:%M").to_string();
2092 assert_eq!(time.content.as_ref(), rendered);
2093 assert_eq!(UnicodeWidthStr::width(rendered.as_str()), 5);
2094 assert_eq!(settings.tunables.time_gutter_width, 5);
2095 assert_eq!(Message::message_column_width(&view, &settings), default_cols + 7);
2096
2097 // An empty format hides the time and reserves no column.
2098 settings.tunables.time_format = String::new();
2099 settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format);
2100 let time = ts.show_time(&settings);
2101 assert_eq!(time.content.as_ref(), "");
2102 assert_eq!(UnicodeWidthStr::width(time.content.as_ref()), 0);
2103 assert_eq!(settings.tunables.time_gutter_width, 0);
2104 assert_eq!(Message::message_column_width(&view, &settings), default_cols + 12);
2105
2106 // Wider than the historical 8-column cap, and a wide character counts as two.
2107 settings.tunables.time_format = "%H時%M分".to_string();
2108 settings.tunables.time_gutter_width = time_gutter_width(&settings.tunables.time_format);
2109 let time = ts.show_time(&settings);
2110 let rendered = dt.format("%H時%M分").to_string();
2111 assert_eq!(time.content.as_ref(), rendered);
2112 assert_eq!(UnicodeWidthStr::width(rendered.as_str()), 8);
2113 assert_eq!(settings.tunables.time_gutter_width, 8);
2114 assert_eq!(Message::message_column_width(&view, &settings), default_cols + 4);
2115 }
2116
2117 #[test]
2118 fn test_show_custom_date_format() {
2119 let (ts, dt) = sample_stamp();
2120 let mut settings = mock_settings();
2121 settings.tunables.date_format = "%Y-%m-%d".to_string();
2122 let date = ts.show_date(&settings);
2123 assert_eq!(date.content.as_ref(), dt.format("%Y-%m-%d").to_string());
2124 }
20632125}
src/tests.rs +3
@@ -201,6 +201,9 @@ pub fn mock_tunables() -> TunableValues {
201201 ssl_verify: true,
202202 cache_policy: Default::default(),
203203 send_on_enter: true,
204 date_format: "%A, %B %d %Y".to_string(),
205 time_format: " [%T]".to_string(),
206 time_gutter_width: 12,
204207 }
205208}
206209