Posting Large Samples of Code

Hello.

When I post code, I want it nice and neat (and easy to scroll past).

I learned how to make it only so high, with a scrollbar:

http://textadventures.co.uk/forum/questkit/topic/d5gbwotaauiavzskhqaxtg/quest-6-object-links-hack-in-progress#df9f8840-0d5c-430d-96ec-d1ce4ac48e10

...but I couldn't figure out how to stop the word-wrapping. white-space: nowrap made a 200 line bit of code turn into one long line of text. I admit that it did let me scroll left and right at that point, but I wish to keep my line-breaks.

This is what I'm doing:

<div id"code-div" style="max-height:200px;overflow:scroll">

```
code goes here

```

</div>

Any advice on how to control my code's overflow?


EDIT

I tried it with <pre><code> instead of ```, too, but it acted the same way either way.


<pre id"code-div" style="max-height:100px;overflow:scroll;"><code style="white-space: pre">

here's some code

</code></pre>



Thank you!  I've been driving myself crazy trying to figure this out and it has been driving me so crazy that I'm writing run-on sentences but now I think I'm okay.


Well, that looked like I wanted it to look before I actually posted it . . .

I hate it when the forum does that.


I'm playing around with the CSS trying to get this to behave… But not being able to see the result without posting, and the stupid "You can't post that here" message make it really annoying.

Think I got it now

Hmm does it not work like it's supposed to? I only tested it in the preview so it's hard to be sure. Can't wait to see what this looks like when actually posted. Especially if I put in an even longer line to make sure it doesn't give the page a horizontal scroll bar.

The hardest thing with this method is that you need to be careful with the line breaks.
Like, if you want your code to come to the top of the box, it has to start on the same line as the <pre>, which is easy to forget.

Also worth noting is that you can use "overflow:auto",
   which is like scroll
      but only shows the scroll bars
         if the text is big enough to need them
let's compare that to a standard ``` block, just to see if my style changes anything else that might not be so obvious at a casual glance

[MANIACAL LAUGH]

This is good, stuff, right here!

I needed a good laugh.


Seems to behave :p

The post above uses:

<pre id"code-div" style="max-height:300px;overflow:auto;max-width:1054px;"><code style="white-space: pre;">

If I just use ``` then it seems to grow up to 1054px; so I used the same number. No idea if this is a fixed constant or is programatically generated somewhere I can't see.


Awesome!

Testing . . .

"use strict"


//====================
// OBJECT LINKS LIB  |
//====================
// by KV             |
//====================
// for QuestJS v 0.3 |
//====================
// Version 1         |
//====================

/*
 * IMPORTANT!!!
 * ------------
 * 
 * Make sure you have modifed DEFAULT_ROOM.description and placed the code block in the
 * code so the changes are loaded BEFORE ANY ROOMS ARE CREATED during game load!!!
 * 
 * Normally, this should go in data.js, above any code that creates any rooms.
 * 
 * Here is the code:
------------------------------------------------------------------

// CODE BEGINS

DEFAULT_ROOM.description = function() {
    if (game.dark) {
      printOrRun(game.player, this, "darkDesc");
      return true;
    }
    if(settings.linksEnabled){
		disableExistingObjectLinks()
	}
    for (let line of settings.roomTemplate) {
      msg(line);
    }
    return true;
}

// END OF CODE

--------------------------------------------------------------------
 * 
 */



//============================================================================


//Capture clicks for the objects links
settings.clickEvents = [{one0:`_PLACEHOLDER_`}]
window.onclick = function(event) {
	if (!event.target.matches('.droplink')) {
		$(".dropdown-content").hide();
	}else{
		settings.clickEvents.unshift(event.target)
		if (typeof(settings.clickEvents[1].nextSibling)!=='undefined' &&  settings.clickEvents[1].nextSibling!==null){
			if (settings.clickEvents[1] !== event.target && settings.clickEvents[1].nextSibling.style.display==="inline" && event.target.matches('.droplink')){
				$(".dropdown-content").hide();
				event.target.nextSibling.style.display="inline"
			}
		}
	}
}


//===================================

// SETTINGS

settings.roomTemplate = [
  "{hereDesc}",
  "{objectsHere:You can see {objectsLinks} here.}",
  "{exitsHere:You can go {exits}.}",
]

settings.linksEnabled = true


// Make it easy to find a command's opposite
settings.cmdOpps = {
	"Switch on":"Switch off",
	"Switch off":"Switch on",
	"Take":"Drop",
	"Drop":"Take",
	"Wear":"Remove",
	"Remove":"Wear",
	"Open":"Close",
	"Close":"Open",
}

// END OF SETTINGS


// TURNSCRIPT

createItem("updateDropdownVerblists_Turnscript",{
	eventPeriod:1,
	eventActive:true,
	eventScript:()=>{
		if(settings.linksEnabled){
			updateDropdownVerblists()
		}else{
			w.updateDropdownVerblists_Turnscript.eventActive = false
		}
	},
})



//===========================
// TEXT PROCESSOR ADDITIONS |
//===========================

tp.text_processors.objectsHereLinks = function(arr, params) {
  //let listOfOjects = scopeHereListed();
  //let objArr = []
  //listOfOjects.forEach(o=>{
	  //let ol = getObjectLink(o,true)//Adding true arg to mark this is for objectsHereLinks!!!
	  //objArr.push(ol)
  //})
  //listOfOjects = objArr
  let listOfOjects = scopeHereListed().map(o => getObjectLink(o,true))
  return listOfOjects.length === 0 ? "" : arr.join(":");
};

tp.text_processors.objectsLinks = function(arr, params) {
  //const listOfOjects = scopeHereListed();
  //let objArr = []
  //listOfOjects.forEach(o=>{
	  //let ol = getObjectLink(o,true)
	  //objArr.push(ol)
  //})
  let objArr = scopeHereListed().map(o => getObjectLink(o,true))
  return formatList(objArr, {article:INDEFINITE, lastJoiner:lang.list_and, modified:true, nothing:lang.list_nothing, loc:game.player.loc});
}

tp.text_processors.objectLink = function(obj, params) {
	return getObjectLink(w[obj[0]],false,false)
}

//=================================
// END OF TEXT PROCESSOR ADDITIONS |
//==================================



// FUNCTIONS
// ---------

function capFirst(string) {
    return string.charAt(0).toUpperCase() + string.slice(1)
}


function getDisplayAlias(obj,art=INDEFINITE){
	return lang.getName(obj,{article:art})
}


// NOTE: getAlias is not used by any function in this library.
function getAlias(obj){
	return obj.alias || obj.name
};

function enterButtonPress(cmd){
	//Calling this function with no arg will cause s to default to the text in the textbox.
	if(cmd) $('#textbox').val(cmd)
	const s = $('#textbox').val();
    io.msgInputText(s); //This emulates printing the echo of the player's command
    if (s) {
		if (io.savedCommands[io.savedCommands.length - 1] !== s) {
			io.savedCommands.push(s);
        }
        io.savedCommandsPos = io.savedCommands.length;
        parser.parse(s);
        $('#textbox').val('');
	}
};

function clickedCmdLink(s){
	if (s) {
		if (io.savedCommands[io.savedCommands.length - 1] !== s) {
		  io.savedCommands.push(s);
		}
		io.savedCommandsPos = io.savedCommands.length;
	}
}

function getObjectLink(obj,isScopeHere=false,addArticle=true){
	//if isScopeHere is sent true, this is for a room description!
	if(settings.linksEnabled){
		var roomClass = isScopeHere ? "room-desc" : ""
		var oName = obj.name
		var id = obj.alias || obj.name;
		var prefix = "";
		if (obj.prefix){
			prefix = obj.prefix+" ";
		}
		var dispAlias = getDisplayAlias(obj)
		if (addArticle) {prefix = dispAlias.replace(obj.alias,'')}
		disableObjectLink($(`[obj="${oName}"]`))
		var s = prefix+``;
		s +=`${id}`;
		s += ``;
		let verbArr = obj.getVerbs()
		if (verbArr.length>0){
			verbArr.forEach (o=>{
				o = capFirst(o)
				s += `${o}`;
			})
		}
		s += "";
		return s;
	}else{
		var s = obj.alias || obj.name;
		return s
	}
};

function toggleDropdown(element) {
    $("#"+element+"").toggle();
}
 
function handleObjLnkClick(cmd,el,verb,objAlias){
	parser.msg("handleObjLnkClick:  Handling object link click . . .")
	parser.msg("cmd: "+cmd)
	parser.msg("verb: "+verb)
	parser.msg("objAlias: "+objAlias)
	parser.msg("Sending to enterButtonPress . . .")
	enterButtonPress(cmd)
}

function updateDropdownVerblists(){
	//parser.debug = true
	let verbEls = $("[link-verb]")
	Object.keys(verbEls).forEach(i => {
		let el = verbEls[i]
		//if(parser.debug) {
			//console.log("verbEls"); 
			//console.log(typeof(verbEls));
			//console.log(verbEls);
			//console.log("verbEls[i]");
			//console.log(verbEls[i])
			//console.log("el");
			//console.log(typeof(el));
			//console.log(el);
			//console.log(el[0]);
			//console.log(typeof(el[0]));
		//}
		let verb = $(el).attr("link-verb")
		if(!verb) return
		let verbOpp = settings.cmdOpps[verb] || null
		if(!verbOpp) {
			//if(parser.debug) {console.log("NO opposite for " + verb)}
			return
		}
		//if(parser.debug) {console.log("i:");console.log(i);console.log("el:");console.log(el);console.log("verb:");console.log(verb);console.log("verbOpp");}
		let objName = $(el).attr("obj")
		//if(parser.debug) {console.log("objName:");console.log(objName);console.log("obj:");}
		let obj = w[objName]
		//if(parser.debug) {console.log(obj);var hr = "=======================================";console.log(hr);console.log("Do the verbs match the getVerbs? . . .");console.log(hr);}
		if(!obj.getVerbs) return
		var objGetVerbs = obj.getVerbs()
		//if(parser.debug) {console.log("objGetVerbs:");console.log(objGetVerbs);}
		objGetVerbs.forEach(newVerb => {
			//if(parser.debug) {console.log("Checking getVerbs() for " + objName + " . . .");console.log(newVerb);}
			if (verbOpp != newVerb) return
			//if(parser.debug) {console.log("Found one!");console.log(objName + " needs " + verb  + " changed to " + newVerb + "!");}
			if(!el.parentElement){
				//if(parser.debug){ console.log("No element parent element.  QUITTING!");} 
				return
			}
			//Change the verb to its opposite!
			switchDropdownVerb(el,newVerb,objName)
			//if(parser.debug) {console.log("DONE!")}
			return true
			
		})
	})
}

function switchDropdownVerb(el, newVerb, objName){
	if (!objName) {let objName = $(el).attr("obj")}
	let oldVerb = $(el).attr("link-verb")
	if (!newVerb) {let newVerb = settings.cmdOpps[oldVerb]}
	let str = el.parentElement.innerHTML
	let regexp = new RegExp(oldVerb,'g')
	let repl = str.replace(regexp,newVerb);
	el.parentElement.innerHTML = repl
	$(el).attr("link-verb",newVerb)
	//parser.msg(`Replaced '${oldVerb}' on ${objName} with '${newVerb}'.`)
}

function disableExistingObjectLinks(bool=false){
	//if bool is false, this only disables existing object links printed using the room description function
	//if bool is true, this disables ALL existing object links
	//parser.msg("running disableExistingObjectLinks!")
	//Checks that this doesn't remove "good" links.
	if (bool){
		$(".droplink").removeClass("droplink").css("cursor","default").attr("name","dead-droplink")
		$(".object-link").removeClass("dropdown")
		$(".dropdown").removeClass("dropdown")
		$(".dropdown-content").remove()
	} else {
		$(".room-desc.droplink").removeClass("droplink").css("cursor","default").attr("name","dead-droplink")
		$(".room-desc.object-link").removeClass("dropdown")
		$(".room-desc.dropdown").removeClass("dropdown")
		$(".room-desc.dropdown-content").remove()
	}
}

function disableObjectLink(el){
	let objName = $(el).attr("obj")
	$(el).removeClass("droplink").css("cursor","default").attr("name","dead-droplink")
	$(el).removeClass("dropdown")
	$(el).removeClass("dropdown")
	$(`#${objName}`).remove()
}

This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums