Подсветка синтаксиса не копируется при вставке в место, поддерживающее цветной текст

Когда я скопировал приведённый ниже фрагмент из Discourse в свой почтовый клиент:

@@ -1,11 +1,11 @@
-Премия «Молодой волонтёр» — чествование молодых волонтёров в возрасте от 16 до 24 лет, которые делают больше, чем от них ожидают, в своих местных сообществах, демонстрируя наши ценности и важность связей и действий.
+Премия «Молодой волонтёр» отмечает молодых волонтёров в возрасте от 16 до 24 лет, которые делают больше, чем от них ожидают, в своих местных сообществах, демонстрируя наши ценности и важность связей и действий.
 
 Знаете ли вы молодого человека, который:
 
-Занимается волонтёрством в рамках «Соседского наблюдения» и оказывает положительное влияние на своё сообщество.
+• Занимается волонтёрством в рамках «Соседского наблюдения» и оказывает положительное влияние на своё сообщество?
 
-Выделяет своё время на поддержку местного сообщества (продовольственные банки, общественные центры и группы, бездомные, религиозные организации)
+• Выделяет своё время на поддержку местного сообщества (продовольственные банки, общественные центры и группы, бездомные, религиозные организации)?
 
-Проводил благотворительные мероприятия в своей школе или колледже или организовывал сбор мусора или другие местные мероприятия.
+• Проводил благотворительные мероприятия в своей школе или колледже или организовывал сбор мусора или другие местные мероприятия?
 
-Вы считаете, что этот молодой волонтёр заслуживает признания за свою тяжёлую работу и преданность своему сообществу.
+Если да, то считаете ли вы, что этот молодой волонтёр заслуживает признания за свою тяжёлую работу и преданность своему сообществу?

…цветовое оформление не было скопировано.

Вы использовали diff? Возможно, ваш почтовый клиент его не поддерживает?

- вот некоторый текст
+ вот ещё немного текста

@Lilly, да. Указание diff обязательно для отображения цветовой подсветки в Discourse:

  1. ```
    @@ -1,11 +1,11 @@
    -Young volunteer award – celebrating young volunteers, aged 16-24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.
    +The Young Volunteer Award celebrates young volunteers, aged 16–24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.
     
     Do you know a young person who:
     
    -Has been volunteering with Neighbourhood Watch and making a positive impact in their community.
    +• Has been volunteering with Neighbourhood Watch and making a positive impact in their community?
     
    -Gives up their time to support their local community (foodbanks, community hubs and groups, homeless, faith groups)
    +• Gives up their time to support their local community (foodbanks, community hubs and groups, homeless, faith groups)?
     
    -Held fundraising activities with their school or college or have organised litter picks or other local events.
    +• Held fundraising activities with their school or college or have organised litter picks or other local events?
     
    -You think this young volunteer deserves to be recognised for their hard work and commitment to their community.
    +If so, do you think this young volunteer deserves to be recognised for their hard work and commitment to their community?
    ```
    
  2. @@ -1,11 +1,11 @@
    -Young volunteer award – celebrating young volunteers, aged 16-24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.
    +The Young Volunteer Award celebrates young volunteers, aged 16–24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.
     
     Do you know a young person who:
     
    -Has been volunteering with Neighbourhood Watch and making a positive impact in their community.
    +• Has been volunteering with Neighbourhood Watch and making a positive impact in their community?
     
    -Gives up their time to support their local community (foodbanks, community hubs and groups, homeless, faith groups)
    +• Gives up their time to support their local community (foodbanks, community hubs and groups, homeless, faith groups)?
     
    -Held fundraising activities with their school or college or have organised litter picks or other local events.
    +• Held fundraising activities with their school or college or have organised litter picks or other local events?
     
    -You think this young volunteer deserves to be recognised for their hard work and commitment to their community.
    +If so, do you think this young volunteer deserves to be recognised for their hard work and commitment to their community?
    

Вы имеете в виду, что я создаю CommonMark в своём клиенте?

Если да, то это вопрос для другой площадки:

Вместо этого я говорю о прямом копировании из отрендеренной разметки здесь, например:

Да, я, разумеется, это знаю, поэтому и спрашивал у тебя.

@Lilly, вы можете увидеть в /1, что я, впрочем, использовал это.

О, извините, я сначала подумал, что это скриншот.

1 лайк

Сегодня это зависит от того, как вы копируете.

Использование кнопки копирования:

помещает в буфер обмена только текстовую версию, среди прочего:

TIMESTAMP,TARGETS,SAVE_TARGETS,MULTIPLE,UTF8_STRING,STRING,TEXT,text/plain,text/plain;charset=utf-8,chromium/x-internal-source-rfh-token,chromium/x-source-url

а копирование самого текста работает:

так как вы копируете отрендеренный HTML через браузер, а не через взаимодействие Discourse с буфером обмена, формат text/HTML доступен для приложений, использующих буфер обмена:

<span class="hljs-meta" style="color: rgb(133, 133, 133); font-style: italic; font-family: &quot;JetBrains Mono&quot;, Consolas, Monaco, monospace; font-size: 15.75px; font-variant-ligatures: none; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: pre; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">@@ -1,11 +1,11 @@</span><span style="color: rgb(199, 199, 199); font-family: &quot;JetBrains Mono&quot;, Consolas, Monaco, monospace; font-size: 15.75px; font-style: normal; font-variant-ligatures: none; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: pre; background-color: rgba(0, 0, 0, 0.25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">\n</span><span class="hljs-deletion" style="background: none 0% 0% / auto repeat scroll padding-box border-box rgb(79, 24, 11); color: rgb(222, 113, 118); font-family: &quot;JetBrains Mono&quot;, Consolas, Monaco, monospace; font-size: 15.75px; font-style: normal; font-variant-ligatures: none; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: pre; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">-Young volunteer award – celebrating young volunteers, aged 16-24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.</span><span style="color: rgb(199, 199, 199); font-family: &quot;JetBrains Mono&quot;, Consolas, Monaco, monospace; font-size: 15.75px; font-style: normal; font-variant-ligatures: none; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: pre; background-color: rgba(0, 0, 0, 0.25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">\n</span><span class="hljs-addition" style="background: none 0% 0% / auto repeat scroll padding-box border-box rgb(11, 66, 32); color: rgb(118, 196, 144); font-family: &quot;JetBrains Mono&quot;, Consolas, Monaco, monospace; font-size: 15.75px; font-style: normal; font-variant-ligatures: none; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: pre; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">+The Young Volunteer Award celebrates young volunteers, aged 16–24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.</span><span style="color: rgb(199, 199, 199); font-family: &quot;JetBrains Mono&quot;, Consolas, Monaco, monospace; font-size: 15.75px; font-style: normal; font-variant-ligatures: none; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; white-space: pre; background-color: rgba(0, 0, 0, 0.25); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">\n</span><br class="Apple-interchange-newline">

Чтобы поддержать это через кнопку копирования, нам нужно добавить возможность брать отрендеренную раскрашенную версию (поскольку раскраска выполняется библиотекой) и отправлять её в буфер обмена в формате text/html. Это, вероятно, возможно (возможно, даже как компонент темы), но пока всегда есть вариант копирования через выделение.

3 лайка

@supermathie, спасибо. Тогда, похоже, проблема в моём клиенте (protonMail/webClients, 5.0.115.3 β):

Screencast20260522180439

Однако раскраска также не копируется в thunderbird-149.0.1-2.fc44, хотя у вас она, похоже, работает:

Есть ли у вас какие-либо идеи, что вы делаете иначе, если вообще что-то делаете?

Когда вы копируете в ProtonMail, будучи веб-клиентом, это выглядит так, будто используется версия в обычном тексте. Обратите внимание на отсутствие различий в форматировании, хотя это трудно сказать, так как вы переопределяете шрифты.

Сравните с вставкой в Thunderbird:

Оно захватывает некоторую часть форматирования, но не всю.

Если я копирую, оно захватывает всё:

Думаю, чтобы разобраться в этом, нужно определить, что именно происходит:

  • копируются не все стили
  • или не все стили вставляются

Начать с чистого браузера без расширений может помочь в выяснении? Например, если я использую приватный браузер без расширений и прочего, я получаю:

Этот скрипт, который я написал, также даст вам возможность увидеть содержимое буфера обмена, что может помочь.

(или, возможно, Arch » Fedora :face_with_tongue:)

1 лайк

@supermathie, это потому, что таблица стилей по умолчанию в ProtonMail ужасна.

Согласно вашим рекомендациям, я установил, что сам Firefox (даже не мой профиль, так как проблема воспроизводится при создании нового в about:profiles) не может это скопировать:

Я очень благодарен!

Да! У меня наблюдается такое же поведение.

И если быть точным, это не баг. Firefox копирует HTML в точности так, как запрошено:

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<p dir="auto">Когда я копировал указанное ниже из Discourse в свой почтовый клиент:</p>
<pre data-code-wrap="diff" dir="auto" class="codeblock-buttons">
		<div class="codeblock-button-wrapper" style="right: 0px;"></div>
		<code class="lang-diff hljs language-diff" data-highlighted="yes">
			<span class="hljs-meta">@@ -1,11 +1,11 @@</span>
			<span class="hljs-deletion">-Young volunteer award – celebrating young volunteers, aged 16-24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.</span>
			<span class="hljs-addition">+The Young Volunteer Award celebrates young volunteers, aged 16–24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.</span>
		</code>
	</pre>

Получившаяся разница после вставки возникает из-за того, что Chromium встраивает стили, а Firefox — нет. Если сократить всё до одной строки, становится ясно[1], что происходит:

<span
  class="hljs-deletion">
-Young volunteer award – celebrating young volunteers, aged 16-24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.
</span>
<span
  class="hljs-deletion"
  style="background: none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 224, 224); color: rgb(192, 45, 46);">
-Young volunteer award – celebrating young volunteers, aged 16-24, who go the extra mile in their local communities, demonstrating our values and the importance of connection and action.
</span>

(добавлены переносы строк)

Chromium извлекает из class="hljs-deletion" встроенный CSS style="background: none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 224, 224); color: rgb(192, 45, 46);" и применяет его к тегу span, поскольку в том месте, куда происходит вставка, вероятно, нет такого стиля.


  1. ха-ха ↩︎