1

Тема: AHK: текст с форматированием + без форматирования в clipboard

Здравствуйте, хочу иметь возможность сохранять полезный текст с интернета, для удобства последующего чтения было бы хорошо сохранять его с форматированием.
Так же часто сохраняю с английских сайтов, и для удобства поиска, хочу сохранять английскую и переведенную версии.
Проблема в том, что когда ввожу в Clipboard переменную с форматированным оригинальным текстом с сайта + переведенный не форматированный текст, то вместо форматированного оригинального текста получаю иероглиф 쀉 + переведенный не форматированный текст но каждое первое слово новой строки напечатано каким-то большим шрифтом.
Если в Clipboard только переменная с форматированным оригинальным текстом с сайта, то получаю нормальный форматированный текст.
В чем проблема? И как её можно решить?

Пример взят с сайта https://www.sustainweb.org/realbread/ascorbic_acid/#e300_function
Текст сохраняю

^s::
MouseGetPos,,, WinUMID
WinActivate, ahk_id %WinUMID%
WinGetActiveTitle, win
Clip := SubStr(win, 1, 195)
haystack := clip
    needle := "[\?<>/\\\*""|:]"
    replacement := "_"
   ;msgbox, % winc := RegExReplace(haystack, needle, replacement)
   winc := RegExReplace(haystack, needle, replacement)
;name = %OutDir%\%winc% %OutNameNoExt%.%OutExtension%
;MsgBox, % clipboard "`n" t
;FileAppend, %t%, test.rtf
	clipb := Clipboardall
    ;sleep, 4000
;MsgBox, % Clipboard
;b := Clipboard
Clipboard=
loop,30
{
sleep,10
} until !Clipboard

Clipboard := clipb "`n" t
loop,700
{
sleep,10
} until Clipboard

;Sleep, 5000
;{
;MsgBox, % Clipboard
saveAsWordDoc("C:\staff\screentextshot" "\" winc ".docx")
saveAsWordDoc(fileName) {	
;Sleep, 5000
;MsgBox, % Clipboard
	static	_ :=	ComObjMissing()
	wd :=	ComObjCreate("Word.Application"), doc :=	wd.Documents.Add(_,_,_,0)
	 , doc.Content.Paste() , doc.SaveAs(fileName), doc.Close(), wd.Quit()
;MsgBox, % Clipboard
;}

}
Clipboard := t
return

Код всего скрипта.

#singleinstance force
;SetKeyDelay,0
;SetWinDelay,2000

~lButton & RButton::
global xbut := 0
translate()
return

translate()
{
   ;ToolTip, xb %xbut%
  
   
	;Gui +LastFound
;KeyWait, lButton , u
if xbut = 0
{
   ;released := 0
;Loop {
        
 ;           If (!getkeystate("lButton", "P") AND !getkeystate("RButton", "P"))
  ;          {
   ;            ToolTip, released = 1
    ;        Sleep, 1000
     ;            break
      ;     }
       ;   Sleep 10
     ;}
     
     ;sendinput,{rbutton up}
;}
;sleep, 100
;send,{rbutton up}
;send,{lbutton up}
global oCB := ClipboardAll ; save clipboard contents
Clipboard=
loop,30
{
sleep,10
} until !Clipboard
sendinput,{lbutton up}
sendinput,^{vk43}

loop,30
{
sleep,10
} until Clipboard
;ToolTip, %oCB% |||||||| clipboard
;Sleep, 2000
;Send, ^c
        ;ClipWait,1
;ToolTip, ctrl+c
}
;ToolTip, %clipboard%

;Send, ^c

if xbut = 0
{
var := clipboard
var1 := SubStr(var, 1, 5)
if RegExMatch(var1, "[a-zA-Z]")
   global lang := "ru"
else
  global lang := "en" 
   ;ToolTip, xbut_o lang is %lang%
   ;Sleep, 1000
}

  if xbut = 1
   {
      ;ToolTip, lang is %lang%
      if lang = ru
     global lang := "en" 
     else
     global lang := "ru" 
     ;xbut := 0
     gui, destroy
     ;Sleep, 1000
     ;ToolTip, lang is %lang%
     global xbut := 0
  }

;GoogleTranslate(Clipboard, "auto", "ru")
;MsgBox, %ClipboardAll% `n%clipboard%
global t
global str
;asd := Clipboard
t := GoogleTranslate(Clipboard, "auto", lang)
if !t
   Loop, 5
   {
      Sleep, 1000
      t := GoogleTranslate(Clipboard, "auto", lang)
      ;ToolTip, жду перевод
   }
until if t
Gui +LastFound
Gui, Font, cFFFF00 s16 ;, Verdana
loop, parse, clipboard, `n, `r
max := a_index

;msgbox,Total Characters=%a%
;msgbox %max%
if max < 2
{
   Loop, Parse, clipboard
     a++
if a < 100
   row := 1
if a > 100
   row := 2
if a > 200
   row := 2
if a > 300
   row := 3
if a > 400
   row := 4
if a > 500
   row := 5 
if a > 600
   row := 6
if a > 700
   row := 7
if a > 800
   row := 8
if a > 900
   row := 9
Gui, Font, cFFFF00 s16 ;, Verdana
Gui, Add, Edit, vstr -E0x200  r%row%, %t% `n
;ToolTip, 1 %t%
 }
 else
{
   ;ToolTip, 2 %t%
   Gui, Font, cFFFF00 s16 ;, Verdana
   Gui, Add, Edit, vstr -E0x200  , %t% `n
}
 a :=
 row :=
;sleep, 1000


;Gui, Font, cFFFF00 s16, Verdana
Gui, Color, 000000, 000000
Gui, Add, Text,  x0 y0  0x9 gGuiMove  ; Use a picture control instead
;Gui Margin, 1000, 0




gui, show, AutoSize, Translit
Gui +LastFound 
WinSet, Transparent, 200
WinSet, ExStyle, ^0x80,
;WinSetTitle,test,,%a_space%
 ControlSend,,{left}, Translit
Gui,  +AlwaysOnTop +Resize + DPIScale -Caption -Border -SysMenu  -ToolWindow ;-0x400000
GuiSize:
If A_EventInfo = 1
Return
GuiControl Move, str, % "H" . (A_GuiHeight) . " W" . (A_GuiWidth)
;GuiControl Move, str1, % "H" . (A_GuiHeight) . " W" . (A_GuiWidth)
;sleep, 3000
ControlGetText, OutputVar, Edit1, ahk_exe translate_tooltip_x64.exe
if OutputVar =
   gui, show, AutoSize, Translit
;ClipBoard := oCB ; return original Clipboard contents
return
}
return
;If ( Win_Class = "Shell_TrayWnd" OR Win_Class = "ProgMan" OR Win_Class = "AltDesk1.x" )
;#if !MouseIsOver("Translit")
;#IfWinExist, Translit

;( (MouseIsOver != "Translit") AND (WinExist = "Translit") )
#If WinExist("Translit") AND !MouseIsOver("Translit")
~lbutton::
{
   if !MouseIsOver("Translit")
   {
   gui, destroy
   if (t = clipboard)
   ClipBoard := oCB ; return original Clipboard contents
   ToolTip
   return
   }
}

#If WinExist("Translit")
XButton1::
;gui, destroy
global xbut := 1
 ClipBoard := t ; copy translate to Clipboard
 if MouseIsOver("Translit")
{
 ControlGetText, OutputVar, Edit1, ahk_exe translate_tooltip_x64.exe
 ClipBoard := OutputVar
}
translate()
return

XButton2::
;gui, destroy

 ClipBoard := t ; copy translate to Clipboard
 ;if MouseIsOver("Translit")
{
 ControlGetText, OutputVar, Edit1, ahk_exe translate_tooltip_x64.exe
 ClipBoard := OutputVar
}
 gui, destroy
                                      		; Long press (> 0.5 sec) on * substitutes the dot multiply
    KeyWait, XButton2, T0.2                               	; Wait no more than 0.5 sec for key release (also suppress auto-repeat)
    If ErrorLevel {                                    	; timeout, so long press
        KeyWait XButton2
        Send, ^{vk56}  
         sleep, 1000
         if (t = clipboard)
 ClipBoard := oCB ; return original Clipboard contents        
                  } Else                                                	; otherwise...
  {                              
		 Send, ^{vk56}

}
return

^s::
MouseGetPos,,, WinUMID
WinActivate, ahk_id %WinUMID%
WinGetActiveTitle, win
Clip := SubStr(win, 1, 195)
haystack := clip
    needle := "[\?<>/\\\*""|:]"
    replacement := "_"
   ;msgbox, % winc := RegExReplace(haystack, needle, replacement)
   winc := RegExReplace(haystack, needle, replacement)
;name = %OutDir%\%winc% %OutNameNoExt%.%OutExtension%
;MsgBox, % clipboard "`n" t
;FileAppend, %t%, test.rtf
	clipb := Clipboardall
    ;sleep, 4000
;MsgBox, % Clipboard
;b := Clipboard
Clipboard=
loop,30
{
sleep,10
} until !Clipboard

Clipboard := clipb "`n" t
loop,700
{
sleep,10
} until Clipboard

;Sleep, 5000
;{
;MsgBox, % Clipboard
saveAsWordDoc("C:\staff\screentextshot" "\" winc ".docx")
saveAsWordDoc(fileName) {	
;Sleep, 5000
;MsgBox, % Clipboard
	static	_ :=	ComObjMissing()
	wd :=	ComObjCreate("Word.Application"), doc :=	wd.Documents.Add(_,_,_,0)
	 , doc.Content.Paste() , doc.SaveAs(fileName), doc.Close(), wd.Quit()
;MsgBox, % Clipboard
;}

}
Clipboard := t
return

#If WinExist("Translit") AND MouseIsOver("Translit")
rbutton::
gui, destroy
if (t = clipboard)
ClipBoard := oCB ; return original Clipboard contents
return

#If WinExist("Translit") AND MouseIsOver("Translit")
~mbutton::
if triger = 
{
gui, show, maximize, Translit
triger = 1
}
else
   {
gui, show, restore, Translit
triger = 
}
return


MouseIsOver(WinTitle) {
MouseGetPos, , , Win
return WinExist(WinTitle . " ahk_id " . Win)
}

GuiMove:

PostMessage, 0xA1, 2,,, A

Return





GoogleTranslate(str, from := "auto", to := "en")  {
   static JS := CreateScriptObj(), _ := JS.( GetJScript() ) := JS.("delete ActiveXObject; delete GetObject;")
   
   json := SendRequest(JS, str, to, from, proxy := "")
   oJSON := JS.("(" . json . ")")

   if !IsObject(oJSON[1])  {
      Loop % oJSON[0].length
         trans .= oJSON[0][A_Index - 1][0]
   }
   else  {
      MainTransText := oJSON[0][0][0]
      Loop % oJSON[1].length  {
         trans .= "`n+"
         obj := oJSON[1][A_Index-1][1]
         Loop % obj.length  {
            txt := obj[A_Index - 1]
            trans .= (MainTransText = txt ? "" : "`n" txt)
         }
      }
   }
   if !IsObject(oJSON[1])
      MainTransText := trans := Trim(trans, ",+`n ")
   else
      trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")

   from := oJSON[2]
   trans := Trim(trans, ",+`n ")
   Return trans
}

SendRequest(JS, str, tl, sl, proxy) {
   ComObjError(false)
   http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
   ( proxy && http.SetProxy(2, proxy) )
   http.open( "POST", "https://translate.google.com/translate_a/single?client=webapp&sl="
      . sl . "&tl=" . tl . "&hl=" . tl
      . "&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=0&ssel=0&tsel=0&pc=1&kc=1"
      . "&tk=" . JS.("tk").(str), 1 )

   http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
   http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
   http.send("q=" . URIEncode(str))
   http.WaitForResponse(-1)
   Return http.responsetext
}

URIEncode(str, encoding := "UTF-8")  {
   VarSetCapacity(var, StrPut(str, encoding))
   StrPut(str, &var, encoding)

   While code := NumGet(Var, A_Index - 1, "UChar")  {
      bool := (code > 0x7F || code < 0x30 || code = 0x3D)
      UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
   }
   Return UrlStr
}

GetJScript()
{
   script =
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());

      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
      }

      function tk(a) {
          for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
              var c = a.charCodeAt(f);
              128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
              (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
              g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
          }
          a = h;
          for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
          a = b(a, "+-3^+b+-f");
          a ^= Number(e[1]) || 0;
          0 > a && (a = (a & 2147483647) + 2147483648);
          a `%= 1E6;
          return a.toString() + "." + (a ^ h)
      }
   )
   Return script
}

CreateScriptObj() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
}

Post's attachments

Ascorbic acid _ Real Bread Campaign - www.sustainweb.org_realbread_ascorbic_acid_ - Mozilla Firefox.docx 13.06 kb, 3 downloads since 2020-02-04 

You don't have the permssions to download the attachments of this post.

2

Re: AHK: текст с форматированием + без форматирования в clipboard

Не пойму, почему всё так сложно. Чтобы сохранить веб-страничку, нужно в браузере нажать Ctrl+S. Сохраняем. Потом эту же страничку прогоняем через онлайн-переводчик и тоже сохраняем. Получаем две странички в формате html. Ну можно ещё в PDF или CHM.

3

Re: AHK: текст с форматированием + без форматирования в clipboard

ypppu, всё дело в скорости, сколько времени у вас на всё это уйдёт? Будете ли вы заниматься этим, если это отнимает столько времени?
В таком варианте как я пытаюсь сделать, пару кликов и всё готово.

4

Re: AHK: текст с форматированием + без форматирования в clipboard

А скорость измеряется в секундах или кликах?

5 (изменено: OmTatSat, 2020-02-04 22:31:01)

Re: AHK: текст с форматированием + без форматирования в clipboard

ypppu в км/ч)).
Если серьёзно, то какая разница? Важно сколько усилий нужно потратить. Чем меньше тем лучше, для меня так, на вкус и цвет конечно...

6

Re: AHK: текст с форматированием + без форматирования в clipboard

AutoHotkey умеет нажимать кнопки в браузере за тебя. Значит мною перечисленные операции можно повесить на 1 горячую клавишу. Одно нажатие - и дело в шляпе.

7

Re: AHK: текст с форматированием + без форматирования в clipboard

OmTatSat пишет:
clipb := Clipboardall
...
Clipboard := clipb "`n" t

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

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

8

Re: AHK: текст с форматированием + без форматирования в clipboard

ypppu уверен, что вы знаете как такое реализовать. Но мне всё же удобней именно такой вариант как предложил выше.
Пример: зашел на сайт, перевел текст, если интересен - хоткей и сохранил, не интересен ищу далее.

9

Re: AHK: текст с форматированием + без форматирования в clipboard

teadrinker а как это сделать правильно?
Или может можно в документ записать переменную вместо clipboard?

10

Re: AHK: текст с форматированием + без форматирования в clipboard

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

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

11

Re: AHK: текст с форматированием + без форматирования в clipboard

ypppu кстати, вы знаете как скормить гугл переводчику только часть выделенного сайта? Имею ввиду чтобы всё форматирование осталось.

12 (изменено: OmTatSat, 2020-02-05 06:05:07)

Re: AHK: текст с форматированием + без форматирования в clipboard

teadrinker получилось так, но не очень нравится, что перевод без форматирования(

	global clipb := t
    saveAsWordDoc("C:\staff\screentextshot" "\" winc ".docx")
	saveAsWordDoc(fileName) {	
	static	_ :=	ComObjMissing()
	wd :=	ComObjCreate("Word.Application"), doc :=	wd.Documents.Add(_,_,_,0)
	 , doc.Content.Paste() , wd.Visible := true , wd.Activate , wd.ActiveDocument.Content.InsertAfter(clipb) doc.SaveAs(fileName), doc.Close(), wd.Quit()
}

13

Re: AHK: текст с форматированием + без форматирования в clipboard

OmTatSat пишет:

ypppu кстати, вы знаете как скормить гугл переводчику только часть выделенного сайта? Имею ввиду чтобы всё форматирование осталось.

Вот, например, мы перевели сайт: http://translate.google.ru/translate?hl … Findex.php. Как сохранить всю страницу полностью я уже написал. Ещё есть два варианта:
1) ПКМ --> В этом фрейме --> Сохранить фрейм как
или
2) ПКМ --> Показать только этот фрейм --> дальше обычное сохранение страницы.
Таким образом сможете отрезать заголовок гугл-переводчика.

Ну ещё можно выделить интересующий фрагмент мышкой  --> ПКМ --> Исходный код выделенного фрагмента. Сохранённый код можно редактировать в Word, я об этом я выше упоминал.
Контекстные меню я написал для Mozilla Firefox, в Вашем веб-обозревателе они могут отличаться.

14

Re: AHK: текст с форматированием + без форматирования в clipboard

Для перевода всего сайта, можно пользовать. Правда с

ypppu пишет:

Исходный код выделенного фрагмента

там полная абракадабра при копипасте в документ.

15

Re: AHK: текст с форматированием + без форматирования в clipboard

teadrinker вы хорошо разбираетесь в api гугл переводчика, возможно ли отправить на перевод форматированный текст? Попробовал на сайте переводчика выбирать документ, в принципе - то, что нужно, перевело с форматированием. Только как отправить документ на перевод через ahk? И может можно просто форматированный текст переводить?

16 (изменено: teadrinker, 2020-02-05 14:46:51)

Re: AHK: текст с форматированием + без форматирования в clipboard

Думаю, нельзя. Когда Google переводит страницу сайта, он просто заменяет текст в тегах переводом. Как отправить документ — пока не знаю, не интересовался, попозже могу посмотреть.

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

17

Re: AHK: текст с форматированием + без форматирования в clipboard

Если отправлять документ, то надо сначала html перевести в pdf.

Возможно это по теме.
https://habr.com/ru/post/438588/

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

18

Re: AHK: текст с форматированием + без форматирования в clipboard

А о каком документе вопрос, html или Word?

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

19

Re: AHK: текст с форматированием + без форматирования в clipboard

Если ТС копирует текст с браузера, значит форматированный текст будет в буфере в html. А html документы google translate не поддерживает.

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

20

Re: AHK: текст с форматированием + без форматирования в clipboard

Html не поддерживает, или word?

Разработка AHK-скриптов:
e-mail dfiveg@mail.ru
Telegram jollycoder

21

Re: AHK: текст с форматированием + без форматирования в clipboard

DOC поддерживает. А зачем он нужен?

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

22

Re: AHK: текст с форматированием + без форматирования в clipboard

Сейчас посмотрел в DOCX форматирование лучше сохраняется чем в DOC, хотя не точно как в html. Есть способ конвертировать Html в DOCX?

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

23

Re: AHK: текст с форматированием + без форматирования в clipboard

MS Word умеет открывать HTML и сохранять в DOCX.

24

Re: AHK: текст с форматированием + без форматирования в clipboard

А зачем такие сложности?
Заменяйте html entities и отпраляйте на перевод - гугл не переводит таги.

25

Re: AHK: текст с форматированием + без форматирования в clipboard

Можешь код привести, чтобы перевести например этот html.


html = 
(
<html>
<body>
<h2 style="box-sizing: border-box; font-family: &quot;Work Sans&quot;, sans-serif; font-weight: 500; line-height: 1.1; color: rgb(51, 51, 51); margin-top: 20px; margin-bottom: 10px; font-size: 30px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">What function does ascorbic acid perform in baking?</h2><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Industrial loaf fabricators categorise ascorbic acid as a flour ‘improver’ or dough conditioner.  In the presence of oxygen, ascorbic acid becomes an oxidising agent and the ‘improvements’ to which it contributes include:</p><ul style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"><li style="box-sizing: border-box;">Strengthened gluten</li><li style="box-sizing: border-box;">Greater loaf volume</li><li style="box-sizing: border-box;">Finer crumb (i.e. smaller, more even cells/bubbles)</li><li style="box-sizing: border-box;">Increased tenderness of the crumb</li><li style="box-sizing: border-box;">Reduced crust thickness</li><li style="box-sizing: border-box;">Faster rising</li></ul><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">‘The net result of AA is to improve the ability of dough to retain gas (as seen by increased oven spring) and to yield bread with a finer (smaller average cell size) crumb cell structure. These changes also result in bread crumb that is softer to the touch yet has the resiliency to recover much of its original shape after compression. This helps to convey the impression of proved freshness to the consumer.’  Baking Problems Solved, p 55, S. Cauvain &amp; L. Young, Woodhead Publishing (2001)</p>
</body>
</html>
)
По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

26

Re: AHK: текст с форматированием + без форматирования в clipboard

Надо убрать html entities, отправить на перевод и потом удалить пробелы в тегах и удалить <тело>.

27

Re: AHK: текст с форматированием + без форматирования в clipboard

Не, непонимаю.



html = 
(
<html>
<body>
<h2 style="box-sizing: border-box; font-family: &quot;Work Sans&quot;, sans-serif; font-weight: 500; line-height: 1.1; color: rgb(51, 51, 51); margin-top: 20px; margin-bottom: 10px; font-size: 30px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">What function does ascorbic acid perform in baking?</h2><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Industrial loaf fabricators categorise ascorbic acid as a flour ‘improver’ or dough conditioner.  In the presence of oxygen, ascorbic acid becomes an oxidising agent and the ‘improvements’ to which it contributes include:</p><ul style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"><li style="box-sizing: border-box;">Strengthened gluten</li><li style="box-sizing: border-box;">Greater loaf volume</li><li style="box-sizing: border-box;">Finer crumb (i.e. smaller, more even cells/bubbles)</li><li style="box-sizing: border-box;">Increased tenderness of the crumb</li><li style="box-sizing: border-box;">Reduced crust thickness</li><li style="box-sizing: border-box;">Faster rising</li></ul><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">‘The net result of AA is to improve the ability of dough to retain gas (as seen by increased oven spring) and to yield bread with a finer (smaller average cell size) crumb cell structure. These changes also result in bread crumb that is softer to the touch yet has the resiliency to recover much of its original shape after compression. This helps to convey the impression of proved freshness to the consumer.’  Baking Problems Solved, p 55, S. Cauvain &amp; L. Young, Woodhead Publishing (2001)</p>
</body>
</html>
)

MsgBox % GoogleTranslate(html, "auto", "ru")




GoogleTranslate(str, from := "auto", to := "en")  {
   static JS := CreateScriptObj(), _ := JS.( GetJScript() ) := JS.("delete ActiveXObject; delete GetObject;")
   
   json := SendRequest(JS, str, to, from, proxy := "")
   oJSON := JS.("(" . json . ")")

   if !IsObject(oJSON[1])  {
      Loop % oJSON[0].length
         trans .= oJSON[0][A_Index - 1][0]
   }
   else  {
      MainTransText := oJSON[0][0][0]
      Loop % oJSON[1].length  {
         trans .= "`n+"
         obj := oJSON[1][A_Index-1][1]
         Loop % obj.length  {
            txt := obj[A_Index - 1]
            trans .= (MainTransText = txt ? "" : "`n" txt)
         }
      }
   }
   if !IsObject(oJSON[1])
      MainTransText := trans := Trim(trans, ",+`n ")
   else
      trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")

   from := oJSON[2]
   trans := Trim(trans, ",+`n ")
   Return trans
}

SendRequest(JS, str, tl, sl, proxy) {
   ComObjError(false)
   http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
   ( proxy && http.SetProxy(2, proxy) )
   http.open( "POST", "https://translate.google.com/translate_a/single?client=webapp&sl="
      . sl . "&tl=" . tl . "&hl=" . tl
      . "&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=0&ssel=0&tsel=0&pc=1&kc=1"
      . "&tk=" . JS.("tk").(str), 1 )

   http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
   http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
   http.send("q=" . URIEncode(str))
   http.WaitForResponse(-1)
   Return http.responsetext
}

URIEncode(str, encoding := "UTF-8")  {
   VarSetCapacity(var, StrPut(str, encoding))
   StrPut(str, &var, encoding)

   While code := NumGet(Var, A_Index - 1, "UChar")  {
      bool := (code > 0x7F || code < 0x30 || code = 0x3D)
      UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
   }
   Return UrlStr
}

GetJScript()
{
   script =
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());

      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
      }

      function tk(a) {
          for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
              var c = a.charCodeAt(f);
              128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
              (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
              g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
          }
          a = h;
          for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
          a = b(a, "+-3^+b+-f");
          a ^= Number(e[1]) || 0;
          0 > a && (a = (a & 2147483647) + 2147483648);
          a `%= 1E6;
          return a.toString() + "." + (a ^ h)
      }
   )
   Return script
}

CreateScriptObj() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
}

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

28

Re: AHK: текст с форматированием + без форматирования в clipboard

Я тестировал не через код, а вставил твой html в гугл переводчик - он мне выдал ошибку.
Я заменил в блокноте html entities, после чего опять отправил на перевод и получил его, но с пробелами в тегах.
После чего удалил эти пробелы, удалил таг <тело>, сохранил в html и открыл для проверки в броузере.

29

Re: AHK: текст с форматированием + без форматирования в clipboard

А как это в блокноте делать?

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

30

Re: AHK: текст с форматированием + без форматирования в clipboard

Простым Replace.

31

Re: AHK: текст с форматированием + без форматирования в clipboard

Malcev пишет:

Я заменил в блокноте html entities

Если по русски, то это как?

По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

32

Re: AHK: текст с форматированием + без форматирования в clipboard

https://www.w3schools.com/html/html_entities.asp
Но тут не все, можно погуглить и найти весь список.

33

Re: AHK: текст с форматированием + без форматирования в clipboard

Так не работает.

html = 
( 

<h2 style="box-sizing: border-box; font-family: &quot;Work Sans&quot;, sans-serif; font-weight: 500; line-height: 1.1; color: rgb(51, 51, 51); margin-top: 20px; margin-bottom: 10px; font-size: 30px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">What function does ascorbic acid perform in baking?</h2><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Industrial loaf fabricators categorise ascorbic acid as a flour ‘improver’ or dough conditioner.  In the presence of oxygen, ascorbic acid becomes an oxidising agent and the ‘improvements’ to which it contributes include:</p><ul style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"><li style="box-sizing: border-box;">Strengthened gluten</li><li style="box-sizing: border-box;">Greater loaf volume</li><li style="box-sizing: border-box;">Finer crumb (i.e. smaller, more even cells/bubbles)</li><li style="box-sizing: border-box;">Increased tenderness of the crumb</li><li style="box-sizing: border-box;">Reduced crust thickness</li><li style="box-sizing: border-box;">Faster rising</li></ul><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">‘The net result of AA is to improve the ability of dough to retain gas (as seen by increased oven spring) and to yield bread with a finer (smaller average cell size) crumb cell structure. These changes also result in bread crumb that is softer to the touch yet has the resiliency to recover much of its original shape after compression. This helps to convey the impression of proved freshness to the consumer.’  Baking Problems Solved, p 55, S. Cauvain &amp; L. Young, Woodhead Publishing (2001)</p>

)
 
MsgBox % html := TransformHTML(html)

MsgBox % GoogleTranslate(html, "auto", "ru")


TransformHTML(str) {
	Transform, str, HTML, %str%, 3 
	Return str
}
По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

34

Re: AHK: текст с форматированием + без форматирования в clipboard

Понятное дело.
Тебе надо  &quot; перевести в ", а ты этой командой делаешь в точности наоборот.

35

Re: AHK: текст с форматированием + без форматирования в clipboard

Что то получилось.



html = 
( 
<h2 style="box-sizing: border-box; font-family: &quot;Work Sans&quot;, sans-serif; font-weight: 500; line-height: 1.1; color: rgb(51, 51, 51); margin-top: 20px; margin-bottom: 10px; font-size: 30px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">What function does ascorbic acid perform in baking?</h2><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">Industrial loaf fabricators categorise ascorbic acid as a flour ‘improver’ or dough conditioner.  In the presence of oxygen, ascorbic acid becomes an oxidising agent and the ‘improvements’ to which it contributes include:</p><ul style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;"><li style="box-sizing: border-box;">Strengthened gluten</li><li style="box-sizing: border-box;">Greater loaf volume</li><li style="box-sizing: border-box;">Finer crumb (i.e. smaller, more even cells/bubbles)</li><li style="box-sizing: border-box;">Increased tenderness of the crumb</li><li style="box-sizing: border-box;">Reduced crust thickness</li><li style="box-sizing: border-box;">Faster rising</li></ul><p style="box-sizing: border-box; margin: 0px 0px 10px; color: rgb(51, 51, 51); font-family: &quot;Work Sans&quot;, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">‘The net result of AA is to improve the ability of dough to retain gas (as seen by increased oven spring) and to yield bread with a finer (smaller average cell size) crumb cell structure. These changes also result in bread crumb that is softer to the touch yet has the resiliency to recover much of its original shape after compression. This helps to convey the impression of proved freshness to the consumer.’  Baking Problems Solved, p 55, S. Cauvain &amp; L. Young, Woodhead Publishing (2001)</p>
)
 
MsgBox % html := TransformHTML(html)

MsgBox % html := GoogleTranslate(html, "auto", "ru")
MsgBox % ClipBoard := html := RegExReplace(html, "<\s*/\s*(.*?)\s*>", "</$1>")

FileDelete, %A_Desktop%\test.html
FileAppend, %html%, %A_Desktop%\test.html
Run %A_Desktop%\test.html
ExitApp



TransformHTML(str) { 
	StringReplace, str, str, &quot;, ", 1
	StringReplace, str, str, &amp;, &, 1
	Return str
}



GoogleTranslate(str, from := "auto", to := "en")  {
   static JS := CreateScriptObj(), _ := JS.( GetJScript() ) := JS.("delete ActiveXObject; delete GetObject;")
   
   json := SendRequest(JS, str, to, from, proxy := "")
   oJSON := JS.("(" . json . ")")

   if !IsObject(oJSON[1])  {
      Loop % oJSON[0].length
         trans .= oJSON[0][A_Index - 1][0]
   }
   else  {
      MainTransText := oJSON[0][0][0]
      Loop % oJSON[1].length  {
         trans .= "`n+"
         obj := oJSON[1][A_Index-1][1]
         Loop % obj.length  {
            txt := obj[A_Index - 1]
            trans .= (MainTransText = txt ? "" : "`n" txt)
         }
      }
   }
   if !IsObject(oJSON[1])
      MainTransText := trans := Trim(trans, ",+`n ")
   else
      trans := MainTransText . "`n+`n" . Trim(trans, ",+`n ")

   from := oJSON[2]
   trans := Trim(trans, ",+`n ")
   Return trans
}

SendRequest(JS, str, tl, sl, proxy) {
   ComObjError(false)
   http := ComObjCreate("WinHttp.WinHttpRequest.5.1")
   ( proxy && http.SetProxy(2, proxy) )
   http.open( "POST", "https://translate.google.com/translate_a/single?client=webapp&sl="
      . sl . "&tl=" . tl . "&hl=" . tl
      . "&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=0&ssel=0&tsel=0&pc=1&kc=1"
      . "&tk=" . JS.("tk").(str), 1 )

   http.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
   http.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
   http.send("q=" . URIEncode(str))
   http.WaitForResponse(-1)
   Return http.responsetext
}

URIEncode(str, encoding := "UTF-8")  {
   VarSetCapacity(var, StrPut(str, encoding))
   StrPut(str, &var, encoding)

   While code := NumGet(Var, A_Index - 1, "UChar")  {
      bool := (code > 0x7F || code < 0x30 || code = 0x3D)
      UrlStr .= bool ? "%" . Format("{:02X}", code) : Chr(code)
   }
   Return UrlStr
}

GetJScript()
{
   script =
   (
      var TKK = ((function() {
        var a = 561666268;
        var b = 1526272306;
        return 406398 + '.' + (a + b);
      })());

      function b(a, b) {
        for (var d = 0; d < b.length - 2; d += 3) {
            var c = b.charAt(d + 2),
                c = "a" <= c ? c.charCodeAt(0) - 87 : Number(c),
                c = "+" == b.charAt(d + 1) ? a >>> c : a << c;
            a = "+" == b.charAt(d) ? a + c & 4294967295 : a ^ c
        }
        return a
      }

      function tk(a) {
          for (var e = TKK.split("."), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {
              var c = a.charCodeAt(f);
              128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ?
              (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240,
              g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
          }
          a = h;
          for (d = 0; d < g.length; d++) a += g[d], a = b(a, "+-a^+6");
          a = b(a, "+-3^+b+-f");
          a ^= Number(e[1]) || 0;
          0 > a && (a = (a & 2147483647) + 2147483648);
          a `%= 1E6;
          return a.toString() + "." + (a ^ h)
      }
   )
   Return script
}

CreateScriptObj() {
   static doc
   doc := ComObjCreate("htmlfile")
   doc.write("<meta http-equiv='X-UA-Compatible' content='IE=9'>")
   Return ObjBindMethod(doc.parentWindow, "eval")
}
По вопросам возмездной помощи пишите на E-Mail: serzh82saratov@mail.ru Telegram: https://t.me/sergiol982
Win10x64 AhkSpy, Hotkey, ClockGui

36 (изменено: DD, 2020-02-08 17:58:07)

Re: AHK: текст с форматированием + без форматирования в clipboard

Malcev пишет:

Заменяйте html entities и отпраляйте на перевод - гугл не переводит таги.

Он таки лезет в теги и иногда переводит ссылки и расставляет в них пробелы и тп. Причем, помню был какой-то спец тег из документации (вроде, <no-translate>), обёрнутое в который якобы не переводилось, но это тоже не работало. Но если предварительно убрать "=" из ссылок, тогда такие ссылки не трогались.

37

Re: AHK: текст с форматированием + без форматирования в clipboard

По последнему коду serzh82saratov видно, что все равно пробелы расставляются в тегах.

38

Re: AHK: текст с форматированием + без форматирования в clipboard

teadrinker пишет:

А о каком документе вопрос, html или Word?

word подойдёт, научился его сохранять с форматированием правда без цветного раскрашивания.

39

Re: AHK: текст с форматированием + без форматирования в clipboard

serzh82saratov пишет:

DOC поддерживает. А зачем он нужен?

docx тоже? Как отправить документ на перевод гуглу? В принципе doc тоже наверно сойдёт, но лучше docx, для него у меня уже есть код сохранения выделенного в документ.

40 (изменено: OmTatSat, 2020-02-12 19:50:13)

Re: AHK: текст с форматированием + без форматирования в clipboard

Получилось такой формат получить,  это очень удобный вариант.

Проблема в том, что делается он двумя этапами.
1. Выделяется область, хоткей, ждём встраивания перевода в интернет страницу.
Проблема - выделение текста сбилось.
2. Выделяется область уже с переводом, хоткей, и через пару секунд на компе лежит файл для важных текстов.

Первая часть с помощью дополнения https://addons.mozilla.org/ru/firefox/a … translator
Вторая часть с помощью https://addons.mozilla.org/ru/firefox/addon/single-file

Было бы здорово, чтобы не нужно было выделять текст дважды, ну и хоткей нажимать единожды.
Как такое реализовать пока не понимаю((
https://i.ibb.co/qR9ytDr/Ascorbic-acid-Real-Bread-Campaign-www-sustainweb-org-realbread-ascorbic-acid-Mozilla-Firefox-02-12-2020-17-43-19.png

41 (изменено: DD, 2020-04-29 05:20:24)

Re: AHK: текст с форматированием + без форматирования в clipboard

Для перевода с форматированием, подумалось сделать следующее: во взятом на перевод фрагменте текста, перед всеми тегами расставляются последовательные числа в квадратных скобках, потом из номеров с тегами составляется список, а теги в самом фрагменте удаляются, после чего текст можно переводить (при этом номера в квадратных скобках не будут затрагиваться) и следом — вернуть теги в текст, заменив из сохранённого списка. В коде ниже сделал первые два шага. Каким будет дополнение для замены номеров из текста — на теги из сохранённого списка?

html = 
( 
<p>El cadáver y los gusanos.
Las convulsiones que preceden al colapso institucional  que tienen como telón de fondo y causa primera la vida religiosa – se traducen en:<span id="more-11512"></span> una crisis económica y monetaria, la quiebra de la Unión Europea en respuesta a la transferencia de la soberanía de las naciones a las instituciones supranacionales, la deslegitimación del poder político en Francia y en el resto de Europa la intensidad y frecuencia de las sacudidas sísmicas están aumentando constantemente y las apelaciones a la reforma de las instituciones europeas <a href="#1" name="n1">[1]</a> y de la República francesa <a href="#2" name="n2">[2]</a> para salvarlas se multiplican desde hace una quincena de años.&#8211;</p> 

)

;ВСТАВКА ПОСЛЕДОВАТЕЛЬНЫХ НОМЕРОВ ПЕРЕД ТЕГАМИ
match := ""
while RegExMatch(html, "iO)((<[^>]*>)+)", match, match ? match.Pos + match.Len + 14 : 1)
{
   n := Format("{:0" . 10 . "u}", a_index)
   html := RegExReplace(html, match[0], "[" . n . "]" . match[0],, 1, match.Pos)
}
MsgBox % html 

;ПОЛУЧЕНИЕ СПИСКА НОМЕР+ТЕГ
Pos = 1
While ( Pos := RegExMatch(html, "(\[\d{10}\](<[^>]*>)+)", Found, Pos + StrLen(Found)) )
    tags_list .= Found . "`n"

MsgBox % tags_list

42

Re: AHK: текст с форматированием + без форматирования в clipboard

Вот

Loop, Parse, tags_list, `n, `r
{
   tag_line := A_LoopField
   If NOT InStr(tag_line, "[")
      break
   num := RegExReplace(tag_line, "(\[\d{10}\])((<[^>]*>)+)", "$1")
   tag := RegExReplace(tag_line, "(\[\d{10}\])((<[^>]*>)+)", "$2")

   StringReplace, html, html, %num%, %tag%, All
}

43 (изменено: DD, 2020-05-05 22:15:41)

Re: AHK: текст с форматированием + без форматирования в clipboard

DD пишет:

после чего текст можно переводить (при этом номера в квадратных скобках не будут затрагиваться)

Для заменяемых тегов лучше всего использовать %3F, иногда удаляя пробелы между. Всё остальное после перевода частично изменяется или удаляется.