Модуль:Не переведено

Документация

Служит для работы шаблонов {{не переведено}}, {{не переведено 2}}, {{не переведено 3}}, {{не переведено 4}} и {{не переведено 5}}.

См. также: Модуль:Не переведено/песочница (сравнить) и Шаблон:Не переведено/тесты.

TODO

  • внешний вид нп3
  • возможно, что-то с nil из [1]
local p = {}local categories = {['error'] = 'Википедия:Статьи с некорректно заполненным шаблоном Не переведено',['outdated'] = 'Википедия:Статьи с неактуальным шаблоном Не переведено',['redirect'] = 'Википедия:Запросы на замену перенаправлений переводами',['unknown'] = 'Википедия:Статьи с неизвестными параметрами шаблонов серии Не переведено',['semiold'] = 'Википедия:Статьи с полустарым синтаксисом в шаблонах серии Не переведено',['probably_wrong'] = 'Википедия:Статьи с предположительно неверными параметрами в шаблонах серии Не переведено',['lang-not-exists'] = 'Википедия:Статьи с шаблоном Не переведено 2, использующие несуществующий шаблон lang-XX',}local function is_empty(param)return param == nil or param == ''endlocal function is_wikidata(lang)return lang == 'd'endlocal function getTitle(page, iw_title, is_wikidata_link)local success, result = pcall(function()if is_wikidata_link thenlocal entity = mw.wikibase.getSitelink(iw_title)if entity ~= nil thenreturn {title = entity,exists = true,-- предположение, что в Викиданных не перенаправлениеisRedirect = false,}endreturn nilelselocal title = mw.title.new(page)return {title = page,exists = title.exists,isRedirect = title.isRedirect,}endend)if success thenreturn resultendreturn nilendlocal function wikilink(title, text, tooltip, lang, style, is_redirect)if is_empty(text) thentext = titleendif not is_empty(lang) and lang ~= 'ru' thentitle = string.format(':%s:%s', lang, title)endif is_wikidata(lang) thentitle = title .. '#sitelinks-wikipedia'endif not is_empty(tooltip) thentext = string.format('<span title="%s">%s</span>', tooltip, text)endif not is_empty(style) thentext = string.format('<span style="%s">%s</span>', style, text)endif is_redirect thenreturn string.format('<span class="plainlinks">[%s %s]</span>',tostring(mw.uri.fullUrl(title,'redirect=no')),text)elseif text ~= title thenreturn string.format('[[%s|%s]]', title, text)elsereturn string.format('[[%s]]', title)endendlocal function addMetadata(text, lang, article)return string.format('<span data-interwiki-lang="%s" data-interwiki-article="%s">%s</span>',lang, article, text)endlocal function throwError(text, category_code, allow_cat)local error = require('Module:Error').errorif category_code and allow_cat thenreturn error{text} .. '[[Category:' .. categories[category_code] .. ']]'elsereturn error{text}endendfunction p._subst(mode, title, text, lang, iw_text)-- Вывести выделение строки за её пределамиlocal selOffset = mw.ustring.find( text, "''" )local sel = ''if selOffset ~= nil and selOffset == 1 thenlocal oldText = texttext = mw.text.trim( text, "'" )sel = mw.ustring.rep( "'", ( mw.ustring.len( oldText ) - mw.ustring.len( text ) ) / 2 )endlocal result = sel .. wikilink(title, text) .. sel-- Вывести содержимое скобок в не переведено 2if mode == 2 thenlocal iw_link = '{{lang-' .. lang .. '|' .. iw_text .. '}}'if is_empty(addition) thenreturn string.format('%s (%s)', result, iw_link)elsereturn string.format('%s (%s; %s)', result, iw_link, addition)endendreturn resultendfunction p.main(frame)local yesno = require('Module:Yesno')local getArgs = require('Module:Arguments').getArgslocal languages = mw.loadData('Module:Languages/data')local prepositional = require('Module:Languages')._transform_langlocal args = getArgs(frame)local categories_list = {}local nocat = yesno(args['nocat'])local allow_cat = (mw.title.getCurrentTitle().namespace == 0or mw.title.getCurrentTitle().namespace == 10) and not nocat-- определение какой из шаблонов "не переведено N"local mode = tonumber(args['mode'])mode = mode == 2 and 2 or 5local template_name = 'Не переведено'if mode ~= 5 thentemplate_name = template_name .. ' ' .. tostring(mode)end-- проверка на неизвестные параметрыlocal redundant_params = {}local good_params = {'mode', 1, 2, 3, 4, 'l', 'leave', 'r', 'q', 'nocat'}if mode == 2 thentable.insert(good_params, 5)table.insert(good_params, 'text')table.insert(good_params, 'текст')endfor k, _ in pairs(args) dolocal is_good_param = falsefor _, v in pairs(good_params) do  if k == v then  is_good_param = true  endendif not is_good_param thentable.insert(redundant_params, k)endendif #redundant_params > 0 thentable.insert(categories_list, {'unknown', table.concat(redundant_params)})end-- получение параметров (кроме nocat)local title = args[1]local text = args[2]local lang = args[3]local iw_title = args[4]local iw_text = args[5]local quotes = yesno(args['q'])local addition = args['text'] or args['текст']local leave_always = yesno(args['l']) or yesno(args['leave'])local leave_if_redirect = yesno(args['r'])-- проверка правильности сырых параметровif not mw.isSubsting() thenif is_empty(title) thenreturn throwError('не указано название статьи', 'error', allow_cat)endif title:match('^:[a-z-]+:') thenreturn throwError('шаблон не поддерживает такой синтаксис', 'semiold', allow_cat)endif is_empty(lang) and not is_empty(iw_title) and iw_title:match('^[a-z][a-z]$') thentable.insert(categories_list, {'probably_wrong', nil})endend-- приведение параметров к нужному видуif is_empty(text) thentext = titleendif is_empty(lang) thenlang = 'en'elselang = mw.ustring.lower(lang)endif is_empty(iw_title) theniw_title = titleendif is_empty(iw_text) theniw_text = iw_titleend-- если используется с подстановкой, выбросить почти без обработкиif mw.isSubsting() thenreturn p._subst( mode, title, text, lang, iw_text )end-- получение страницы, чтобы знать, существует ли она и является ли она перенаправлениемlocal isWikidataLink = is_wikidata(lang)local considerAsExistslocal isRedirectlocal considerAsRedirectif leave_always then -- если задано |l=1, то ничего не проверять, потому что дорогоconsiderAsExists = falseisRedirect = falseconsiderAsRedirect = falseelse-- дорогая функция, после 500 вызова крашитсяlocal titleObject = getTitle(title, iw_title, isWikidataLink)if titleObject thentitle = titleObject.titleconsiderAsExists = titleObject.existsisRedirect = titleObject.isRedirectconsiderAsRedirect = isRedirect and not leave_if_redirectelse -- после 500 вызова или если в названии есть некорректные символыconsiderAsExists = falseisRedirect = falseconsiderAsRedirect = falseendend-- проверка правильности обработанных параметровif lang ~= 'd' and languages[lang] == nil thenreturn throwError('некорректный ISO-код «' .. lang .. '»', 'error', allow_cat)endif mode == 2 and isWikidataLink thenreturn throwError('шаблон Не переведено 2 не поддерживает Викиданные вместо языка')endif mode == 2 and not mw.title.new('Template:Lang-' .. lang).exists then -- дорогая функцияreturn throwError('не найден шаблон ' .. frame:expandTemplate{ title = 'tl', args = { 'lang-' .. lang } },'lang-not-exists', allow_cat)endif mode == 5 and considerAsRedirect thentable.insert(categories_list, {'redirect', nil})elseif considerAsExists thentable.insert(categories_list, {'outdated', nil})end-- всплывающая подсказка к ссылке на иноязычную статьюlocal iw_tooltiplocal ucfirst_title = mw.getContentLanguage():ucfirst(title)if isWikidataLink theniw_tooltip = string.format('Элемент статьи «%s» в Викиданных', ucfirst_title)elseiw_tooltip = string.format('%s — версия статьи «%s» на %s', iw_title, ucfirst_title, prepositional(lang))end-- формирование первой части - основной ссылкиlocal main_textif considerAsExists or mode == 1 or mode == 2 or mode == 5 thenmain_text = wikilink(title, text, nil, nil, nil, isRedirect)if not considerAsExists thenmain_text = addMetadata(main_text, lang, iw_title)endelsemain_text = wikilink(iw_title, text, iw_tooltip, lang)endif mode == 4 and quotes then -- TODO: все шаблоны или отключитьmain_text = '«' .. main_text .. '»'end-- формирование второй части - языковой меткиlocal post_text = ''if not (considerAsExists and not (isRedirect and leave_if_redirect)) or mode == 2 or (mode == 5 and considerAsRedirect) then-- для шаблона "не переведено"if mode == 1 thenlocal lang_textif isWikidataLink thenlang_text = 'ВД'elselang_text = languages[lang][1]endlocal iw_link = wikilink(iw_title, lang_text, iw_tooltip, lang)post_text = string.format('<span class="noprint" style="white-space: nowrap; font-size: 85%%;"> (%s)</span>',iw_link)-- для шаблона "не переведено 2"elseif mode == 2 thenlocal iw_link = ''if considerAsExists theniw_link = frame:expandTemplate{ title = 'lang-' .. lang, args = { iw_text } }elseiw_link = frame:expandTemplate{ title = 'lang-' .. lang, args = { wikilink(iw_title, iw_text, iw_tooltip, lang) } }endif is_empty(addition) thenpost_text = string.format(' (%s)', iw_link)elsepost_text = string.format(' (%s; %s)', iw_link,  addition)end-- для шаблона "не переведено 3"-- TODO: вынести всё это добро в TemplateStyleselseif mode == 3 thenlocal ref = string.format(-- неразрывный пробел на этой позиции предотвращает перенос перед элементом с display:inline-block в Хроме'<span style="font-size:117.6%%; margin-left:-0.43em; position:relative; top:0.28em;">%s</span>',frame:expandTemplate{title = 'ref-' .. (isWikidataLink and 'info' or lang),args = {isWikidataLink and 'ВД' or ''}})local ru_link = wikilink(title, 'рус.')if not considerAsExists thenru_link = addMetadata(ru_link, lang, iw_title)endru_link = string.format(-- position:absolute; позволяет точнее позиционировать пометку; иначе она «скачет», по крайней мере в Хроме'<span class="link-ru metadata" style="margin-left:-0.43em; position:absolute; left:0; z-index:1; margin-top:-0.35em;"><span style="visibility:hidden; margin-right:0.099em;">&nbsp;(</span>%s</span>',ru_link)post_text = string.format(-- размер шрифта и свойство display:inline-block указывается здесь из-за проблем с размерами шрифта в Хроме на Андроиде'&nbsp;<span style="display:inline-block; font-size:80%%; position:relative;">%s%s</span>',ref, ru_link)-- для шаблона "не переведено 4"elseif mode == 4 thenlocal styles = ''if lang == 'fr' thenstyles = 'margin-right:0.3em;'elseif lang == 'fi' thenstyles = 'margin-right:0.35em;'elseif lang == 'it' thenstyles = 'margin-right:0.5em;'endlocal ru_link = wikilink(title, 'ru', 'Статья «' .. title .. '» в русском разделе отсутствует')if not considerAsExists thenru_link = addMetadata(ru_link, lang, iw_title)endru_link = string.format('<sup style="margin-left:2px; position:relative; top:-1px;">%s</sup>',ru_link)local ref = string.format('<sub style="margin-left:-0.94em; %s" title="По ссылке доступна статья на %s">%s</sub>',styles, prepositional(lang), lang)post_text = string.format('%s%s', ru_link, ref)-- для шаблона "не переведено 5"elselocal langText = '[???]'if lang == 'd' thenlangText = '[вд]'elselangText = '[' .. ( languages[ lang ] and languages[ lang ][ 1 ] or lang ) .. ']'endpost_text = string.format('<sup class="noprint" style="font-style:normal; font-weight:normal;">%s</sup>',wikilink(iw_title, langText, iw_tooltip, lang))endend-- формирование третьей части - уведомления о существовании страницыlocal exist_message = ''if considerAsExists and not (isRedirect and leave_if_redirect) thenlocal exist_message_linkif mode == 5 thenif considerAsRedirect thenexist_message_link = 'Шаблон:' .. template_name .. '#Если существует перенаправление'elseexist_message_link = 'Шаблон:' .. template_name .. '#Если существует статья'endelseexist_message_link = 'Шаблон:' .. template_name .. '#Действия после появления страницы'endif mode == 5 and considerAsRedirect thenexist_message = string.format('<sup class="noprint" style="margin:0 0 0 1px;">%s</sup>',wikilink(exist_message_link, '*', 'Замените название перенаправления на название статьи либо уберите шаблон «' .. template_name .. '»', nil, 'color:red;'))elseexist_message = string.format('<sup class="noprint">%s</sup>',wikilink(exist_message_link, '?!', 'Уберите шаблон «' .. template_name .. '» из статьи и замените его простой вики-ссылкой', nil, 'color:red;'))endexist_message = string.format('<span style="font-style:normal; font-weight:bold;">%s</span>', exist_message)endlocal categories_text = ''if allow_cat thenfor _, category_data in pairs(categories_list) dolocal category_name = categories[category_data[1]]if category_data[2] ~= nil thencategory_name = category_name .. '|' .. category_data[2]endcategories_text = categories_text .. '[[Category:' .. category_name .. ']]'endendlocal resultif mode == 2 thenresult = main_text .. exist_message .. post_text .. categories_textelseresult = main_text .. post_text .. exist_message .. categories_textendreturn resultendreturn p